file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
91693_2 | package main;
import java.util.ArrayList;
public abstract class Creature {
protected String nom;
protected int age;
protected int sexe; // 0 = male; 1 = femelle
protected int poids; // En kg
protected int taille; // En cm
protected ArrayList<?> type = getTypeName(); // Nom de l'interface
protected int dureeDeVie = 50; // En années
protected int indicateurFaim = 0; // De 0 a 100
protected int indicateurSante = 100; // De 100 a 0
protected int indicateurSommeil = 0; // De 0 a 100
protected boolean dortIl = false;
protected boolean estMorte = false;
public static class InstanceManager {
private static final ArrayList<Creature> instances = new ArrayList<>();
private static void addInstance(Creature instance) {
instances.add(instance);
}
public static ArrayList<Creature> getAllInstances() {
return instances;
}
}
public Creature(String nom, int age, int sexe, int poids, int taille) {
this.nom = nom;
this.age = age;
this.sexe = sexe;
this.poids = poids;
this.taille = taille;
InstanceManager.addInstance(this);
}
public void manger() {
if (!estMorte){
if (!dortIl) {
System.out.println("Miam miam");
indicateurFaim+=0;
} else {
System.out.println(nom+" dort");
}
} else {
System.out.println(nom+" est "+accordMortMess());
}
}
public boolean emetUnSon() {
if (!this.estMorte) {
System.out.println(nom+" émet un son");
return true;
} else {
System.out.println(nom+" est "+accordMortMess());
return false;
}
}
public void soigner() {
if (!estMorte) {
this.indicateurSante = 100;
} else {
System.out.println(nom+" est "+accordMortMess());
}
}
public void sendormirOuSeReveiller() {
if (estMorte){
System.out.println(nom+" est "+accordMortMess());
} else {
dortIl = !dortIl;
indicateurSommeil=0;
}
}
public void vieillir(int annee) {
if ((this.age+annee)<dureeDeVie) {
this.age += annee;
} else if ((this.age+annee)==dureeDeVie) {
this.age += annee;
this.meurt();
} else {
this.age = dureeDeVie;
this.meurt();
}
}
public void meurt() {
if (!estMorte) {
this.estMorte = true;
if (Enclos.getListCreatureDansEnclos().contains(this)) {
System.out.println("Vous devez enlever le cadavre de "+nom+" de son enclos");
}
} else {
System.out.println(nom+" est déjà "+accordMortMess());
}
}
//setters
public void setIndicateurFaim(int indicateurFaim) {
this.indicateurFaim = indicateurFaim;
}
public void setIndicateurSante(int indicateurSante) {
this.indicateurSante = indicateurSante;
}
public void setIndicateurSommeil(int indicateurSommeil) {
this.indicateurSommeil = indicateurSommeil;
}
// Getters
public String getNom() {
return nom;
}
public String getSex() {
if (this.sexe==0){
return "Male";
} else if (this.sexe==1) {
return "Femelle";
} else {
return "Non défini";
}
}
public int getAge() {
return age;
}
public int getPoids() {
return poids;
}
public int getTaille() {
return taille;
}
public ArrayList<?> getType() {
return type;
}
public int getDureeDeVie() {
return dureeDeVie;
}
public int getIndicateurFaim() {
return indicateurFaim;
}
public int getIndicateurSante() {
return indicateurSante;
}
public int getIndicateurSommeil() {
return indicateurSommeil;
}
public boolean isDortIl() {
return dortIl;
}
public boolean isEstMorte() {
return estMorte;
}
protected String accordMortMess() {
if (sexe==1) {return "morte";}
else {return "mort";}
}
// Méthode pour obtenir le nom de l'interface
private ArrayList<?> getTypeName() {
Class<?>[] interfaces = this.getClass().getInterfaces();
ArrayList<String> interfaceNames = new ArrayList<>();
// Gestion du cas où la classe n'implémente aucune interface
if (interfaces.length > 0) {
for (Class<?> interfaceElem : interfaces) {
interfaceNames.add(interfaceElem.getSimpleName());
}
} else {
interfaceNames.add("Non spécifé");
}
return interfaceNames; // Prend le nom de la première interface (Volant dans ce cas)
}
@Override
public String toString() {
return "Creature{" +
"nom='" + nom + '\'' +
", age=" + age +
", sexe='" + getSex() + '\'' +
", poids=" + poids +
", taille=" + taille +
", type='" + getTypeName() + '\'' +
", indicateurFaim=" + indicateurFaim +
", indicateurSante=" + indicateurSante +
", indicateurSommeil=" + indicateurSommeil +
", dortIl=" + dortIl +
", estMorte=" + estMorte +
'}';
}
}
| FERRIER-Killian-2225036a/S3_IUT_AMU | R3.04_Qualité_Dev/TD3/src/main/Creature.java | 1,679 | // De 0 a 100 | line_comment | nl | package main;
import java.util.ArrayList;
public abstract class Creature {
protected String nom;
protected int age;
protected int sexe; // 0 = male; 1 = femelle
protected int poids; // En kg
protected int taille; // En cm
protected ArrayList<?> type = getTypeName(); // Nom de l'interface
protected int dureeDeVie = 50; // En années
protected int indicateurFaim = 0; // De 0<SUF>
protected int indicateurSante = 100; // De 100 a 0
protected int indicateurSommeil = 0; // De 0 a 100
protected boolean dortIl = false;
protected boolean estMorte = false;
public static class InstanceManager {
private static final ArrayList<Creature> instances = new ArrayList<>();
private static void addInstance(Creature instance) {
instances.add(instance);
}
public static ArrayList<Creature> getAllInstances() {
return instances;
}
}
public Creature(String nom, int age, int sexe, int poids, int taille) {
this.nom = nom;
this.age = age;
this.sexe = sexe;
this.poids = poids;
this.taille = taille;
InstanceManager.addInstance(this);
}
public void manger() {
if (!estMorte){
if (!dortIl) {
System.out.println("Miam miam");
indicateurFaim+=0;
} else {
System.out.println(nom+" dort");
}
} else {
System.out.println(nom+" est "+accordMortMess());
}
}
public boolean emetUnSon() {
if (!this.estMorte) {
System.out.println(nom+" émet un son");
return true;
} else {
System.out.println(nom+" est "+accordMortMess());
return false;
}
}
public void soigner() {
if (!estMorte) {
this.indicateurSante = 100;
} else {
System.out.println(nom+" est "+accordMortMess());
}
}
public void sendormirOuSeReveiller() {
if (estMorte){
System.out.println(nom+" est "+accordMortMess());
} else {
dortIl = !dortIl;
indicateurSommeil=0;
}
}
public void vieillir(int annee) {
if ((this.age+annee)<dureeDeVie) {
this.age += annee;
} else if ((this.age+annee)==dureeDeVie) {
this.age += annee;
this.meurt();
} else {
this.age = dureeDeVie;
this.meurt();
}
}
public void meurt() {
if (!estMorte) {
this.estMorte = true;
if (Enclos.getListCreatureDansEnclos().contains(this)) {
System.out.println("Vous devez enlever le cadavre de "+nom+" de son enclos");
}
} else {
System.out.println(nom+" est déjà "+accordMortMess());
}
}
//setters
public void setIndicateurFaim(int indicateurFaim) {
this.indicateurFaim = indicateurFaim;
}
public void setIndicateurSante(int indicateurSante) {
this.indicateurSante = indicateurSante;
}
public void setIndicateurSommeil(int indicateurSommeil) {
this.indicateurSommeil = indicateurSommeil;
}
// Getters
public String getNom() {
return nom;
}
public String getSex() {
if (this.sexe==0){
return "Male";
} else if (this.sexe==1) {
return "Femelle";
} else {
return "Non défini";
}
}
public int getAge() {
return age;
}
public int getPoids() {
return poids;
}
public int getTaille() {
return taille;
}
public ArrayList<?> getType() {
return type;
}
public int getDureeDeVie() {
return dureeDeVie;
}
public int getIndicateurFaim() {
return indicateurFaim;
}
public int getIndicateurSante() {
return indicateurSante;
}
public int getIndicateurSommeil() {
return indicateurSommeil;
}
public boolean isDortIl() {
return dortIl;
}
public boolean isEstMorte() {
return estMorte;
}
protected String accordMortMess() {
if (sexe==1) {return "morte";}
else {return "mort";}
}
// Méthode pour obtenir le nom de l'interface
private ArrayList<?> getTypeName() {
Class<?>[] interfaces = this.getClass().getInterfaces();
ArrayList<String> interfaceNames = new ArrayList<>();
// Gestion du cas où la classe n'implémente aucune interface
if (interfaces.length > 0) {
for (Class<?> interfaceElem : interfaces) {
interfaceNames.add(interfaceElem.getSimpleName());
}
} else {
interfaceNames.add("Non spécifé");
}
return interfaceNames; // Prend le nom de la première interface (Volant dans ce cas)
}
@Override
public String toString() {
return "Creature{" +
"nom='" + nom + '\'' +
", age=" + age +
", sexe='" + getSex() + '\'' +
", poids=" + poids +
", taille=" + taille +
", type='" + getTypeName() + '\'' +
", indicateurFaim=" + indicateurFaim +
", indicateurSante=" + indicateurSante +
", indicateurSommeil=" + indicateurSommeil +
", dortIl=" + dortIl +
", estMorte=" + estMorte +
'}';
}
}
|
15652_9 | /* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */
/* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package fhv;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (without unicode processing).
*/
public class SimpleCharStream
{
/** Whether parser is static. */
public static final boolean staticFlag = true;
static int bufsize;
static int available;
static int tokenBegin;
/** Position in buffer. */
static public int bufpos = -1;
static protected int bufline[];
static protected int bufcolumn[];
static protected int column = 0;
static protected int line = 1;
static protected boolean prevCharIsCR = false;
static protected boolean prevCharIsLF = false;
static protected java.io.Reader inputStream;
static protected char[] buffer;
static protected int maxNextCharInd = 0;
static protected int inBuf = 0;
static protected int tabSize = 8;
static protected void setTabSize(int i) { tabSize = i; }
static protected int getTabSize(int i) { return tabSize; }
static protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
/** Start. */
static public char BeginToken() throws java.io.IOException
{
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
static protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
/** Read a character. */
static public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return c;
}
@Deprecated
/**
* @deprecated
* @see #getEndColumn
*/
static public int getColumn() {
return bufcolumn[bufpos];
}
@Deprecated
/**
* @deprecated
* @see #getEndLine
*/
static public int getLine() {
return bufline[bufpos];
}
/** Get token end column number. */
static public int getEndColumn() {
return bufcolumn[bufpos];
}
/** Get token end line number. */
static public int getEndLine() {
return bufline[bufpos];
}
/** Get token beginning column number. */
static public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/** Get token beginning line number. */
static public int getBeginLine() {
return bufline[tokenBegin];
}
/** Backup a number of characters. */
static public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
if (inputStream != null)
throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" +
" You must either use ReInit() or set the JavaCC option STATIC to false\n" +
" during the generation of this class.");
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Get token literal value. */
static public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
/** Get the suffix. */
static public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
/** Reset buffer when finished. */
static public void Done()
{
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
static public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
/* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
| FHV-ITM13/Just-Language | Justy_Wachter/src/fhv/SimpleCharStream.java | 3,932 | /** Get token beginning column number. */ | block_comment | nl | /* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */
/* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package fhv;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (without unicode processing).
*/
public class SimpleCharStream
{
/** Whether parser is static. */
public static final boolean staticFlag = true;
static int bufsize;
static int available;
static int tokenBegin;
/** Position in buffer. */
static public int bufpos = -1;
static protected int bufline[];
static protected int bufcolumn[];
static protected int column = 0;
static protected int line = 1;
static protected boolean prevCharIsCR = false;
static protected boolean prevCharIsLF = false;
static protected java.io.Reader inputStream;
static protected char[] buffer;
static protected int maxNextCharInd = 0;
static protected int inBuf = 0;
static protected int tabSize = 8;
static protected void setTabSize(int i) { tabSize = i; }
static protected int getTabSize(int i) { return tabSize; }
static protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
/** Start. */
static public char BeginToken() throws java.io.IOException
{
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
static protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
/** Read a character. */
static public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return c;
}
@Deprecated
/**
* @deprecated
* @see #getEndColumn
*/
static public int getColumn() {
return bufcolumn[bufpos];
}
@Deprecated
/**
* @deprecated
* @see #getEndLine
*/
static public int getLine() {
return bufline[bufpos];
}
/** Get token end column number. */
static public int getEndColumn() {
return bufcolumn[bufpos];
}
/** Get token end line number. */
static public int getEndLine() {
return bufline[bufpos];
}
/** Get token beginning<SUF>*/
static public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/** Get token beginning line number. */
static public int getBeginLine() {
return bufline[tokenBegin];
}
/** Backup a number of characters. */
static public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
if (inputStream != null)
throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" +
" You must either use ReInit() or set the JavaCC option STATIC to false\n" +
" during the generation of this class.");
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Get token literal value. */
static public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
/** Get the suffix. */
static public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
/** Reset buffer when finished. */
static public void Done()
{
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
static public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
/* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
|
91774_3 | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal sleutels in de boom. */
int size();
/** @return de diepte van de boom. */
int depth();
}
| FKD13/SemiSplayTree-AD2 | src/main/java/semisplay/SearchTree.java | 206 | /** @return het aantal sleutels in de boom. */ | block_comment | nl | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal<SUF>*/
int size();
/** @return de diepte van de boom. */
int depth();
}
|
30809_5 | package frc.team4481.robot.auto.modes;
import frc.team4481.lib.auto.actions.ParallelAction;
import frc.team4481.lib.auto.mode.AutoModeBase;
import frc.team4481.lib.auto.mode.AutoModeEndedException;
import frc.team4481.lib.path.PathNotLoadedException;
import frc.team4481.lib.path.TrajectoryHandler;
import frc.team4481.lib.subsystems.SubsystemHandler;
import frc.team4481.robot.auto.actions.*;
import frc.team4481.robot.auto.selector.AutoMode;
import frc.team4481.robot.auto.selector.Disabled;
import frc.team4481.robot.subsystems.Intake;
import frc.team4481.robot.subsystems.IntakeManager;
import frc.team4481.robot.subsystems.OuttakeManager;
@Disabled
@AutoMode(displayName = "[Bottom] 4 note Q90")
public class Low_4_note_barker extends AutoModeBase {
String path_1 = "LOW_CN1";
String path_2 = "SHOOT_CN12";
String path_3 = "Recover_CN12";
String path_4 = "SHOOT_CN2";
String path_5 = "Recover_CN23";
String path_6 = "CN3_understage";
String path_7 = "SHOOT_CN3";
String path_8 = "FN1_4_note_runner";
private Intake intake;
private IntakeManager intakeManager;
private final SubsystemHandler subsystemHandler = SubsystemHandler.getInstance();
@Override
protected void initialize() throws AutoModeEndedException, PathNotLoadedException {
intake = (Intake) subsystemHandler.getSubsystemByClass(Intake.class);
intakeManager = intake.getSubsystemManager();
TrajectoryHandler trajectoryHandler = TrajectoryHandler.getInstance();
try {
trajectoryHandler.setUnloadedPath(path_1);
trajectoryHandler.setUnloadedPath(path_2);
trajectoryHandler.setUnloadedPath(path_3);
trajectoryHandler.setUnloadedPath(path_4);
trajectoryHandler.setUnloadedPath(path_5);
trajectoryHandler.setUnloadedPath(path_6);
trajectoryHandler.setUnloadedPath(path_7);
trajectoryHandler.setUnloadedPath(path_8);
} catch (PathNotLoadedException e) {
e.printStackTrace();
}
}
@Override
protected void routine() throws AutoModeEndedException {
//shoot
// runAction(new SetInitalPositionAction(path_1));
// runAction(new DriveAndShootTimedAction(path_1, new double[]{0.92, 4.14, 7.07}));
// runAction(new ParallelAction(
// new DrivePathAction(path_2),
// new ParallelAction(
// new AimingManualAction(OuttakeManager.positionState.STOWED)),
// new IntakeAction(2.9))
// );
// runAction(new DriveAndShootTimedAction(path_3, new double[]{0.82}));
runAction(new SetInitalPositionAction(path_1));
runAction(new DriveAndShootTimedAction(path_1, new double[] {0.7}));
if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD ) {
runAction(new DriveAndShootTimedAction(path_2, new double [] {2}));
} else {
runAction(new DrivePathAction(path_3));
}
// if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD) {
runAction(new DriveAndShootTimedAction(path_4, new double[] {2.1-0.15}));
// runAction(new ParallelAction(
// new AimingManualAction(OuttakeManager.positionState.STOWED),
// new IntakeAction(2.25),
// new DrivePathAction(path_6) )
//// );
// } else {
// runAction(new DrivePathAction(path_5));
// runAction(new AimingManualAction(OuttakeManager.positionState.STOWED));
// }
// runAction(new DrivePathAction(path_7));
// runAction(new ScoreAutomaticAction());
runAction(new DriveAndShootTimedAction(path_8, new double[]{0.10})); //dit werkt, 0.10 doet eigenlijk niks
runAction(new ScoreAutomaticAction());
}
}
| FRC-4481-Team-Rembrandts/4481-robot-2024-public | src/main/java/frc/team4481/robot/auto/modes/Low_4_note_barker.java | 1,274 | //dit werkt, 0.10 doet eigenlijk niks | line_comment | nl | package frc.team4481.robot.auto.modes;
import frc.team4481.lib.auto.actions.ParallelAction;
import frc.team4481.lib.auto.mode.AutoModeBase;
import frc.team4481.lib.auto.mode.AutoModeEndedException;
import frc.team4481.lib.path.PathNotLoadedException;
import frc.team4481.lib.path.TrajectoryHandler;
import frc.team4481.lib.subsystems.SubsystemHandler;
import frc.team4481.robot.auto.actions.*;
import frc.team4481.robot.auto.selector.AutoMode;
import frc.team4481.robot.auto.selector.Disabled;
import frc.team4481.robot.subsystems.Intake;
import frc.team4481.robot.subsystems.IntakeManager;
import frc.team4481.robot.subsystems.OuttakeManager;
@Disabled
@AutoMode(displayName = "[Bottom] 4 note Q90")
public class Low_4_note_barker extends AutoModeBase {
String path_1 = "LOW_CN1";
String path_2 = "SHOOT_CN12";
String path_3 = "Recover_CN12";
String path_4 = "SHOOT_CN2";
String path_5 = "Recover_CN23";
String path_6 = "CN3_understage";
String path_7 = "SHOOT_CN3";
String path_8 = "FN1_4_note_runner";
private Intake intake;
private IntakeManager intakeManager;
private final SubsystemHandler subsystemHandler = SubsystemHandler.getInstance();
@Override
protected void initialize() throws AutoModeEndedException, PathNotLoadedException {
intake = (Intake) subsystemHandler.getSubsystemByClass(Intake.class);
intakeManager = intake.getSubsystemManager();
TrajectoryHandler trajectoryHandler = TrajectoryHandler.getInstance();
try {
trajectoryHandler.setUnloadedPath(path_1);
trajectoryHandler.setUnloadedPath(path_2);
trajectoryHandler.setUnloadedPath(path_3);
trajectoryHandler.setUnloadedPath(path_4);
trajectoryHandler.setUnloadedPath(path_5);
trajectoryHandler.setUnloadedPath(path_6);
trajectoryHandler.setUnloadedPath(path_7);
trajectoryHandler.setUnloadedPath(path_8);
} catch (PathNotLoadedException e) {
e.printStackTrace();
}
}
@Override
protected void routine() throws AutoModeEndedException {
//shoot
// runAction(new SetInitalPositionAction(path_1));
// runAction(new DriveAndShootTimedAction(path_1, new double[]{0.92, 4.14, 7.07}));
// runAction(new ParallelAction(
// new DrivePathAction(path_2),
// new ParallelAction(
// new AimingManualAction(OuttakeManager.positionState.STOWED)),
// new IntakeAction(2.9))
// );
// runAction(new DriveAndShootTimedAction(path_3, new double[]{0.82}));
runAction(new SetInitalPositionAction(path_1));
runAction(new DriveAndShootTimedAction(path_1, new double[] {0.7}));
if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD ) {
runAction(new DriveAndShootTimedAction(path_2, new double [] {2}));
} else {
runAction(new DrivePathAction(path_3));
}
// if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD) {
runAction(new DriveAndShootTimedAction(path_4, new double[] {2.1-0.15}));
// runAction(new ParallelAction(
// new AimingManualAction(OuttakeManager.positionState.STOWED),
// new IntakeAction(2.25),
// new DrivePathAction(path_6) )
//// );
// } else {
// runAction(new DrivePathAction(path_5));
// runAction(new AimingManualAction(OuttakeManager.positionState.STOWED));
// }
// runAction(new DrivePathAction(path_7));
// runAction(new ScoreAutomaticAction());
runAction(new DriveAndShootTimedAction(path_8, new double[]{0.10})); //dit werkt,<SUF>
runAction(new ScoreAutomaticAction());
}
}
|
148481_8 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems.eyes;
import com.ctre.phoenix.CANifier;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
public class EyeSubsystem extends SubsystemBase {
private static EyeMovement currentDefaultMovementLeft = Constants.EYE_MOVEMENT_4; //might need to be _3
private static EyeMovement currentDefaultMovementRight = Constants.EYE_MOVEMENT_1;
private static EyeColor currentDefaultColor = Constants.LED_OFF;
private final Servo eyePupilServoRight;
private final Servo eyePupilServoLeft;
private final Servo eyeLidServoRight;
private final Servo eyeLidServoLeft;
private final CANifier clights;
public EyeSubsystem() {
eyePupilServoRight = new Servo(Constants.RIGHT_PUPIL_SERVO); // eyePupilServo1 connected to roboRIO PWM 4
eyePupilServoLeft = new Servo(Constants.LEFT_PUPIL_SERVO); // eyePupilServo2 connected to roboRIO PWM 5
eyeLidServoRight = new Servo(Constants.RIGHT_EYELID_SERVO); // eyeLidServo1 connected to roboRIO PWM 1
eyeLidServoLeft = new Servo(Constants.LEFT_EYELID_SERVO); // eyeLidServo2 connected to roboRIO PWM 2
clights = new CANifier(Constants.EYE_CANIFIER_ID);
}
public static EyeColor getDefaultColor() {
return currentDefaultColor;
}
public static void setDefaultColor(EyeColor defaultColor) {
currentDefaultColor = defaultColor;
}
public static void setDefaultMovementLeft(EyeMovement defaultMovementLeft) {
currentDefaultMovementLeft = defaultMovementLeft;
}
public static void setDefaultMovementRight(EyeMovement defaultMovementRight) {
currentDefaultMovementRight = defaultMovementRight;
}
private synchronized void setLEDColor(EyeColor color) {
// ChannelA is Green
// ChannelB is Red
// ChannelC is Blue
clights.setLEDOutput(color.getRed(), CANifier.LEDChannel.LEDChannelB); // Red
clights.setLEDOutput(color.getGreen(), CANifier.LEDChannel.LEDChannelA); // Green
clights.setLEDOutput(color.getBlue(), CANifier.LEDChannel.LEDChannelC); // Blue
// mOutputsChanged = true;
}
private void setEyePositions(EyeMovement movementLeft, EyeMovement movementRight) {
eyePupilServoRight.set(movementRight.getEyePupil());
eyePupilServoLeft.set(movementLeft.getEyePupil());
eyeLidServoRight.set(movementRight.getEyeLid());
eyeLidServoLeft.set(movementLeft.getEyeLid());
}
public EyeMovement getLeftEyeMovement() {
return new EyeMovement(eyeLidServoLeft.get(), eyePupilServoLeft.get());
}
public EyeMovement getRightEyeMovement() {
return new EyeMovement(eyeLidServoRight.get(), eyePupilServoRight.get());
}
public double getLeftEyeLid() {
return eyeLidServoLeft.get();
}
public double getLeftEyePupil() {
return eyePupilServoLeft.get();
}
public double getRightEyeLid() {
return eyeLidServoRight.get();
}
public double getRightEyePupil() {
return eyePupilServoRight.get();
}
public CommandBase setEyes(EyeMovement movementLeft, EyeMovement movementRight, EyeColor color) {
return run( // keep at run, runOnce is just a 20 ms loop
() -> {
setEyePositions(movementLeft, movementRight);
setLEDColor(color);
//setDefaultColor(color);
});
}
public CommandBase setEyesToDefault() {
return run(
() -> {
setLEDColor(currentDefaultColor);
//System.out.println("Current Default color: " + currentDefaultColor.toString() + "");
setEyePositions(currentDefaultMovementLeft, currentDefaultMovementRight);
//System.out.println("Current Default movement: Left = " + currentDefaultMovementLeft.toString() +
// " Right = " + currentDefaultMovementRight.toString() + "");
});
}
public CommandBase setColor(EyeColor color) {
return run(
() -> {
setLEDColor(color);
});
}
public CommandBase setMovement(EyeMovement movementLeft, EyeMovement movementRight) {
return run(
() -> {
setEyePositions(movementLeft, movementRight);
});
}
// public CommandBase setLeftEyeLidMovement(EyeMovement movementLeft) {
// return run(
//() -> {
//setEyePositions(movementLeft, movementRight);
// });
//}
// public static void setLeftEyelid(double position) {
// eyeLidServoLeft.set(position);
//}
@Override
public void periodic() {
// Colors
// Ask for color of target (inside ingestor)
// Change LED color depending on this result
// For teleop: White if nothing in ingestor, purple if cube in ingestor, yellow
// if cone in ingestor, red or blue depending on alliance for the last few seconds
// Also, white during auton
// Pupil
// __assuming robot is moving forward
// Move Pupil Forward
// __assuming robot is driving back
// Move Pupil Back
// __assuming robot is balancing
// repeat Move Pupil Forward and Move Pupil Back (to shake)
// __assuming robot is balanced
// Do nothing with pupil
}
@Override
public void simulationPeriodic() {
// This method will be called once per scheduler run during simulation
}
}
| FRC2832/Robot6861-2023 | src/main/java/frc/robot/subsystems/eyes/EyeSubsystem.java | 1,735 | // ChannelA is Green | line_comment | nl | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems.eyes;
import com.ctre.phoenix.CANifier;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
public class EyeSubsystem extends SubsystemBase {
private static EyeMovement currentDefaultMovementLeft = Constants.EYE_MOVEMENT_4; //might need to be _3
private static EyeMovement currentDefaultMovementRight = Constants.EYE_MOVEMENT_1;
private static EyeColor currentDefaultColor = Constants.LED_OFF;
private final Servo eyePupilServoRight;
private final Servo eyePupilServoLeft;
private final Servo eyeLidServoRight;
private final Servo eyeLidServoLeft;
private final CANifier clights;
public EyeSubsystem() {
eyePupilServoRight = new Servo(Constants.RIGHT_PUPIL_SERVO); // eyePupilServo1 connected to roboRIO PWM 4
eyePupilServoLeft = new Servo(Constants.LEFT_PUPIL_SERVO); // eyePupilServo2 connected to roboRIO PWM 5
eyeLidServoRight = new Servo(Constants.RIGHT_EYELID_SERVO); // eyeLidServo1 connected to roboRIO PWM 1
eyeLidServoLeft = new Servo(Constants.LEFT_EYELID_SERVO); // eyeLidServo2 connected to roboRIO PWM 2
clights = new CANifier(Constants.EYE_CANIFIER_ID);
}
public static EyeColor getDefaultColor() {
return currentDefaultColor;
}
public static void setDefaultColor(EyeColor defaultColor) {
currentDefaultColor = defaultColor;
}
public static void setDefaultMovementLeft(EyeMovement defaultMovementLeft) {
currentDefaultMovementLeft = defaultMovementLeft;
}
public static void setDefaultMovementRight(EyeMovement defaultMovementRight) {
currentDefaultMovementRight = defaultMovementRight;
}
private synchronized void setLEDColor(EyeColor color) {
// ChannelA is<SUF>
// ChannelB is Red
// ChannelC is Blue
clights.setLEDOutput(color.getRed(), CANifier.LEDChannel.LEDChannelB); // Red
clights.setLEDOutput(color.getGreen(), CANifier.LEDChannel.LEDChannelA); // Green
clights.setLEDOutput(color.getBlue(), CANifier.LEDChannel.LEDChannelC); // Blue
// mOutputsChanged = true;
}
private void setEyePositions(EyeMovement movementLeft, EyeMovement movementRight) {
eyePupilServoRight.set(movementRight.getEyePupil());
eyePupilServoLeft.set(movementLeft.getEyePupil());
eyeLidServoRight.set(movementRight.getEyeLid());
eyeLidServoLeft.set(movementLeft.getEyeLid());
}
public EyeMovement getLeftEyeMovement() {
return new EyeMovement(eyeLidServoLeft.get(), eyePupilServoLeft.get());
}
public EyeMovement getRightEyeMovement() {
return new EyeMovement(eyeLidServoRight.get(), eyePupilServoRight.get());
}
public double getLeftEyeLid() {
return eyeLidServoLeft.get();
}
public double getLeftEyePupil() {
return eyePupilServoLeft.get();
}
public double getRightEyeLid() {
return eyeLidServoRight.get();
}
public double getRightEyePupil() {
return eyePupilServoRight.get();
}
public CommandBase setEyes(EyeMovement movementLeft, EyeMovement movementRight, EyeColor color) {
return run( // keep at run, runOnce is just a 20 ms loop
() -> {
setEyePositions(movementLeft, movementRight);
setLEDColor(color);
//setDefaultColor(color);
});
}
public CommandBase setEyesToDefault() {
return run(
() -> {
setLEDColor(currentDefaultColor);
//System.out.println("Current Default color: " + currentDefaultColor.toString() + "");
setEyePositions(currentDefaultMovementLeft, currentDefaultMovementRight);
//System.out.println("Current Default movement: Left = " + currentDefaultMovementLeft.toString() +
// " Right = " + currentDefaultMovementRight.toString() + "");
});
}
public CommandBase setColor(EyeColor color) {
return run(
() -> {
setLEDColor(color);
});
}
public CommandBase setMovement(EyeMovement movementLeft, EyeMovement movementRight) {
return run(
() -> {
setEyePositions(movementLeft, movementRight);
});
}
// public CommandBase setLeftEyeLidMovement(EyeMovement movementLeft) {
// return run(
//() -> {
//setEyePositions(movementLeft, movementRight);
// });
//}
// public static void setLeftEyelid(double position) {
// eyeLidServoLeft.set(position);
//}
@Override
public void periodic() {
// Colors
// Ask for color of target (inside ingestor)
// Change LED color depending on this result
// For teleop: White if nothing in ingestor, purple if cube in ingestor, yellow
// if cone in ingestor, red or blue depending on alliance for the last few seconds
// Also, white during auton
// Pupil
// __assuming robot is moving forward
// Move Pupil Forward
// __assuming robot is driving back
// Move Pupil Back
// __assuming robot is balancing
// repeat Move Pupil Forward and Move Pupil Back (to shake)
// __assuming robot is balanced
// Do nothing with pupil
}
@Override
public void simulationPeriodic() {
// This method will be called once per scheduler run during simulation
}
}
|
36602_3 | package nl.rivm.screenit.wsb.vrla;
/*-
* ========================LICENSE_START=================================
* screenit-webservice-broker
* %%
* Copyright (C) 2012 - 2024 Facilitaire Samenwerking Bevolkingsonderzoek
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* =========================LICENSE_END==================================
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nl.rivm.screenit.model.Client;
import nl.rivm.screenit.model.enums.LogGebeurtenis;
import nl.rivm.screenit.model.formulieren.IdentifierElement;
import nl.rivm.screenit.model.project.ProjectBrief;
import nl.rivm.screenit.model.project.ProjectVragenlijstAntwoordenHolder;
import nl.rivm.screenit.model.project.ProjectVragenlijstStatus;
import nl.rivm.screenit.model.project.ScannedVragenlijst;
import nl.rivm.screenit.model.vragenlijsten.VragenlijstAntwoorden;
import nl.rivm.screenit.service.InstellingService;
import nl.rivm.screenit.service.LogService;
import nl.rivm.screenit.ws.vrla.Response;
import nl.rivm.screenit.ws.vrla.Vraag;
import nl.rivm.screenit.ws.vrla.Vragenlijst;
import nl.rivm.screenit.ws.vrla.VragenlijstAntwoordenService;
import nl.rivm.screenit.ws.vrla.VragenlijstProcessingException_Exception;
import nl.topicuszorg.formulieren2.api.instantie.FormulierActieInstantie;
import nl.topicuszorg.formulieren2.api.instantie.FormulierElement;
import nl.topicuszorg.formulieren2.api.instantie.FormulierElementContainer;
import nl.topicuszorg.formulieren2.api.instantie.VraagInstantie;
import nl.topicuszorg.formulieren2.api.rendering.AntwoordRenderType;
import nl.topicuszorg.formulieren2.persistence.definitie.DefaultAntwoordKeuzeVraagDefinitieImpl;
import nl.topicuszorg.formulieren2.persistence.instantie.VraagInstantieImpl;
import nl.topicuszorg.formulieren2.persistence.instantie.acties.StringShowVraagActieInstantie;
import nl.topicuszorg.formulieren2.persistence.resultaat.AbstractAntwoord;
import nl.topicuszorg.formulieren2.persistence.resultaat.MeervoudigStringAntwoord;
import nl.topicuszorg.formulieren2.persistence.resultaat.StringAntwoord;
import nl.topicuszorg.hibernate.spring.dao.HibernateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(propagation = Propagation.SUPPORTS)
@WebService(targetNamespace = "http://screenit.rivm.nl/", name = "VragenlijstAntwoordenService")
@Slf4j
@AllArgsConstructor
public class VragenlijstAntwoordenServiceImpl implements VragenlijstAntwoordenService
{
private final HibernateService hibernateService;
private final InstellingService instellingService;
private final LogService logService;
@Override
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "vragenlijstScanned", targetNamespace = "http://screenit.rivm.nl/", className = "nl.rivm.screenit.ws.vrla.VragenlijstScanned")
@WebMethod
@ResponseWrapper(localName = "vragenlijstScannedResponse", targetNamespace = "http://screenit.rivm.nl/", className = "nl.rivm.screenit.ws.vrla.VragenlijstScannedResponse")
@Transactional(propagation = Propagation.REQUIRED)
public Response vragenlijstScanned(Vragenlijst vragenlijst) throws VragenlijstProcessingException_Exception
{
LogGebeurtenis gebeurtenis = LogGebeurtenis.VRAGENLIJST_AFGEWEZEN;
Client client = null;
String melding = "Op papier ontvangen - Barcode: " + vragenlijst.getDocumentId() + " Status: " + vragenlijst.getStatus();
Response response = new Response();
response.setCode(1);
response.setMisluktwerkbak("");
try
{
if (StringUtils.isNumeric(vragenlijst.getDocumentId()))
{
ProjectBrief projectBrief = hibernateService.get(ProjectBrief.class, Long.valueOf(vragenlijst.getDocumentId()));
ProjectVragenlijstAntwoordenHolder vragenlijstAntwoordenHolder = projectBrief.getVragenlijstAntwoordenHolder();
if (projectBrief != null && vragenlijstAntwoordenHolder != null)
{
client = projectBrief.getClient();
response.setMisluktwerkbak(projectBrief.getDefinitie().getMisluktBak());
if (!vragenlijstAntwoordenHolder.getStatus().equals(ProjectVragenlijstStatus.AFGEROND))
{
VragenlijstProcessor vragenlijstProcessor = new VragenlijstProcessor(vragenlijst, projectBrief, response);
Set<AbstractAntwoord<?>> antwoordSet = vragenlijstProcessor.run();
if (ScannedVragenlijst.STATUS_AFGEHANDELD.equals(vragenlijst.getStatus()) && response.getFoutens().isEmpty()
|| ScannedVragenlijst.STATUS_VERWIJDERD.equals(vragenlijst.getStatus()))
{
ScannedVragenlijst scannedVragenlijst = new ScannedVragenlijst();
scannedVragenlijst.setBarcode(vragenlijst.getDocumentId());
scannedVragenlijst.setObjid(vragenlijst.getObjId());
scannedVragenlijst.setStatus(vragenlijst.getStatus());
scannedVragenlijst.setScanDatum(vragenlijst.getScanDatum().toGregorianCalendar().getTime());
scannedVragenlijst.setLabId(instellingService.getIfobtLabByLabID(vragenlijst.getLabId()));
scannedVragenlijst.setFouten(new HashSet<String>(response.getFoutens()));
vragenlijstAntwoordenHolder.getVragenlijstAntwoorden().getResultaat().setAntwoorden(antwoordSet);
vragenlijstAntwoordenHolder.setScannedVragenlijst(scannedVragenlijst);
vragenlijstAntwoordenHolder.setStatus(ProjectVragenlijstStatus.AFGEROND);
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder);
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder.getScannedVragenlijst());
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder.getVragenlijstAntwoorden());
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder.getVragenlijstAntwoorden().getResultaat());
response.getFoutens().clear();
response.setCode(0);
gebeurtenis = LogGebeurtenis.VRAGENLIJST_AFGEROND;
}
else
{
if (ScannedVragenlijst.STATUS_ONBETROUWBAAR.equals(vragenlijst.getStatus()))
{
response.getFoutens().add("De scan heeft status onbetrouwbaar");
}
if (ScannedVragenlijst.STATUS_AFGEHANDELD.equals(vragenlijst.getStatus()) || ScannedVragenlijst.STATUS_ONBETROUWBAAR.equals(vragenlijst.getStatus()))
{
response.setCode(4);
}
melding += " - Fouten bij invullen vragenlijst";
}
}
else
{
response.getFoutens().add("Al bestaande vragenlijst");
response.setCode(3);
melding += " - Al bestaande vragenlijst";
}
}
else
{
response.getFoutens().add("Niet bestaande barcode");
response.setCode(2);
melding += " - Niet bestaande barcode";
}
}
else
{
response.getFoutens().add("Niet bestaande barcode");
response.setCode(2);
melding += " - Niet bestaande barcode";
}
}
catch (Exception e)
{
LOG.error("Onverwachtte fout", e);
melding += " - Onverwachtte fout";
}
logService.logGebeurtenis(gebeurtenis, client, melding);
return response;
}
private static class VragenlijstProcessor
{
private final Vragenlijst gegevenAntwoorden;
private final ProjectBrief projectBrief;
private final Response response;
private final Map<Integer, Set<Integer>> gegevenAntwoordenMap = new HashMap<>();
private final Map<String, Set<String>> teValiderenAntwoordenMap = new HashMap<>();
private final Map<String, StringShowVraagActieInstantie> actieMap = new HashMap<>();
private final Set<AbstractAntwoord<?>> resultaatAntwoorden;
private int aantalVragenInDefinitie = 0;
private VragenlijstProcessor(Vragenlijst gegevenAntwoorden, ProjectBrief projectBrief, Response response)
{
this.gegevenAntwoorden = gegevenAntwoorden;
this.projectBrief = projectBrief;
this.response = response;
resultaatAntwoorden = new HashSet<>();
maakAntwoordenMap();
maakActieMap();
}
private Set<AbstractAntwoord<?>> run()
{
VragenlijstAntwoorden<ProjectVragenlijstAntwoordenHolder> vragenlijstAntwoorden = projectBrief.getVragenlijstAntwoordenHolder().getVragenlijstAntwoorden();
processElementContainer((FormulierElementContainer) vragenlijstAntwoorden.getFormulierInstantie().getContainer());
if (aantalVragenInDefinitie != gegevenAntwoorden.getVragens().size())
{
response.getFoutens().add(
String.format("Er worden in totaal %d vragen verwacht maar er zijn %d vragen ontvangen.", aantalVragenInDefinitie, gegevenAntwoorden.getVragens().size()));
}
return resultaatAntwoorden;
}
private void maakAntwoordenMap()
{
for (Vraag vraag : gegevenAntwoorden.getVragens())
{
Integer identifier = Integer.valueOf(vraag.getIdentifier());
Set<Integer> antwoorden = new HashSet<>();
for (String antwoord : vraag.getAntwoordens())
{
antwoorden.add(Integer.valueOf(antwoord));
}
gegevenAntwoordenMap.put(identifier, antwoorden);
}
}
private void maakActieMap()
{
VragenlijstAntwoorden<ProjectVragenlijstAntwoordenHolder> vragenlijstAntwoorden = projectBrief.getVragenlijstAntwoordenHolder().getVragenlijstAntwoorden();
for (FormulierActieInstantie<?, ?> actieInstantie : vragenlijstAntwoorden.getFormulierInstantie().getActies())
{
StringShowVraagActieInstantie actie = (StringShowVraagActieInstantie) actieInstantie;
VraagInstantie targetElement = (VraagInstantie) actie.getTargetElement();
String identifier = ((IdentifierElement) targetElement.getVraagDefinitie()).getIdentifier();
actieMap.put(identifier, actie);
}
}
private void processElementContainer(FormulierElementContainer<FormulierElement> elementContainer)
{
for (FormulierElement formulierElement : elementContainer.getElementen())
{
if (formulierElement instanceof FormulierElementContainer)
{
processElementContainer((FormulierElementContainer) formulierElement);
}
else if (formulierElement instanceof VraagInstantieImpl)
{
processVraag((VraagInstantieImpl) formulierElement);
}
}
}
private void processVraag(VraagInstantieImpl vraagInstantie)
{
DefaultAntwoordKeuzeVraagDefinitieImpl<String> vraagDefinitie = (DefaultAntwoordKeuzeVraagDefinitieImpl<String>) vraagInstantie.getVraagDefinitie();
String identifier = ((IdentifierElement) vraagDefinitie).getIdentifier();
int vraagNummer = ++aantalVragenInDefinitie;
boolean isVerplicht = vraagDefinitie.getVerplichting() != null;
boolean isMeervoudig = vraagDefinitie.getRenderType().equals(AntwoordRenderType.CHECKBOX_HORIZONTAAL)
|| vraagDefinitie.getRenderType().equals(AntwoordRenderType.CHECKBOX_VERTICAAL);
boolean isZichtbaar = isZichtbaar(identifier);
Set<Integer> gegevenAntwoorden = gegevenAntwoordenMap.get(vraagNummer);
if (gegevenAntwoorden == null)
{
response.getFoutens().add(String.format("Vraag %d ontbreekt.", vraagNummer));
return;
}
if (isZichtbaar)
{
if (isVerplicht && gegevenAntwoorden.size() == 0)
{
response.getFoutens().add(String.format("Vraag %d is verplicht.", vraagNummer));
}
if (!isMeervoudig && gegevenAntwoorden.size() > 1)
{
response.getFoutens().add(String.format("Op vraag %d is slechts één antwoord mogelijk.", vraagNummer));
}
}
else
{
if (gegevenAntwoorden.size() > 0)
{
response.getFoutens().add(String.format("Vraag %d had niet moeten worden ingevuld.", vraagNummer));
}
}
Set<String> teValiderenAntwoordenSet = new HashSet<>();
if (!isMeervoudig)
{
if (!gegevenAntwoorden.isEmpty())
{
Integer antwoordNummer = gegevenAntwoorden.iterator().next();
StringAntwoord stringAntwoord = new StringAntwoord();
stringAntwoord.setVraagInstantie(vraagInstantie);
String antwoordString = vraagDefinitie.getMogelijkeAntwoorden().get(antwoordNummer - 1).getAntwoordString();
stringAntwoord.setValue(antwoordString);
resultaatAntwoorden.add(stringAntwoord);
teValiderenAntwoordenSet.add(antwoordString);
}
}
else
{
if (!gegevenAntwoorden.isEmpty())
{
MeervoudigStringAntwoord meervoudigStringAntwoord = new MeervoudigStringAntwoord();
meervoudigStringAntwoord.setVraagInstantie(vraagInstantie);
for (Integer antwoordNummer : gegevenAntwoorden)
{
String antwoordString = vraagDefinitie.getMogelijkeAntwoorden().get(antwoordNummer - 1).getAntwoordString();
meervoudigStringAntwoord.getValues().add(antwoordString);
teValiderenAntwoordenSet.add(antwoordString);
}
resultaatAntwoorden.add(meervoudigStringAntwoord);
}
}
teValiderenAntwoordenMap.put(identifier, teValiderenAntwoordenSet);
}
private boolean isZichtbaar(String targetIdentifier)
{
StringShowVraagActieInstantie actie = actieMap.get(targetIdentifier);
if (actie != null)
{
String previousIdentifier = ((IdentifierElement) actie.getVraagInstantie().getVraagDefinitie()).getIdentifier();
if (isZichtbaar(previousIdentifier))
{
Set<String> antwoorden = teValiderenAntwoordenMap.get(previousIdentifier);
for (String antwoord : antwoorden)
{
if (actie.getActieResultaat(antwoord, null, null))
{
return true;
}
}
}
return false;
}
return true;
}
}
}
| FSB-Source/rivm-screenit | screenit-webservice-broker/src/main/java/nl/rivm/screenit/wsb/vrla/VragenlijstAntwoordenServiceImpl.java | 4,928 | //screenit.rivm.nl/", className = "nl.rivm.screenit.ws.vrla.VragenlijstScannedResponse") | line_comment | nl | package nl.rivm.screenit.wsb.vrla;
/*-
* ========================LICENSE_START=================================
* screenit-webservice-broker
* %%
* Copyright (C) 2012 - 2024 Facilitaire Samenwerking Bevolkingsonderzoek
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* =========================LICENSE_END==================================
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nl.rivm.screenit.model.Client;
import nl.rivm.screenit.model.enums.LogGebeurtenis;
import nl.rivm.screenit.model.formulieren.IdentifierElement;
import nl.rivm.screenit.model.project.ProjectBrief;
import nl.rivm.screenit.model.project.ProjectVragenlijstAntwoordenHolder;
import nl.rivm.screenit.model.project.ProjectVragenlijstStatus;
import nl.rivm.screenit.model.project.ScannedVragenlijst;
import nl.rivm.screenit.model.vragenlijsten.VragenlijstAntwoorden;
import nl.rivm.screenit.service.InstellingService;
import nl.rivm.screenit.service.LogService;
import nl.rivm.screenit.ws.vrla.Response;
import nl.rivm.screenit.ws.vrla.Vraag;
import nl.rivm.screenit.ws.vrla.Vragenlijst;
import nl.rivm.screenit.ws.vrla.VragenlijstAntwoordenService;
import nl.rivm.screenit.ws.vrla.VragenlijstProcessingException_Exception;
import nl.topicuszorg.formulieren2.api.instantie.FormulierActieInstantie;
import nl.topicuszorg.formulieren2.api.instantie.FormulierElement;
import nl.topicuszorg.formulieren2.api.instantie.FormulierElementContainer;
import nl.topicuszorg.formulieren2.api.instantie.VraagInstantie;
import nl.topicuszorg.formulieren2.api.rendering.AntwoordRenderType;
import nl.topicuszorg.formulieren2.persistence.definitie.DefaultAntwoordKeuzeVraagDefinitieImpl;
import nl.topicuszorg.formulieren2.persistence.instantie.VraagInstantieImpl;
import nl.topicuszorg.formulieren2.persistence.instantie.acties.StringShowVraagActieInstantie;
import nl.topicuszorg.formulieren2.persistence.resultaat.AbstractAntwoord;
import nl.topicuszorg.formulieren2.persistence.resultaat.MeervoudigStringAntwoord;
import nl.topicuszorg.formulieren2.persistence.resultaat.StringAntwoord;
import nl.topicuszorg.hibernate.spring.dao.HibernateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(propagation = Propagation.SUPPORTS)
@WebService(targetNamespace = "http://screenit.rivm.nl/", name = "VragenlijstAntwoordenService")
@Slf4j
@AllArgsConstructor
public class VragenlijstAntwoordenServiceImpl implements VragenlijstAntwoordenService
{
private final HibernateService hibernateService;
private final InstellingService instellingService;
private final LogService logService;
@Override
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "vragenlijstScanned", targetNamespace = "http://screenit.rivm.nl/", className = "nl.rivm.screenit.ws.vrla.VragenlijstScanned")
@WebMethod
@ResponseWrapper(localName = "vragenlijstScannedResponse", targetNamespace = "http://screenit.rivm.nl/", className<SUF>
@Transactional(propagation = Propagation.REQUIRED)
public Response vragenlijstScanned(Vragenlijst vragenlijst) throws VragenlijstProcessingException_Exception
{
LogGebeurtenis gebeurtenis = LogGebeurtenis.VRAGENLIJST_AFGEWEZEN;
Client client = null;
String melding = "Op papier ontvangen - Barcode: " + vragenlijst.getDocumentId() + " Status: " + vragenlijst.getStatus();
Response response = new Response();
response.setCode(1);
response.setMisluktwerkbak("");
try
{
if (StringUtils.isNumeric(vragenlijst.getDocumentId()))
{
ProjectBrief projectBrief = hibernateService.get(ProjectBrief.class, Long.valueOf(vragenlijst.getDocumentId()));
ProjectVragenlijstAntwoordenHolder vragenlijstAntwoordenHolder = projectBrief.getVragenlijstAntwoordenHolder();
if (projectBrief != null && vragenlijstAntwoordenHolder != null)
{
client = projectBrief.getClient();
response.setMisluktwerkbak(projectBrief.getDefinitie().getMisluktBak());
if (!vragenlijstAntwoordenHolder.getStatus().equals(ProjectVragenlijstStatus.AFGEROND))
{
VragenlijstProcessor vragenlijstProcessor = new VragenlijstProcessor(vragenlijst, projectBrief, response);
Set<AbstractAntwoord<?>> antwoordSet = vragenlijstProcessor.run();
if (ScannedVragenlijst.STATUS_AFGEHANDELD.equals(vragenlijst.getStatus()) && response.getFoutens().isEmpty()
|| ScannedVragenlijst.STATUS_VERWIJDERD.equals(vragenlijst.getStatus()))
{
ScannedVragenlijst scannedVragenlijst = new ScannedVragenlijst();
scannedVragenlijst.setBarcode(vragenlijst.getDocumentId());
scannedVragenlijst.setObjid(vragenlijst.getObjId());
scannedVragenlijst.setStatus(vragenlijst.getStatus());
scannedVragenlijst.setScanDatum(vragenlijst.getScanDatum().toGregorianCalendar().getTime());
scannedVragenlijst.setLabId(instellingService.getIfobtLabByLabID(vragenlijst.getLabId()));
scannedVragenlijst.setFouten(new HashSet<String>(response.getFoutens()));
vragenlijstAntwoordenHolder.getVragenlijstAntwoorden().getResultaat().setAntwoorden(antwoordSet);
vragenlijstAntwoordenHolder.setScannedVragenlijst(scannedVragenlijst);
vragenlijstAntwoordenHolder.setStatus(ProjectVragenlijstStatus.AFGEROND);
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder);
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder.getScannedVragenlijst());
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder.getVragenlijstAntwoorden());
hibernateService.saveOrUpdate(vragenlijstAntwoordenHolder.getVragenlijstAntwoorden().getResultaat());
response.getFoutens().clear();
response.setCode(0);
gebeurtenis = LogGebeurtenis.VRAGENLIJST_AFGEROND;
}
else
{
if (ScannedVragenlijst.STATUS_ONBETROUWBAAR.equals(vragenlijst.getStatus()))
{
response.getFoutens().add("De scan heeft status onbetrouwbaar");
}
if (ScannedVragenlijst.STATUS_AFGEHANDELD.equals(vragenlijst.getStatus()) || ScannedVragenlijst.STATUS_ONBETROUWBAAR.equals(vragenlijst.getStatus()))
{
response.setCode(4);
}
melding += " - Fouten bij invullen vragenlijst";
}
}
else
{
response.getFoutens().add("Al bestaande vragenlijst");
response.setCode(3);
melding += " - Al bestaande vragenlijst";
}
}
else
{
response.getFoutens().add("Niet bestaande barcode");
response.setCode(2);
melding += " - Niet bestaande barcode";
}
}
else
{
response.getFoutens().add("Niet bestaande barcode");
response.setCode(2);
melding += " - Niet bestaande barcode";
}
}
catch (Exception e)
{
LOG.error("Onverwachtte fout", e);
melding += " - Onverwachtte fout";
}
logService.logGebeurtenis(gebeurtenis, client, melding);
return response;
}
private static class VragenlijstProcessor
{
private final Vragenlijst gegevenAntwoorden;
private final ProjectBrief projectBrief;
private final Response response;
private final Map<Integer, Set<Integer>> gegevenAntwoordenMap = new HashMap<>();
private final Map<String, Set<String>> teValiderenAntwoordenMap = new HashMap<>();
private final Map<String, StringShowVraagActieInstantie> actieMap = new HashMap<>();
private final Set<AbstractAntwoord<?>> resultaatAntwoorden;
private int aantalVragenInDefinitie = 0;
private VragenlijstProcessor(Vragenlijst gegevenAntwoorden, ProjectBrief projectBrief, Response response)
{
this.gegevenAntwoorden = gegevenAntwoorden;
this.projectBrief = projectBrief;
this.response = response;
resultaatAntwoorden = new HashSet<>();
maakAntwoordenMap();
maakActieMap();
}
private Set<AbstractAntwoord<?>> run()
{
VragenlijstAntwoorden<ProjectVragenlijstAntwoordenHolder> vragenlijstAntwoorden = projectBrief.getVragenlijstAntwoordenHolder().getVragenlijstAntwoorden();
processElementContainer((FormulierElementContainer) vragenlijstAntwoorden.getFormulierInstantie().getContainer());
if (aantalVragenInDefinitie != gegevenAntwoorden.getVragens().size())
{
response.getFoutens().add(
String.format("Er worden in totaal %d vragen verwacht maar er zijn %d vragen ontvangen.", aantalVragenInDefinitie, gegevenAntwoorden.getVragens().size()));
}
return resultaatAntwoorden;
}
private void maakAntwoordenMap()
{
for (Vraag vraag : gegevenAntwoorden.getVragens())
{
Integer identifier = Integer.valueOf(vraag.getIdentifier());
Set<Integer> antwoorden = new HashSet<>();
for (String antwoord : vraag.getAntwoordens())
{
antwoorden.add(Integer.valueOf(antwoord));
}
gegevenAntwoordenMap.put(identifier, antwoorden);
}
}
private void maakActieMap()
{
VragenlijstAntwoorden<ProjectVragenlijstAntwoordenHolder> vragenlijstAntwoorden = projectBrief.getVragenlijstAntwoordenHolder().getVragenlijstAntwoorden();
for (FormulierActieInstantie<?, ?> actieInstantie : vragenlijstAntwoorden.getFormulierInstantie().getActies())
{
StringShowVraagActieInstantie actie = (StringShowVraagActieInstantie) actieInstantie;
VraagInstantie targetElement = (VraagInstantie) actie.getTargetElement();
String identifier = ((IdentifierElement) targetElement.getVraagDefinitie()).getIdentifier();
actieMap.put(identifier, actie);
}
}
private void processElementContainer(FormulierElementContainer<FormulierElement> elementContainer)
{
for (FormulierElement formulierElement : elementContainer.getElementen())
{
if (formulierElement instanceof FormulierElementContainer)
{
processElementContainer((FormulierElementContainer) formulierElement);
}
else if (formulierElement instanceof VraagInstantieImpl)
{
processVraag((VraagInstantieImpl) formulierElement);
}
}
}
private void processVraag(VraagInstantieImpl vraagInstantie)
{
DefaultAntwoordKeuzeVraagDefinitieImpl<String> vraagDefinitie = (DefaultAntwoordKeuzeVraagDefinitieImpl<String>) vraagInstantie.getVraagDefinitie();
String identifier = ((IdentifierElement) vraagDefinitie).getIdentifier();
int vraagNummer = ++aantalVragenInDefinitie;
boolean isVerplicht = vraagDefinitie.getVerplichting() != null;
boolean isMeervoudig = vraagDefinitie.getRenderType().equals(AntwoordRenderType.CHECKBOX_HORIZONTAAL)
|| vraagDefinitie.getRenderType().equals(AntwoordRenderType.CHECKBOX_VERTICAAL);
boolean isZichtbaar = isZichtbaar(identifier);
Set<Integer> gegevenAntwoorden = gegevenAntwoordenMap.get(vraagNummer);
if (gegevenAntwoorden == null)
{
response.getFoutens().add(String.format("Vraag %d ontbreekt.", vraagNummer));
return;
}
if (isZichtbaar)
{
if (isVerplicht && gegevenAntwoorden.size() == 0)
{
response.getFoutens().add(String.format("Vraag %d is verplicht.", vraagNummer));
}
if (!isMeervoudig && gegevenAntwoorden.size() > 1)
{
response.getFoutens().add(String.format("Op vraag %d is slechts één antwoord mogelijk.", vraagNummer));
}
}
else
{
if (gegevenAntwoorden.size() > 0)
{
response.getFoutens().add(String.format("Vraag %d had niet moeten worden ingevuld.", vraagNummer));
}
}
Set<String> teValiderenAntwoordenSet = new HashSet<>();
if (!isMeervoudig)
{
if (!gegevenAntwoorden.isEmpty())
{
Integer antwoordNummer = gegevenAntwoorden.iterator().next();
StringAntwoord stringAntwoord = new StringAntwoord();
stringAntwoord.setVraagInstantie(vraagInstantie);
String antwoordString = vraagDefinitie.getMogelijkeAntwoorden().get(antwoordNummer - 1).getAntwoordString();
stringAntwoord.setValue(antwoordString);
resultaatAntwoorden.add(stringAntwoord);
teValiderenAntwoordenSet.add(antwoordString);
}
}
else
{
if (!gegevenAntwoorden.isEmpty())
{
MeervoudigStringAntwoord meervoudigStringAntwoord = new MeervoudigStringAntwoord();
meervoudigStringAntwoord.setVraagInstantie(vraagInstantie);
for (Integer antwoordNummer : gegevenAntwoorden)
{
String antwoordString = vraagDefinitie.getMogelijkeAntwoorden().get(antwoordNummer - 1).getAntwoordString();
meervoudigStringAntwoord.getValues().add(antwoordString);
teValiderenAntwoordenSet.add(antwoordString);
}
resultaatAntwoorden.add(meervoudigStringAntwoord);
}
}
teValiderenAntwoordenMap.put(identifier, teValiderenAntwoordenSet);
}
private boolean isZichtbaar(String targetIdentifier)
{
StringShowVraagActieInstantie actie = actieMap.get(targetIdentifier);
if (actie != null)
{
String previousIdentifier = ((IdentifierElement) actie.getVraagInstantie().getVraagDefinitie()).getIdentifier();
if (isZichtbaar(previousIdentifier))
{
Set<String> antwoorden = teValiderenAntwoordenMap.get(previousIdentifier);
for (String antwoord : antwoorden)
{
if (actie.getActieResultaat(antwoord, null, null))
{
return true;
}
}
}
return false;
}
return true;
}
}
}
|
155310_9 | package com.ftfl.icaremyself.util;
public class ProfileInfo {
public String name;
public String age;
public String bloodGroup;
public String weight;
public String height;
public String dateOfBirth;
public String specialNotes;
String mPhone = "";
String id;
/*
* set id of the profile
*/
public void setID(String iID) {
id = iID;
}
/*
* get id of the activity
*/
public String getID() {
return id;
}
/*
* Set a name for icare profile. parameter iName return name
*/
public void setName(String iName) {
name = iName;
}
/*
* get name of the icare profile.
*/
public String getName() {
return name;
}
/*
* set age of the person
*/
public void setAge(String iAge) {
age = iAge;
}
/*
* get age of the person
*/
public String getAge() {
return age;
}
/*
* set eye color of the person
*/
public void setBloodGroup(String eBloodGroup) {
bloodGroup = eBloodGroup;
}
/*
* get eye color of the person
*/
public String getBlooGroup() {
return bloodGroup;
}
/*
* set weight
*/
public void setWeight(String iWeight) {
weight = iWeight;
}
/*
* get weight
*/
public String getWeight() {
return weight;
}
/*
* set height
*/
public void setHeight(String iHeight) {
height = iHeight;
}
/*
* get height
*/
public String getHeight() {
return height;
}
/*
* set date of birth
*/
public void setDateOfBirth(String iDateOfBirth) {
dateOfBirth = iDateOfBirth;
}
/*
* get date of birth
*/
public String getDateOfBirth() {
return dateOfBirth;
}
/*
* set special notes
*/
public void setSpecialNotes(String iSpecialNotes) {
specialNotes = iSpecialNotes;
}
/*
* get special notes
*/
public String getSpecialNotes() {
return specialNotes;
}
/*
* set special notes
*/
public void setmPhone(String ePhone) {
mPhone = ePhone;
}
/*
* get special notes
*/
public String getmPhone() {
return mPhone;
}
/*
* set empty constructor of this class
*/
public ProfileInfo() {
}
/*
* constructor for set value
*/
public ProfileInfo(String mId, String icName, String icAge, String eBloodGroup,
String icWeight, String icHeight, String icDateOfBirth,
String icSpecialNotes, String ePhone) {
id = mId;
name = icName;
age = icAge;
bloodGroup = eBloodGroup;
weight = icWeight;
height = icHeight;
dateOfBirth = icDateOfBirth;
mPhone = ePhone;
specialNotes = icSpecialNotes;
}
}
| FTFL02-ANDROID/Ankhi | ICareMyself/src/com/ftfl/icaremyself/util/ProfileInfo.java | 903 | /*
* get weight
*/ | block_comment | nl | package com.ftfl.icaremyself.util;
public class ProfileInfo {
public String name;
public String age;
public String bloodGroup;
public String weight;
public String height;
public String dateOfBirth;
public String specialNotes;
String mPhone = "";
String id;
/*
* set id of the profile
*/
public void setID(String iID) {
id = iID;
}
/*
* get id of the activity
*/
public String getID() {
return id;
}
/*
* Set a name for icare profile. parameter iName return name
*/
public void setName(String iName) {
name = iName;
}
/*
* get name of the icare profile.
*/
public String getName() {
return name;
}
/*
* set age of the person
*/
public void setAge(String iAge) {
age = iAge;
}
/*
* get age of the person
*/
public String getAge() {
return age;
}
/*
* set eye color of the person
*/
public void setBloodGroup(String eBloodGroup) {
bloodGroup = eBloodGroup;
}
/*
* get eye color of the person
*/
public String getBlooGroup() {
return bloodGroup;
}
/*
* set weight
*/
public void setWeight(String iWeight) {
weight = iWeight;
}
/*
* get weight
<SUF>*/
public String getWeight() {
return weight;
}
/*
* set height
*/
public void setHeight(String iHeight) {
height = iHeight;
}
/*
* get height
*/
public String getHeight() {
return height;
}
/*
* set date of birth
*/
public void setDateOfBirth(String iDateOfBirth) {
dateOfBirth = iDateOfBirth;
}
/*
* get date of birth
*/
public String getDateOfBirth() {
return dateOfBirth;
}
/*
* set special notes
*/
public void setSpecialNotes(String iSpecialNotes) {
specialNotes = iSpecialNotes;
}
/*
* get special notes
*/
public String getSpecialNotes() {
return specialNotes;
}
/*
* set special notes
*/
public void setmPhone(String ePhone) {
mPhone = ePhone;
}
/*
* get special notes
*/
public String getmPhone() {
return mPhone;
}
/*
* set empty constructor of this class
*/
public ProfileInfo() {
}
/*
* constructor for set value
*/
public ProfileInfo(String mId, String icName, String icAge, String eBloodGroup,
String icWeight, String icHeight, String icDateOfBirth,
String icSpecialNotes, String ePhone) {
id = mId;
name = icName;
age = icAge;
bloodGroup = eBloodGroup;
weight = icWeight;
height = icHeight;
dateOfBirth = icDateOfBirth;
mPhone = ePhone;
specialNotes = icSpecialNotes;
}
}
|
155311_9 | package com.ftfl.icare.util;
public class ICareProfile {
String mId = "";
String mName = "";
String mGender = "";
String mDateOfBirth = "";
String mWeight = "";
String mHeight = "";
String mBloodGroup = "";
String mImage = "";
/*
* set id of the profile
*/
public void setID(String eID) {
mId = eID;
}
/*
* get id of the activity
*/
public String getID() {
return mId;
}
/*
* Set a name for profile. parameter mName return name
*/
public void setName(String eName) {
mName = eName;
}
/*
* get name of the profile.
*/
public String getName() {
return mName;
}
/*
* set age of the person
*/
public void setGender(String eGender) {
mGender = eGender;
}
/*
* get age of the person
*/
public String getGender() {
return mGender;
}
/*
* set eye color of the person
*/
public void setBloodGroup(String eBloodGroup) {
mBloodGroup = eBloodGroup;
}
/*
* get eye color of the person
*/
public String getBlooGroup() {
return mBloodGroup;
}
/*
* set weight
*/
public void setWeight(String eWeight) {
mWeight = eWeight;
}
/*
* get weight
*/
public String getWeight() {
return mWeight;
}
/*
* set height
*/
public void setHeight(String eHeight) {
mHeight = eHeight;
}
/*
* get height
*/
public String getHeight() {
return mHeight;
}
/*
* set date of birth
*/
public void setDateOfBirth(String eDateOfBirth) {
mDateOfBirth = eDateOfBirth;
}
/*
* get date of birth
*/
public String getDateOfBirth() {
return mDateOfBirth;
}
/*
* set special notes
*/
public void setImage(String eImage) {
mImage = eImage;
}
/*
* get special notes
*/
public String getImage() {
return mImage;
}
/*
* set empty constructor of this class
*/
public ICareProfile() {
}
/*
* constructor for set value
*/
public ICareProfile(String eId, String eName, String eGender,
String eDateOfBirth, String eHeight, String eWeight,
String eBloodGroup, String eImage) {
mId = eId;
mName = eName;
mGender = eGender;
mBloodGroup = eBloodGroup;
mWeight = eWeight;
mHeight = eHeight;
mDateOfBirth = eDateOfBirth;
mImage = eImage;
}
}
| FTFL02-ANDROID/Nasser | ICare/src/com/ftfl/icare/util/ICareProfile.java | 822 | /*
* get weight
*/ | block_comment | nl | package com.ftfl.icare.util;
public class ICareProfile {
String mId = "";
String mName = "";
String mGender = "";
String mDateOfBirth = "";
String mWeight = "";
String mHeight = "";
String mBloodGroup = "";
String mImage = "";
/*
* set id of the profile
*/
public void setID(String eID) {
mId = eID;
}
/*
* get id of the activity
*/
public String getID() {
return mId;
}
/*
* Set a name for profile. parameter mName return name
*/
public void setName(String eName) {
mName = eName;
}
/*
* get name of the profile.
*/
public String getName() {
return mName;
}
/*
* set age of the person
*/
public void setGender(String eGender) {
mGender = eGender;
}
/*
* get age of the person
*/
public String getGender() {
return mGender;
}
/*
* set eye color of the person
*/
public void setBloodGroup(String eBloodGroup) {
mBloodGroup = eBloodGroup;
}
/*
* get eye color of the person
*/
public String getBlooGroup() {
return mBloodGroup;
}
/*
* set weight
*/
public void setWeight(String eWeight) {
mWeight = eWeight;
}
/*
* get weight
<SUF>*/
public String getWeight() {
return mWeight;
}
/*
* set height
*/
public void setHeight(String eHeight) {
mHeight = eHeight;
}
/*
* get height
*/
public String getHeight() {
return mHeight;
}
/*
* set date of birth
*/
public void setDateOfBirth(String eDateOfBirth) {
mDateOfBirth = eDateOfBirth;
}
/*
* get date of birth
*/
public String getDateOfBirth() {
return mDateOfBirth;
}
/*
* set special notes
*/
public void setImage(String eImage) {
mImage = eImage;
}
/*
* get special notes
*/
public String getImage() {
return mImage;
}
/*
* set empty constructor of this class
*/
public ICareProfile() {
}
/*
* constructor for set value
*/
public ICareProfile(String eId, String eName, String eGender,
String eDateOfBirth, String eHeight, String eWeight,
String eBloodGroup, String eImage) {
mId = eId;
mName = eName;
mGender = eGender;
mBloodGroup = eBloodGroup;
mWeight = eWeight;
mHeight = eHeight;
mDateOfBirth = eDateOfBirth;
mImage = eImage;
}
}
|
33196_6 | /*
* Grafiek.java - V - 1 - Cless responsible for making a graph for the manager
* based on the solved cases for bags
*/
package bagawareapp;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
/**
*
* @author IS106 - Team 2
*/
public class Grafiek extends javax.swing.JFrame {
private Connection conn = null;
private ResultSet rs = null;
private PreparedStatement pst = null;
private JavaConnect JavaConnect = new JavaConnect();
/**
* @description initializes the parameters for the graph
*/
public Grafiek() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
Button_CreateChart = new javax.swing.JButton();
startDate = new com.toedter.calendar.JCalendar();
endDate = new com.toedter.calendar.JCalendar();
jLabel1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(159, 13, 10));
setForeground(new java.awt.Color(159, 13, 10));
jPanel1.setBackground(new java.awt.Color(159, 13, 10));
jPanel1.setForeground(new java.awt.Color(159, 13, 10));
Button_CreateChart.setText("Create chart");
Button_CreateChart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button_CreateChartActionPerformed(evt);
}
});
jLabel1.setText("Enter start date");
jLabel5.setText("Enter end date");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4)
.addGap(408, 408, 408))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(65, 65, 65)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel5))
.addGap(122, 122, 122)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(endDate, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
.addComponent(startDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(439, 439, 439)
.addComponent(Button_CreateChart)))
.addContainerGap(277, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(startDate, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(114, 114, 114)
.addComponent(jLabel1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(endDate, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(108, 108, 108)))
.addComponent(Button_CreateChart)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @description confirms the selected dates and makes the graph
* @param evt
*/
private void Button_CreateChartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_CreateChartActionPerformed
int bLost = 0;
try {
//Connection openen gebeurt hier.
conn = JavaConnect.ConnecrDb();
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost");
rs = pst.executeQuery();
if (rs.next()) {
bLost = rs.getInt(1);
}
} catch (Exception e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Table cannot be found");
}
DefaultCategoryDataset bagStats = new DefaultCategoryDataset();
bagStats.setValue(bLost, "Bagage Lost", "Bagage Lost");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");
String strstartDate = sdf.format(startDate.getDate());
String strendDate = sdf.format(endDate.getDate());
JFreeChart chart = ChartFactory.createBarChart("BagAware Statistics", strstartDate + " - " + strendDate, "Amount", bagStats, PlotOrientation.VERTICAL, false, true, false);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.red);
ChartFrame frame = new ChartFrame("Bar Chart", chart);
frame.setVisible(true);
frame.setSize(450, 350);
JavaConnect.closeDb();
}//GEN-LAST:event_Button_CreateChartActionPerformed
/**
* @param args the command line arguments
*/
public void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Grafiek().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Button_CreateChart;
private com.toedter.calendar.JCalendar endDate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private com.toedter.calendar.JCalendar startDate;
// End of variables declaration//GEN-END:variables
}
| FYSTeam2/BagAwareFinal | src/bagawareapp/Grafiek.java | 3,041 | //Connection openen gebeurt hier. | line_comment | nl | /*
* Grafiek.java - V - 1 - Cless responsible for making a graph for the manager
* based on the solved cases for bags
*/
package bagawareapp;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
/**
*
* @author IS106 - Team 2
*/
public class Grafiek extends javax.swing.JFrame {
private Connection conn = null;
private ResultSet rs = null;
private PreparedStatement pst = null;
private JavaConnect JavaConnect = new JavaConnect();
/**
* @description initializes the parameters for the graph
*/
public Grafiek() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
Button_CreateChart = new javax.swing.JButton();
startDate = new com.toedter.calendar.JCalendar();
endDate = new com.toedter.calendar.JCalendar();
jLabel1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(159, 13, 10));
setForeground(new java.awt.Color(159, 13, 10));
jPanel1.setBackground(new java.awt.Color(159, 13, 10));
jPanel1.setForeground(new java.awt.Color(159, 13, 10));
Button_CreateChart.setText("Create chart");
Button_CreateChart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button_CreateChartActionPerformed(evt);
}
});
jLabel1.setText("Enter start date");
jLabel5.setText("Enter end date");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4)
.addGap(408, 408, 408))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(65, 65, 65)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel5))
.addGap(122, 122, 122)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(endDate, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
.addComponent(startDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(439, 439, 439)
.addComponent(Button_CreateChart)))
.addContainerGap(277, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(startDate, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(114, 114, 114)
.addComponent(jLabel1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(endDate, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(108, 108, 108)))
.addComponent(Button_CreateChart)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @description confirms the selected dates and makes the graph
* @param evt
*/
private void Button_CreateChartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_CreateChartActionPerformed
int bLost = 0;
try {
//Connection openen<SUF>
conn = JavaConnect.ConnecrDb();
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost");
rs = pst.executeQuery();
if (rs.next()) {
bLost = rs.getInt(1);
}
} catch (Exception e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Table cannot be found");
}
DefaultCategoryDataset bagStats = new DefaultCategoryDataset();
bagStats.setValue(bLost, "Bagage Lost", "Bagage Lost");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");
String strstartDate = sdf.format(startDate.getDate());
String strendDate = sdf.format(endDate.getDate());
JFreeChart chart = ChartFactory.createBarChart("BagAware Statistics", strstartDate + " - " + strendDate, "Amount", bagStats, PlotOrientation.VERTICAL, false, true, false);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.red);
ChartFrame frame = new ChartFrame("Bar Chart", chart);
frame.setVisible(true);
frame.setSize(450, 350);
JavaConnect.closeDb();
}//GEN-LAST:event_Button_CreateChartActionPerformed
/**
* @param args the command line arguments
*/
public void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Grafiek.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Grafiek().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Button_CreateChart;
private com.toedter.calendar.JCalendar endDate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private com.toedter.calendar.JCalendar startDate;
// End of variables declaration//GEN-END:variables
}
|
48663_0 | package nl.geostandaarden.imx.orchestrate.source.rest.executor;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import nl.geostandaarden.imx.orchestrate.engine.exchange.AbstractDataRequest;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.AbstractResult;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.BatchResult;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.CollectionResult;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.ObjectResult;
import nl.geostandaarden.imx.orchestrate.source.rest.config.RestOrchestrateConfig;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.util.*;
@SuppressWarnings("SpellCheckingInspection")
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
public class RemoteExecutor implements ApiExecutor {
private final WebClient webClient;
static AbstractResult requestType;
public static RemoteExecutor create(RestOrchestrateConfig config) {
return new RemoteExecutor(RestWebClient.create(config));
}
@Override
public Mono<AbstractResult> execute(Map<String, Object> requestedData, AbstractDataRequest objectRequest) {
requestType = getRequestType(objectRequest);
var mapTypeRef = new ParameterizedTypeReference<Map<String, Object>>() {};
return this.webClient.get()
.uri(createUri(requestedData))
.accept(MediaType.valueOf("application/hal+json"))
.retrieve()
.bodyToMono(mapTypeRef)
.map(RemoteExecutor::mapToResult);
}
static AbstractResult getRequestType(AbstractDataRequest objectRequest) {
if (objectRequest == null) {
return null;
}
return switch (objectRequest.getClass().getName()) {
case "nl.geostandaarden.imx.orchestrate.engine.exchange.CollectionRequest" -> new CollectionResult(null);
case "nl.geostandaarden.imx.orchestrate.engine.exchange.ObjectRequest" -> new ObjectResult(null);
case "nl.geostandaarden.imx.orchestrate.engine.exchange.BatchRequest" -> new BatchResult(null);
default -> null;
};
}
static String createUri(Map<String, Object> requestedData) {
if (requestedData == null)
return "";
if (requestedData.size() != 1)
return "";
//Haal het eerste item uit de map, je kunt immers maar 1 ding in het URI plakken om op te zoeken
Map.Entry<String, Object> entry = requestedData.entrySet().iterator().next();
var key = requestedData.keySet().iterator().next();
var value = entry.getValue();
if(key.equals("identificatie")){
value = "?openbaarLichaam=" + value;
} else {
value = "/" + value;
}
return (value.toString());
}
static AbstractResult mapToResult(Map<String, Object> body) {
AbstractResult result;
ArrayList<LinkedHashMap<String, Object>> resultlist = new ArrayList<>();
//Als de return body meer als 2 items heeft (meer als _embedded en _links) dan is het een enkel resultaat uit een zoek query
if(body.size() > 2 ){
resultlist.add((LinkedHashMap<String, Object>) body);
result = new ObjectResult(null);
result.data = resultlist;
return result;
}
if (requestType instanceof CollectionResult) {
result = new CollectionResult(null);
} else if (requestType instanceof BatchResult) {
result = new BatchResult(null);
} else if (requestType instanceof ObjectResult) {
result = new ObjectResult(null);
} else {
result = null;
}
if (body.containsKey("_embedded")) {
Object embeddedObject = body.get("_embedded");
if (embeddedObject instanceof LinkedHashMap) {
LinkedHashMap<String, Object> embeddedMap = (LinkedHashMap<String, Object>) embeddedObject;
Iterator<String> iterator = embeddedMap.keySet().iterator();
Object bodyListObject = embeddedMap.get(iterator.hasNext() ? iterator.next() : "defaultKey");
if (bodyListObject instanceof ArrayList) {
ArrayList<?> bodyList = (ArrayList<?>) bodyListObject;
for (Object item : bodyList) {
if (item instanceof LinkedHashMap) {
resultlist.add((LinkedHashMap<String, Object>) item);
}
}
}
}
}
if (result != null) {
result.data = resultlist;
}
return result;
}
}
| Faalangst26/imx-orchestrate-quadaster | source-rest/src/main/java/nl/geostandaarden/imx/orchestrate/source/rest/executor/RemoteExecutor.java | 1,307 | //Haal het eerste item uit de map, je kunt immers maar 1 ding in het URI plakken om op te zoeken | line_comment | nl | package nl.geostandaarden.imx.orchestrate.source.rest.executor;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import nl.geostandaarden.imx.orchestrate.engine.exchange.AbstractDataRequest;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.AbstractResult;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.BatchResult;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.CollectionResult;
import nl.geostandaarden.imx.orchestrate.source.rest.Result.ObjectResult;
import nl.geostandaarden.imx.orchestrate.source.rest.config.RestOrchestrateConfig;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.util.*;
@SuppressWarnings("SpellCheckingInspection")
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
public class RemoteExecutor implements ApiExecutor {
private final WebClient webClient;
static AbstractResult requestType;
public static RemoteExecutor create(RestOrchestrateConfig config) {
return new RemoteExecutor(RestWebClient.create(config));
}
@Override
public Mono<AbstractResult> execute(Map<String, Object> requestedData, AbstractDataRequest objectRequest) {
requestType = getRequestType(objectRequest);
var mapTypeRef = new ParameterizedTypeReference<Map<String, Object>>() {};
return this.webClient.get()
.uri(createUri(requestedData))
.accept(MediaType.valueOf("application/hal+json"))
.retrieve()
.bodyToMono(mapTypeRef)
.map(RemoteExecutor::mapToResult);
}
static AbstractResult getRequestType(AbstractDataRequest objectRequest) {
if (objectRequest == null) {
return null;
}
return switch (objectRequest.getClass().getName()) {
case "nl.geostandaarden.imx.orchestrate.engine.exchange.CollectionRequest" -> new CollectionResult(null);
case "nl.geostandaarden.imx.orchestrate.engine.exchange.ObjectRequest" -> new ObjectResult(null);
case "nl.geostandaarden.imx.orchestrate.engine.exchange.BatchRequest" -> new BatchResult(null);
default -> null;
};
}
static String createUri(Map<String, Object> requestedData) {
if (requestedData == null)
return "";
if (requestedData.size() != 1)
return "";
//Haal het<SUF>
Map.Entry<String, Object> entry = requestedData.entrySet().iterator().next();
var key = requestedData.keySet().iterator().next();
var value = entry.getValue();
if(key.equals("identificatie")){
value = "?openbaarLichaam=" + value;
} else {
value = "/" + value;
}
return (value.toString());
}
static AbstractResult mapToResult(Map<String, Object> body) {
AbstractResult result;
ArrayList<LinkedHashMap<String, Object>> resultlist = new ArrayList<>();
//Als de return body meer als 2 items heeft (meer als _embedded en _links) dan is het een enkel resultaat uit een zoek query
if(body.size() > 2 ){
resultlist.add((LinkedHashMap<String, Object>) body);
result = new ObjectResult(null);
result.data = resultlist;
return result;
}
if (requestType instanceof CollectionResult) {
result = new CollectionResult(null);
} else if (requestType instanceof BatchResult) {
result = new BatchResult(null);
} else if (requestType instanceof ObjectResult) {
result = new ObjectResult(null);
} else {
result = null;
}
if (body.containsKey("_embedded")) {
Object embeddedObject = body.get("_embedded");
if (embeddedObject instanceof LinkedHashMap) {
LinkedHashMap<String, Object> embeddedMap = (LinkedHashMap<String, Object>) embeddedObject;
Iterator<String> iterator = embeddedMap.keySet().iterator();
Object bodyListObject = embeddedMap.get(iterator.hasNext() ? iterator.next() : "defaultKey");
if (bodyListObject instanceof ArrayList) {
ArrayList<?> bodyList = (ArrayList<?>) bodyListObject;
for (Object item : bodyList) {
if (item instanceof LinkedHashMap) {
resultlist.add((LinkedHashMap<String, Object>) item);
}
}
}
}
}
if (result != null) {
result.data = resultlist;
}
return result;
}
}
|
84098_34 | package com.simibubi.create.content.equipment.extendoGrip;
import java.util.UUID;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.jamieswhiteshirt.reachentityattributes.ReachEntityAttributes;
import com.simibubi.create.AllItems;
import com.simibubi.create.content.equipment.armor.BacktankUtil;
import com.simibubi.create.foundation.advancement.AllAdvancements;
import com.simibubi.create.foundation.utility.AnimationTickHolder;
import com.simibubi.create.infrastructure.config.AllConfigs;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult.Type;
import net.minecraft.world.phys.Vec3;
public class ExtendoGripItem extends Item {
public static final int MAX_DAMAGE = 200;
public static final AttributeModifier singleRangeAttributeModifier =
new AttributeModifier(UUID.fromString("7f7dbdb2-0d0d-458a-aa40-ac7633691f66"), "Range modifier", 3,
AttributeModifier.Operation.ADDITION);
public static final AttributeModifier doubleRangeAttributeModifier =
new AttributeModifier(UUID.fromString("8f7dbdb2-0d0d-458a-aa40-ac7633691f66"), "Range modifier", 5,
AttributeModifier.Operation.ADDITION);
private static final Supplier<Multimap<Attribute, AttributeModifier>> rangeModifier = Suppliers.memoize(() ->
// Holding an ExtendoGrip
ImmutableMultimap.of(ReachEntityAttributes.REACH, singleRangeAttributeModifier));
private static final Supplier<Multimap<Attribute, AttributeModifier>> doubleRangeModifier = Suppliers.memoize(() ->
// Holding two ExtendoGrips o.O
ImmutableMultimap.of(ReachEntityAttributes.REACH, doubleRangeAttributeModifier));
private static DamageSource lastActiveDamageSource;
public ExtendoGripItem(Properties properties) {
super(properties.defaultDurability(MAX_DAMAGE));
}
public static final String EXTENDO_MARKER = "createExtendo";
public static final String DUAL_EXTENDO_MARKER = "createDualExtendo";
public static void holdingExtendoGripIncreasesRange(LivingEntity entity) {
if (!(entity instanceof Player))
return;
Player player = (Player) entity;
CompoundTag persistentData = player.getExtraCustomData();
boolean inOff = AllItems.EXTENDO_GRIP.isIn(player.getOffhandItem());
boolean inMain = AllItems.EXTENDO_GRIP.isIn(player.getMainHandItem());
boolean holdingDualExtendo = inOff && inMain;
boolean holdingExtendo = inOff ^ inMain;
holdingExtendo &= !holdingDualExtendo;
boolean wasHoldingExtendo = persistentData.contains(EXTENDO_MARKER);
boolean wasHoldingDualExtendo = persistentData.contains(DUAL_EXTENDO_MARKER);
if (holdingExtendo != wasHoldingExtendo) {
if (!holdingExtendo) {
player.getAttributes()
.removeAttributeModifiers(rangeModifier.get());
persistentData.remove(EXTENDO_MARKER);
} else {
AllAdvancements.EXTENDO_GRIP.awardTo(player);
player.getAttributes()
.addTransientAttributeModifiers(rangeModifier.get());
persistentData.putBoolean(EXTENDO_MARKER, true);
}
}
if (holdingDualExtendo != wasHoldingDualExtendo) {
if (!holdingDualExtendo) {
player.getAttributes()
.removeAttributeModifiers(doubleRangeModifier.get());
persistentData.remove(DUAL_EXTENDO_MARKER);
} else {
AllAdvancements.EXTENDO_GRIP_DUAL.awardTo(player);
player.getAttributes()
.addTransientAttributeModifiers(doubleRangeModifier.get());
persistentData.putBoolean(DUAL_EXTENDO_MARKER, true);
}
}
}
public static void addReachToJoiningPlayersHoldingExtendo(Entity entity, @Nullable CompoundTag persistentData) {
if (!(entity instanceof Player player) || persistentData == null) return;
// Player player = event.getPlayer();
// CompoundTag persistentData = player.getExtraCustomData();
if (persistentData.contains(DUAL_EXTENDO_MARKER))
player.getAttributes()
.addTransientAttributeModifiers(doubleRangeModifier.get());
else if (persistentData.contains(EXTENDO_MARKER))
player.getAttributes()
.addTransientAttributeModifiers(rangeModifier.get());
}
// @SubscribeEvent
@Environment(EnvType.CLIENT)
public static void dontMissEntitiesWhenYouHaveHighReachDistance(/*ClickInputEvent event*/) {
Minecraft mc = Minecraft.getInstance();
LocalPlayer player = mc.player;
if (mc.level == null || player == null)
return;
if (!isHoldingExtendoGrip(player))
return;
if (mc.hitResult instanceof BlockHitResult && mc.hitResult.getType() != Type.MISS)
return;
// Modified version of GameRenderer#getMouseOver
double d0 = player.getAttribute(ReachEntityAttributes.REACH)
.getValue();
if (!player.isCreative())
d0 -= 0.5f;
Vec3 Vector3d = player.getEyePosition(AnimationTickHolder.getPartialTicks());
Vec3 Vector3d1 = player.getViewVector(1.0F);
Vec3 Vector3d2 = Vector3d.add(Vector3d1.x * d0, Vector3d1.y * d0, Vector3d1.z * d0);
AABB AABB = player.getBoundingBox()
.expandTowards(Vector3d1.scale(d0))
.inflate(1.0D, 1.0D, 1.0D);
EntityHitResult entityraytraceresult =
ProjectileUtil.getEntityHitResult(player, Vector3d, Vector3d2, AABB, (e) -> {
return !e.isSpectator() && e.isPickable();
}, d0 * d0);
if (entityraytraceresult != null) {
Entity entity1 = entityraytraceresult.getEntity();
Vec3 Vector3d3 = entityraytraceresult.getLocation();
double d2 = Vector3d.distanceToSqr(Vector3d3);
if (d2 < d0 * d0 || mc.hitResult == null || mc.hitResult.getType() == Type.MISS) {
mc.hitResult = entityraytraceresult;
if (entity1 instanceof LivingEntity || entity1 instanceof ItemFrame)
mc.crosshairPickEntity = entity1;
}
}
}
// @SubscribeEvent(priority = EventPriority.LOWEST)
// public static void consumeDurabilityOnBlockBreak(BreakEvent event) {
// findAndDamageExtendoGrip(event.getPlayer());
// }
//
// @SubscribeEvent(priority = EventPriority.LOWEST)
// public static void consumeDurabilityOnPlace(EntityPlaceEvent event) {
// Entity entity = event.getEntity();
// if (entity instanceof Player)
// findAndDamageExtendoGrip((Player) entity);
// }
// @SubscribeEvent(priority = EventPriority.LOWEST)
// public static void consumeDurabilityOnPlace(PlayerInteractEvent event) {
// findAndDamageExtendoGrip(event.getPlayer());
// }
private static void findAndDamageExtendoGrip(Player player) {
if (player == null)
return;
if (player.level.isClientSide)
return;
InteractionHand hand = InteractionHand.MAIN_HAND;
ItemStack extendo = player.getMainHandItem();
if (!AllItems.EXTENDO_GRIP.isIn(extendo)) {
extendo = player.getOffhandItem();
hand = InteractionHand.OFF_HAND;
}
if (!AllItems.EXTENDO_GRIP.isIn(extendo))
return;
final InteractionHand h = hand;
if (!BacktankUtil.canAbsorbDamage(player, maxUses()))
extendo.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(h));
}
@Override
public boolean isBarVisible(ItemStack stack) {
return BacktankUtil.isBarVisible(stack, maxUses());
}
@Override
public int getBarWidth(ItemStack stack) {
return BacktankUtil.getBarWidth(stack, maxUses());
}
@Override
public int getBarColor(ItemStack stack) {
return BacktankUtil.getBarColor(stack, maxUses());
}
private static int maxUses() {
return AllConfigs.server().equipment.maxExtendoGripActions.get();
}
public static float bufferLivingAttackEvent(DamageSource source, LivingEntity damaged, float amount) {
// Workaround for removed patch to get the attacking entity.
lastActiveDamageSource = source;
Entity trueSource = source.getEntity();
if (trueSource instanceof Player)
findAndDamageExtendoGrip((Player) trueSource);
return amount;
}
public static double attacksByExtendoGripHaveMoreKnockback(double strength, Player player) {
if (lastActiveDamageSource == null)
return strength;
Entity entity = lastActiveDamageSource.getDirectEntity();
if (!(entity instanceof Player))
return strength;
Player playerE = (Player) entity;
if (!isHoldingExtendoGrip(playerE))
return strength;
return strength + 2;
}
// private static boolean isUncaughtClientInteraction(Entity entity, Entity target) {
// // Server ignores entity interaction further than 6m
// if (entity.distanceToSqr(target) < 36)
// return false;
// if (!entity.level.isClientSide)
// return false;
// if (!(entity instanceof Player))
// return false;
// return true;
// }
// @SubscribeEvent
// @Environment(EnvType.CLIENT)
// public static void notifyServerOfLongRangeAttacks(AttackEntityEvent event) {
// Entity entity = event.getEntity();
// Entity target = event.getTarget();
// if (!isUncaughtClientInteraction(entity, target))
// return;
// Player player = (Player) entity;
// if (isHoldingExtendoGrip(player))
// AllPackets.channel.sendToServer(new ExtendoGripInteractionPacket(target));
// }
//
// @SubscribeEvent
// @Environment(EnvType.CLIENT)
// public static void notifyServerOfLongRangeInteractions(PlayerInteractEvent.EntityInteract event) {
// Entity entity = event.getEntity();
// Entity target = event.getTarget();
// if (!isUncaughtClientInteraction(entity, target))
// return;
// Player player = (Player) entity;
// if (isHoldingExtendoGrip(player))
// AllPackets.channel.sendToServer(new ExtendoGripInteractionPacket(target, event.getHand()));
// }
//
// @SubscribeEvent
// @Environment(EnvType.CLIENT)
// public static void notifyServerOfLongRangeSpecificInteractions(PlayerInteractEvent.EntityInteractSpecific event) {
// Entity entity = event.getEntity();
// Entity target = event.getTarget();
// if (!isUncaughtClientInteraction(entity, target))
// return;
// Player player = (Player) entity;
// if (isHoldingExtendoGrip(player))
// AllPackets.getChannel()
// .sendToServer(new ExtendoGripInteractionPacket(target, event.getHand(), event.getLocalPos()));
// }
public static boolean isHoldingExtendoGrip(Player player) {
boolean inOff = AllItems.EXTENDO_GRIP.isIn(player.getOffhandItem());
boolean inMain = AllItems.EXTENDO_GRIP.isIn(player.getMainHandItem());
boolean holdingGrip = inOff || inMain;
return holdingGrip;
}
// @Override
// @Environment(EnvType.CLIENT)
// public void initializeClient(Consumer<IItemRenderProperties> consumer) {
// consumer.accept(SimpleCustomRenderer.create(this, new ExtendoGripItemRenderer()));
// }
}
| Fabricators-of-Create/Create | src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java | 3,677 | // .sendToServer(new ExtendoGripInteractionPacket(target, event.getHand(), event.getLocalPos())); | line_comment | nl | package com.simibubi.create.content.equipment.extendoGrip;
import java.util.UUID;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.jamieswhiteshirt.reachentityattributes.ReachEntityAttributes;
import com.simibubi.create.AllItems;
import com.simibubi.create.content.equipment.armor.BacktankUtil;
import com.simibubi.create.foundation.advancement.AllAdvancements;
import com.simibubi.create.foundation.utility.AnimationTickHolder;
import com.simibubi.create.infrastructure.config.AllConfigs;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult.Type;
import net.minecraft.world.phys.Vec3;
public class ExtendoGripItem extends Item {
public static final int MAX_DAMAGE = 200;
public static final AttributeModifier singleRangeAttributeModifier =
new AttributeModifier(UUID.fromString("7f7dbdb2-0d0d-458a-aa40-ac7633691f66"), "Range modifier", 3,
AttributeModifier.Operation.ADDITION);
public static final AttributeModifier doubleRangeAttributeModifier =
new AttributeModifier(UUID.fromString("8f7dbdb2-0d0d-458a-aa40-ac7633691f66"), "Range modifier", 5,
AttributeModifier.Operation.ADDITION);
private static final Supplier<Multimap<Attribute, AttributeModifier>> rangeModifier = Suppliers.memoize(() ->
// Holding an ExtendoGrip
ImmutableMultimap.of(ReachEntityAttributes.REACH, singleRangeAttributeModifier));
private static final Supplier<Multimap<Attribute, AttributeModifier>> doubleRangeModifier = Suppliers.memoize(() ->
// Holding two ExtendoGrips o.O
ImmutableMultimap.of(ReachEntityAttributes.REACH, doubleRangeAttributeModifier));
private static DamageSource lastActiveDamageSource;
public ExtendoGripItem(Properties properties) {
super(properties.defaultDurability(MAX_DAMAGE));
}
public static final String EXTENDO_MARKER = "createExtendo";
public static final String DUAL_EXTENDO_MARKER = "createDualExtendo";
public static void holdingExtendoGripIncreasesRange(LivingEntity entity) {
if (!(entity instanceof Player))
return;
Player player = (Player) entity;
CompoundTag persistentData = player.getExtraCustomData();
boolean inOff = AllItems.EXTENDO_GRIP.isIn(player.getOffhandItem());
boolean inMain = AllItems.EXTENDO_GRIP.isIn(player.getMainHandItem());
boolean holdingDualExtendo = inOff && inMain;
boolean holdingExtendo = inOff ^ inMain;
holdingExtendo &= !holdingDualExtendo;
boolean wasHoldingExtendo = persistentData.contains(EXTENDO_MARKER);
boolean wasHoldingDualExtendo = persistentData.contains(DUAL_EXTENDO_MARKER);
if (holdingExtendo != wasHoldingExtendo) {
if (!holdingExtendo) {
player.getAttributes()
.removeAttributeModifiers(rangeModifier.get());
persistentData.remove(EXTENDO_MARKER);
} else {
AllAdvancements.EXTENDO_GRIP.awardTo(player);
player.getAttributes()
.addTransientAttributeModifiers(rangeModifier.get());
persistentData.putBoolean(EXTENDO_MARKER, true);
}
}
if (holdingDualExtendo != wasHoldingDualExtendo) {
if (!holdingDualExtendo) {
player.getAttributes()
.removeAttributeModifiers(doubleRangeModifier.get());
persistentData.remove(DUAL_EXTENDO_MARKER);
} else {
AllAdvancements.EXTENDO_GRIP_DUAL.awardTo(player);
player.getAttributes()
.addTransientAttributeModifiers(doubleRangeModifier.get());
persistentData.putBoolean(DUAL_EXTENDO_MARKER, true);
}
}
}
public static void addReachToJoiningPlayersHoldingExtendo(Entity entity, @Nullable CompoundTag persistentData) {
if (!(entity instanceof Player player) || persistentData == null) return;
// Player player = event.getPlayer();
// CompoundTag persistentData = player.getExtraCustomData();
if (persistentData.contains(DUAL_EXTENDO_MARKER))
player.getAttributes()
.addTransientAttributeModifiers(doubleRangeModifier.get());
else if (persistentData.contains(EXTENDO_MARKER))
player.getAttributes()
.addTransientAttributeModifiers(rangeModifier.get());
}
// @SubscribeEvent
@Environment(EnvType.CLIENT)
public static void dontMissEntitiesWhenYouHaveHighReachDistance(/*ClickInputEvent event*/) {
Minecraft mc = Minecraft.getInstance();
LocalPlayer player = mc.player;
if (mc.level == null || player == null)
return;
if (!isHoldingExtendoGrip(player))
return;
if (mc.hitResult instanceof BlockHitResult && mc.hitResult.getType() != Type.MISS)
return;
// Modified version of GameRenderer#getMouseOver
double d0 = player.getAttribute(ReachEntityAttributes.REACH)
.getValue();
if (!player.isCreative())
d0 -= 0.5f;
Vec3 Vector3d = player.getEyePosition(AnimationTickHolder.getPartialTicks());
Vec3 Vector3d1 = player.getViewVector(1.0F);
Vec3 Vector3d2 = Vector3d.add(Vector3d1.x * d0, Vector3d1.y * d0, Vector3d1.z * d0);
AABB AABB = player.getBoundingBox()
.expandTowards(Vector3d1.scale(d0))
.inflate(1.0D, 1.0D, 1.0D);
EntityHitResult entityraytraceresult =
ProjectileUtil.getEntityHitResult(player, Vector3d, Vector3d2, AABB, (e) -> {
return !e.isSpectator() && e.isPickable();
}, d0 * d0);
if (entityraytraceresult != null) {
Entity entity1 = entityraytraceresult.getEntity();
Vec3 Vector3d3 = entityraytraceresult.getLocation();
double d2 = Vector3d.distanceToSqr(Vector3d3);
if (d2 < d0 * d0 || mc.hitResult == null || mc.hitResult.getType() == Type.MISS) {
mc.hitResult = entityraytraceresult;
if (entity1 instanceof LivingEntity || entity1 instanceof ItemFrame)
mc.crosshairPickEntity = entity1;
}
}
}
// @SubscribeEvent(priority = EventPriority.LOWEST)
// public static void consumeDurabilityOnBlockBreak(BreakEvent event) {
// findAndDamageExtendoGrip(event.getPlayer());
// }
//
// @SubscribeEvent(priority = EventPriority.LOWEST)
// public static void consumeDurabilityOnPlace(EntityPlaceEvent event) {
// Entity entity = event.getEntity();
// if (entity instanceof Player)
// findAndDamageExtendoGrip((Player) entity);
// }
// @SubscribeEvent(priority = EventPriority.LOWEST)
// public static void consumeDurabilityOnPlace(PlayerInteractEvent event) {
// findAndDamageExtendoGrip(event.getPlayer());
// }
private static void findAndDamageExtendoGrip(Player player) {
if (player == null)
return;
if (player.level.isClientSide)
return;
InteractionHand hand = InteractionHand.MAIN_HAND;
ItemStack extendo = player.getMainHandItem();
if (!AllItems.EXTENDO_GRIP.isIn(extendo)) {
extendo = player.getOffhandItem();
hand = InteractionHand.OFF_HAND;
}
if (!AllItems.EXTENDO_GRIP.isIn(extendo))
return;
final InteractionHand h = hand;
if (!BacktankUtil.canAbsorbDamage(player, maxUses()))
extendo.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(h));
}
@Override
public boolean isBarVisible(ItemStack stack) {
return BacktankUtil.isBarVisible(stack, maxUses());
}
@Override
public int getBarWidth(ItemStack stack) {
return BacktankUtil.getBarWidth(stack, maxUses());
}
@Override
public int getBarColor(ItemStack stack) {
return BacktankUtil.getBarColor(stack, maxUses());
}
private static int maxUses() {
return AllConfigs.server().equipment.maxExtendoGripActions.get();
}
public static float bufferLivingAttackEvent(DamageSource source, LivingEntity damaged, float amount) {
// Workaround for removed patch to get the attacking entity.
lastActiveDamageSource = source;
Entity trueSource = source.getEntity();
if (trueSource instanceof Player)
findAndDamageExtendoGrip((Player) trueSource);
return amount;
}
public static double attacksByExtendoGripHaveMoreKnockback(double strength, Player player) {
if (lastActiveDamageSource == null)
return strength;
Entity entity = lastActiveDamageSource.getDirectEntity();
if (!(entity instanceof Player))
return strength;
Player playerE = (Player) entity;
if (!isHoldingExtendoGrip(playerE))
return strength;
return strength + 2;
}
// private static boolean isUncaughtClientInteraction(Entity entity, Entity target) {
// // Server ignores entity interaction further than 6m
// if (entity.distanceToSqr(target) < 36)
// return false;
// if (!entity.level.isClientSide)
// return false;
// if (!(entity instanceof Player))
// return false;
// return true;
// }
// @SubscribeEvent
// @Environment(EnvType.CLIENT)
// public static void notifyServerOfLongRangeAttacks(AttackEntityEvent event) {
// Entity entity = event.getEntity();
// Entity target = event.getTarget();
// if (!isUncaughtClientInteraction(entity, target))
// return;
// Player player = (Player) entity;
// if (isHoldingExtendoGrip(player))
// AllPackets.channel.sendToServer(new ExtendoGripInteractionPacket(target));
// }
//
// @SubscribeEvent
// @Environment(EnvType.CLIENT)
// public static void notifyServerOfLongRangeInteractions(PlayerInteractEvent.EntityInteract event) {
// Entity entity = event.getEntity();
// Entity target = event.getTarget();
// if (!isUncaughtClientInteraction(entity, target))
// return;
// Player player = (Player) entity;
// if (isHoldingExtendoGrip(player))
// AllPackets.channel.sendToServer(new ExtendoGripInteractionPacket(target, event.getHand()));
// }
//
// @SubscribeEvent
// @Environment(EnvType.CLIENT)
// public static void notifyServerOfLongRangeSpecificInteractions(PlayerInteractEvent.EntityInteractSpecific event) {
// Entity entity = event.getEntity();
// Entity target = event.getTarget();
// if (!isUncaughtClientInteraction(entity, target))
// return;
// Player player = (Player) entity;
// if (isHoldingExtendoGrip(player))
// AllPackets.getChannel()
// .sendToServer(new ExtendoGripInteractionPacket(target,<SUF>
// }
public static boolean isHoldingExtendoGrip(Player player) {
boolean inOff = AllItems.EXTENDO_GRIP.isIn(player.getOffhandItem());
boolean inMain = AllItems.EXTENDO_GRIP.isIn(player.getMainHandItem());
boolean holdingGrip = inOff || inMain;
return holdingGrip;
}
// @Override
// @Environment(EnvType.CLIENT)
// public void initializeClient(Consumer<IItemRenderProperties> consumer) {
// consumer.accept(SimpleCustomRenderer.create(this, new ExtendoGripItemRenderer()));
// }
}
|
115103_12 | package com.lightspeedhq.ecom.domain;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.lightspeedhq.ecom.LightspeedEComClient;
import com.lightspeedhq.ecom.jackson.FalseNullDeserializer;
import com.lightspeedhq.ecom.jackson.ResourceIdDeserializer;
import java.io.Serializable;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import lombok.Getter;
/**
* Products are the primary items for sale in a shop. A product always has one or more variants and zero or more images.
*
* @see <a href="http://developers.seoshop.com/api/resources/product">http://developers.seoshop.com/api/resources/product</a>
* @author stevensnoeijen
*/
@JsonRootName("product")
public class Product implements Serializable {
private static final long serialVersionUID = 2L;
@JsonRootName("products")
public static class List extends ArrayList<Product> {
}
public enum Visibility {
HIDDEN, VISIBLE, AUTO;
@JsonValue
public String toJson() {
return name().toLowerCase();
}
@JsonCreator
public static Visibility fromJson(String value) {
return Enum.valueOf(Visibility.class, value.toUpperCase());
}
}
/**
* The unique numeric identifier for the product.<br/>
* Example: <code>{"id": "{id}"}</code>
*/
@Getter
private int id;
/**
* The date and time when the product was created.<br/>
* (format: ISO-8601)<br/>
* Example: <code>{"createdAt": "2013-09-24T21:48:17+02:00"}</code>
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = LightspeedEComClient.DATETIME_FORMAT)
@Getter
private ZonedDateTime createdAt;
/**
* The date and time when the product was last updated.<br/>
* (format: ISO-8601)<br/>
* Example: <code>{"updatedAt": "2013-09-24T22:02:24+02:00"}</code>
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = LightspeedEComClient.DATETIME_FORMAT)
@Getter
private ZonedDateTime updatedAt;
/**
* Product visibility.<br/>
* Example: <code>{"isVisible": "true|false"}</code>
*/
@JsonProperty("isVisible")
@Getter
private boolean isVisible;
/**
* Product visibility setting.<br/>
* Example: <code>{"visibility": "hidden, visible, auto"}</code>
*/
@Getter
private Visibility visibility;
@Getter
private boolean hasMatrix;
/**
* Extra template variable data01.<br/>
* Example: <code>{"data01": ""}</code>
*/
@Getter
private String data01;
/**
* Extra template variable data02.<br/>
* Example: <code>{"data02": ""}</code>
*/
@Getter
private String data02;
/**
* Extra template variable data03.<br/>
* Example: <code>{"data03": ""}</code>
*/
@Getter
private String data03;
/**
* Product slug.<br/>
* Example: <code>{"url": "wade-crewneck-navyblue"}</code>
*/
@Getter
private String url;
/**
* Product title.<br/>
* Example: <code>{"title": "Wade Crewneck Navyblue"}</code>
*/
@Getter
private String title;
/**
* Product full title.<br/>
* Example: <code>{"fulltitle": "Wade Crewneck Navyblue"}</code>
*/
@Getter
private String fulltitle;
/**
* Product description.<br/>
* Example: <code>{"description": "De Wade Crewneck Navyblue van Wemoto. Deze blauwe trui met de enorme W op de chest heeft een heel klassieke look."}</code>
*/
@Getter
private String description;
/**
* Product content.<br/>
* Example: <code>{"content": "De Wade Crewneck Navyblue van Wemoto. Deze blauwe trui met de enorme W op de chest heeft een heel klassieke look."}</code>
*/
@Getter
private String content;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/brand">Brand</a> resource.<br/>
* Use this value get the {@link Brand} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getBrand(int) }.
* Value is "-1" when no value is set.
*/
@Getter
@JsonProperty("brand")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int brandId;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/deliverydate">DeliveryDate</a> resource.<br/>
* Use this value get the {@link Deliverydate} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getDeliverydate(int) }.
* Value is "-1" when no value is set.
*/
@Getter
@JsonProperty("deliverydate")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int deliverydateId;
/**
* Main product image. See <a href="http://developers.seoshop.com/api/resources/file">File</a>
* Id will be empty inside the product.
*/
@Getter
@JsonDeserialize(using = FalseNullDeserializer.class)
private Image image;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/type">Type</a> resource.<br/>
* Use this value get the {@link Type} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getType(int) }.
*/
@Getter
@JsonProperty("type")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int typeId;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/type">Type</a> resource.<br/>
* Use this value get the {@link Supplier} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getSupplier(int) }.
*/
@Getter
@JsonProperty("supplier")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int supplierId;
}
| Falkplan/lightspeedecom-api | lightspeedecom-api/src/main/java/com/lightspeedhq/ecom/domain/Product.java | 1,818 | /**
* Product description.<br/>
* Example: <code>{"description": "De Wade Crewneck Navyblue van Wemoto. Deze blauwe trui met de enorme W op de chest heeft een heel klassieke look."}</code>
*/ | block_comment | nl | package com.lightspeedhq.ecom.domain;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.lightspeedhq.ecom.LightspeedEComClient;
import com.lightspeedhq.ecom.jackson.FalseNullDeserializer;
import com.lightspeedhq.ecom.jackson.ResourceIdDeserializer;
import java.io.Serializable;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import lombok.Getter;
/**
* Products are the primary items for sale in a shop. A product always has one or more variants and zero or more images.
*
* @see <a href="http://developers.seoshop.com/api/resources/product">http://developers.seoshop.com/api/resources/product</a>
* @author stevensnoeijen
*/
@JsonRootName("product")
public class Product implements Serializable {
private static final long serialVersionUID = 2L;
@JsonRootName("products")
public static class List extends ArrayList<Product> {
}
public enum Visibility {
HIDDEN, VISIBLE, AUTO;
@JsonValue
public String toJson() {
return name().toLowerCase();
}
@JsonCreator
public static Visibility fromJson(String value) {
return Enum.valueOf(Visibility.class, value.toUpperCase());
}
}
/**
* The unique numeric identifier for the product.<br/>
* Example: <code>{"id": "{id}"}</code>
*/
@Getter
private int id;
/**
* The date and time when the product was created.<br/>
* (format: ISO-8601)<br/>
* Example: <code>{"createdAt": "2013-09-24T21:48:17+02:00"}</code>
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = LightspeedEComClient.DATETIME_FORMAT)
@Getter
private ZonedDateTime createdAt;
/**
* The date and time when the product was last updated.<br/>
* (format: ISO-8601)<br/>
* Example: <code>{"updatedAt": "2013-09-24T22:02:24+02:00"}</code>
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = LightspeedEComClient.DATETIME_FORMAT)
@Getter
private ZonedDateTime updatedAt;
/**
* Product visibility.<br/>
* Example: <code>{"isVisible": "true|false"}</code>
*/
@JsonProperty("isVisible")
@Getter
private boolean isVisible;
/**
* Product visibility setting.<br/>
* Example: <code>{"visibility": "hidden, visible, auto"}</code>
*/
@Getter
private Visibility visibility;
@Getter
private boolean hasMatrix;
/**
* Extra template variable data01.<br/>
* Example: <code>{"data01": ""}</code>
*/
@Getter
private String data01;
/**
* Extra template variable data02.<br/>
* Example: <code>{"data02": ""}</code>
*/
@Getter
private String data02;
/**
* Extra template variable data03.<br/>
* Example: <code>{"data03": ""}</code>
*/
@Getter
private String data03;
/**
* Product slug.<br/>
* Example: <code>{"url": "wade-crewneck-navyblue"}</code>
*/
@Getter
private String url;
/**
* Product title.<br/>
* Example: <code>{"title": "Wade Crewneck Navyblue"}</code>
*/
@Getter
private String title;
/**
* Product full title.<br/>
* Example: <code>{"fulltitle": "Wade Crewneck Navyblue"}</code>
*/
@Getter
private String fulltitle;
/**
* Product description.<br/>
<SUF>*/
@Getter
private String description;
/**
* Product content.<br/>
* Example: <code>{"content": "De Wade Crewneck Navyblue van Wemoto. Deze blauwe trui met de enorme W op de chest heeft een heel klassieke look."}</code>
*/
@Getter
private String content;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/brand">Brand</a> resource.<br/>
* Use this value get the {@link Brand} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getBrand(int) }.
* Value is "-1" when no value is set.
*/
@Getter
@JsonProperty("brand")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int brandId;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/deliverydate">DeliveryDate</a> resource.<br/>
* Use this value get the {@link Deliverydate} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getDeliverydate(int) }.
* Value is "-1" when no value is set.
*/
@Getter
@JsonProperty("deliverydate")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int deliverydateId;
/**
* Main product image. See <a href="http://developers.seoshop.com/api/resources/file">File</a>
* Id will be empty inside the product.
*/
@Getter
@JsonDeserialize(using = FalseNullDeserializer.class)
private Image image;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/type">Type</a> resource.<br/>
* Use this value get the {@link Type} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getType(int) }.
*/
@Getter
@JsonProperty("type")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int typeId;
/**
* Link to <a href="http://developers.seoshop.com/api/resources/type">Type</a> resource.<br/>
* Use this value get the {@link Supplier} with {@link com.lightspeedhq.ecom.LightspeedEComClient#getSupplier(int) }.
*/
@Getter
@JsonProperty("supplier")
@JsonDeserialize(using = ResourceIdDeserializer.class)
private int supplierId;
}
|
42251_71 | package com.fasterxml.aalto.util;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.codehaus.stax2.typed.Base64Variant;
import org.codehaus.stax2.typed.TypedArrayDecoder;
import org.codehaus.stax2.typed.TypedXMLStreamException;
import org.codehaus.stax2.ri.typed.CharArrayBase64Decoder;
import com.fasterxml.aalto.in.ReaderConfig;
/**
* Class conceptually similar to {@link java.lang.StringBuilder}, but
* that allows for bit more efficient building, using segmented internal
* buffers, and direct access to these buffers.
*/
public final class TextBuilder
{
final static char[] sNoChars = new char[0];
/**
* Size of the first text segment buffer to allocate. Need not contain
* the biggest segment, since new ones will get allocated as needed.
* However, it's sensible to use something that often is big enough
* to contain typical segments.
*/
final static int DEF_INITIAL_BUFFER_SIZE = 500; // 1k
final static int MAX_SEGMENT_LENGTH = 256 * 1024;
final static int INT_SPACE = 0x0020;
// // // Configuration:
private final ReaderConfig _config;
// // // Internal non-shared collector buffers:
/**
* List of segments prior to currently active segment.
*/
private ArrayList<char[]> _segments;
// // // Currently used segment; not (yet) contained in _segments
/**
* Amount of characters in segments in {@link _segments}
*/
private int _segmentSize;
private char[] _currentSegment;
/**
* Number of characters in currently active (last) segment
*/
private int _currentSize;
// // // Temporary caching for Objects to return
/**
* String that will be constructed when the whole contents are
* needed; will be temporarily stored in case asked for again.
*/
private String _resultString;
private char[] _resultArray;
/**
* Indicator for length of data with <code>_resultArray</code>, iff
* the primary indicator (_currentSize) is invalid (-1).
*/
private int _resultLen;
/*
/**********************************************************************
/* Support for decoding, for Typed Access API
/**********************************************************************
*/
private char[] _decodeBuffer;
private int _decodePtr;
private int _decodeEnd;
/*
/**********************************************************************
/* Support for optimizating indentation segments:
/**********************************************************************
*/
/**
* Marker to know if the contents currently stored were created
* using "indentation detection". If so, it's known to be all
* white space
*/
private boolean _isIndentation = false;
// // // Canonical indentation objects (up to 32 spaces, 8 tabs)
public final static int MAX_INDENT_SPACES = 32;
public final static int MAX_INDENT_TABS = 8;
// Let's add one more space at the end, for safety...
private final static String sIndSpaces =
// 123456789012345678901234567890123
"\n ";
private final static char[] sIndSpacesArray = sIndSpaces.toCharArray();
private final static String[] sIndSpacesStrings = new String[sIndSpacesArray.length];
private final static String sIndTabs =
// 1 2 3 4 5 6 7 8 9
"\n\t\t\t\t\t\t\t\t\t";
private final static char[] sIndTabsArray = sIndTabs.toCharArray();
private final static String[] sIndTabsStrings = new String[sIndTabsArray.length];
/*
/**********************************************************************
/* Life-cycle
/**********************************************************************
*/
private TextBuilder(ReaderConfig cfg)
{
_config = cfg;
}
public static TextBuilder createRecyclableBuffer(ReaderConfig cfg)
{
return new TextBuilder(cfg);
}
/**
* Method called to indicate that the underlying buffers should now
* be recycled if they haven't yet been recycled. Although caller
* can still use this text buffer, it is not advisable to call this
* method if that is likely, since next time a buffer is needed,
* buffers need to reallocated.
* Note: calling this method automatically also clears contents
* of the buffer.
*/
public void recycle(boolean force)
{
if (_config != null && _currentSegment != null) {
if (force) {
/* shouldn't call resetWithEmpty, as that would allocate
* initial buffer; but need to inline
*/
_resultString = null;
_resultArray = null;
} else {
/* But if there's non-shared data (ie. buffer is still
* in use), can't return it yet:
*/
if ((_segmentSize + _currentSize) > 0) {
return;
}
}
// If no data (or only shared data), can continue
if (_segments != null && _segments.size() > 0) {
// No need to use anything from list, curr segment not null
_segments.clear();
_segmentSize = 0;
}
char[] buf = _currentSegment;
_currentSegment = null;
_config.freeMediumCBuffer(buf);
}
}
/**
* Method called to clear out any content text buffer may have, and
* initializes and returns the first segment to add characters to.
*/
public char[] resetWithEmpty()
{
_resultString = null;
_resultArray = null;
_isIndentation = false;
// And then reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
/* Since the current segment should be the biggest one
* (as we allocate 50% bigger each time), let's retain it,
* and clear others
*/
_segments.clear();
_segmentSize = 0;
}
_currentSize = 0;
if (_currentSegment == null) {
_currentSegment = allocBuffer(0);
}
return _currentSegment;
}
public void resetWithIndentation(int indCharCount, char indChar)
{
// First reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
_segments.clear();
_segmentSize = 0;
}
_currentSize = -1;
_isIndentation = true;
String text;
int strlen = indCharCount+1;
_resultLen = strlen;
if (indChar == '\t') { // tabs?
_resultArray = sIndTabsArray;
text = sIndTabsStrings[indCharCount];
if (text == null) {
sIndTabsStrings[indCharCount] = text = sIndTabs.substring(0, strlen);
}
} else { // nope, spaces (should assert indChar?)
_resultArray = sIndSpacesArray;
text = sIndSpacesStrings[indCharCount];
if (text == null) {
sIndSpacesStrings[indCharCount] = text = sIndSpaces.substring(0, strlen);
}
}
_resultString = text;
}
/**
* Method called to initialize the buffer with just a single char
*/
public void resetWithChar(char c)
{
_resultString = null;
_resultArray = null;
_isIndentation = false;
// And then reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
_segments.clear();
_segmentSize = 0;
}
_currentSize = 1;
if (_currentSegment == null) {
_currentSegment = allocBuffer(1);
}
_currentSegment[0] = c;
}
public void resetWithSurrogate(int c)
{
_resultString = null;
_resultArray = null;
_isIndentation = false;
// And then reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
_segments.clear();
_segmentSize = 0;
}
_currentSize = 2;
if (_currentSegment == null) {
_currentSegment = allocBuffer(2);
}
_currentSegment[0] = (char) (0xD800 | (c >> 10));
_currentSegment[1] = (char) (0xDC00 | (c & 0x3FF));
}
public char[] getBufferWithoutReset()
{
return _currentSegment;
}
/*
/**********************************************************************
/* Accessors for implementing StAX interface:
/**********************************************************************
*/
/**
* @return Number of characters currently stored by this collector
*/
public int size()
{
int size = _currentSize;
// Will be -1 only if we have shared white space
if (size < 0) {
return _resultLen;
}
return size + _segmentSize;
}
public char[] getTextBuffer()
{
// Does it fit in just one segment?
if (_segments == null || _segments.size() == 0) {
// But is it whitespace, actually?
if (_resultArray != null) {
return _resultArray;
}
return _currentSegment;
}
// Nope, need to have/create a non-segmented array and return it
return contentsAsArray();
}
/*
/**********************************************************************
/* Accessors for text contained
/**********************************************************************
*/
public String contentsAsString()
{
if (_resultString == null) {
// Has array been requested? Can make a shortcut, if so:
if (_resultArray != null) {
_resultString = new String(_resultArray);
} else {
// Let's optimize common case: nothing in extra segments:
int segLen = _segmentSize;
int currLen = _currentSize;
if (segLen == 0) {
_resultString = (currLen == 0) ? "" : new String(_currentSegment, 0, currLen);
return _resultString;
}
// Nope, need to combine:
StringBuilder sb = new StringBuilder(segLen + currLen);
// First stored segments
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] curr = (char[]) _segments.get(i);
sb.append(curr, 0, curr.length);
}
}
// And finally, current segment:
sb.append(_currentSegment, 0, currLen);
_resultString = sb.toString();
}
}
return _resultString;
}
public char[] contentsAsArray()
{
char[] result = _resultArray;
if (result == null) {
_resultArray = result = buildResultArray();
}
return result;
}
public int contentsToArray(int srcStart, char[] dst, int dstStart, int len) {
/* Could also check if we have array, but that'd only help with
* brain dead clients that get full array first, then segments...
* which hopefully aren't that common
*/
// Copying from segmented array is bit more involved:
int totalAmount = 0;
if (_segments != null) {
for (int i = 0, segc = _segments.size(); i < segc; ++i) {
char[] segment = (char[]) _segments.get(i);
int segLen = segment.length;
int amount = segLen - srcStart;
if (amount < 1) { // nothing from this segment?
srcStart -= segLen;
continue;
}
if (amount >= len) { // can get rest from this segment?
System.arraycopy(segment, srcStart, dst, dstStart, len);
return (totalAmount + len);
}
// Can get some from this segment, offset becomes zero:
System.arraycopy(segment, srcStart, dst, dstStart, amount);
totalAmount += amount;
dstStart += amount;
len -= amount;
srcStart = 0;
}
}
// Need to copy anything from last segment?
if (len > 0) {
int maxAmount = _currentSize - srcStart;
if (len > maxAmount) {
len = maxAmount;
}
if (len > 0) { // should always be true
System.arraycopy(_currentSegment, srcStart, dst, dstStart, len);
totalAmount += len;
}
}
return totalAmount;
}
/**
* Method that will stream contents of this buffer into specified
* Writer.
*/
public int rawContentsTo(Writer w)
throws IOException
{
// Let's first see if we have created helper objects:
if (_resultArray != null) {
w.write(_resultArray);
return _resultArray.length;
}
if (_resultString != null) {
w.write(_resultString);
return _resultString.length();
}
// Nope, need to do full segmented output
int rlen = 0;
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] ch = (char[]) _segments.get(i);
w.write(ch);
rlen += ch.length;
}
}
if (_currentSize > 0) {
w.write(_currentSegment, 0, _currentSize);
rlen += _currentSize;
}
return rlen;
}
public boolean isAllWhitespace()
{
if (_isIndentation) {
return true;
}
// Need to do full segmented output, otherwise
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] buf = (char[]) _segments.get(i);
for (int j = 0, len2 = buf.length; j < len2; ++j) {
if (buf[j] > 0x0020) {
return false;
}
}
}
}
char[] buf = _currentSegment;
for (int i = 0, len = _currentSize; i < len; ++i) {
if (buf[i] > 0x0020) {
return false;
}
}
return true;
}
/*
* Method that can be used to check if the contents of the buffer end
* in specified String.
*
* @return True if the textual content buffer contains ends with the
* specified String; false otherwise
public boolean endsWith(String str)
{
int segIndex = (_segments == null) ? 0 : _segments.size();
int inIndex = str.length() - 1;
char[] buf = _currentSegment;
int bufIndex = _currentSize-1;
while (inIndex >= 0) {
if (str.charAt(inIndex) != buf[bufIndex]) {
return false;
}
if (--inIndex == 0) {
break;
}
if (--bufIndex < 0) {
if (--segIndex < 0) { // no more data?
return false;
}
buf = (char[]) _segments.get(segIndex);
bufIndex = buf.length-1;
}
}
return true;
}
*/
/**
* Note: it is assumed that this method is not used often enough to
* be a bottleneck, or for long segments. Based on this, it is optimized
* for common simple cases where there is only one single character
* segment to use; fallback for other cases is to create such segment.
*/
public boolean equalsString(String str)
{
int expLen = str.length();
// Otherwise, segments:
if (expLen != size()) {
return false;
}
char[] seg;
if (_segments == null || _segments.size() == 0) {
// just one segment, still easy
seg = _currentSegment;
} else {
/* Ok; this is the sub-optimal case. Could obviously juggle through
* segments, but probably not worth the hassle, we seldom if ever
* get here...
*/
seg = contentsAsArray();
}
for (int i = 0; i < expLen; ++i) {
if (seg[i] != str.charAt(i)) {
return false;
}
}
return true;
}
/*
/**********************************************************************
/* Methods for generating SAX events
/**********************************************************************
*/
/**
* This is a specialized "accessor" method, which is basically
* to fire SAX characters() events in an optimal way, based on
* which internal buffers are being used
*/
public void fireSaxCharacterEvents(ContentHandler h)
throws SAXException
{
if (_resultArray != null) { // only happens for indentation
h.characters(_resultArray, 0, _resultLen);
} else {
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] ch = (char[]) _segments.get(i);
h.characters(ch, 0, ch.length);
}
}
if (_currentSize > 0) {
h.characters(_currentSegment, 0, _currentSize);
}
}
}
public void fireSaxSpaceEvents(ContentHandler h)
throws SAXException
{
if (_resultArray != null) { // only happens for indentation
h.ignorableWhitespace(_resultArray, 0, _resultLen);
} else {
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] ch = (char[]) _segments.get(i);
h.ignorableWhitespace(ch, 0, ch.length);
}
}
if (_currentSize > 0) {
h.ignorableWhitespace(_currentSegment, 0, _currentSize);
}
}
}
public void fireSaxCommentEvent(LexicalHandler h)
throws SAXException
{
// Comment can not be split, so may need to combine the array
if (_resultArray != null) { // only happens for indentation
h.comment(_resultArray, 0, _resultLen);
} else if (_segments != null && _segments.size() > 0) {
char[] ch = contentsAsArray();
h.comment(ch, 0, ch.length);
} else {
h.comment(_currentSegment, 0, _currentSize);
}
}
/*
/**********************************************************************
/* Support for validation
/**********************************************************************
*/
/*
public void validateText(XMLValidator vld, boolean lastSegment)
throws XMLValidationException
{
// Can either create a combine buffer, or construct
// a String. While former could be more efficient, let's do latter
// for now since current validator implementations work better
// with Strings.
vld.validateText(contentsAsString(), lastSegment);
}
*/
/*
/**********************************************************************
/* Public mutators:
/**********************************************************************
*/
public void append(char c)
{
_resultString = null;
_resultArray = null;
// Room in current segment?
char[] curr = _currentSegment;
if (_currentSize >= curr.length) {
expand(1);
}
curr[_currentSize++] = c;
}
public void appendSurrogate(int surr)
{
append((char) (0xD800 | (surr >> 10)));
append((char) (0xDC00 | (surr & 0x3FF)));
}
public void append(char[] c, int start, int len)
{
_resultString = null;
_resultArray = null;
// Room in current segment?
char[] curr = _currentSegment;
int max = curr.length - _currentSize;
if (max >= len) {
System.arraycopy(c, start, curr, _currentSize, len);
_currentSize += len;
} else {
// No room for all, need to copy part(s):
if (max > 0) {
System.arraycopy(c, start, curr, _currentSize, max);
start += max;
len -= max;
}
/* And then allocate new segment; we are guaranteed to now
* have enough room in segment.
*/
expand(len); // note: curr != _currentSegment after this
System.arraycopy(c, start, _currentSegment, 0, len);
_currentSize = len;
}
}
public void append(String str)
{
_resultString = null;
_resultArray = null;
int len = str.length();
// Room in current segment?
char[] curr = _currentSegment;
int max = curr.length - _currentSize;
if (max >= len) {
str.getChars(0, len, curr, _currentSize);
_currentSize += len;
} else {
// No room for all, need to copy part(s):
if (max > 0) {
str.getChars(0, max, curr, _currentSize);
len -= max;
}
/* And then allocate new segment; we are guaranteed to now
* have enough room in segment.
*/
expand(len);
str.getChars(max, max+len, _currentSegment, 0);
_currentSize = len;
}
}
/*
/**********************************************************************
/* Raw access, for high-performance use:
/**********************************************************************
*/
public int getCurrentLength() {
return _currentSize;
}
public void setCurrentLength(int len) {
_currentSize = len;
}
public char[] finishCurrentSegment()
{
if (_segments == null) {
_segments = new ArrayList<char[]>();
}
_segments.add(_currentSegment);
int oldLen = _currentSegment.length;
_segmentSize += oldLen;
char[] curr = new char[calcNewSize(oldLen)];
_currentSize = 0;
_currentSegment = curr;
return curr;
}
private int calcNewSize(int latestSize)
{
// Let's grow segments by 50%, when over 8k
int incr = (latestSize < 8000) ? latestSize : (latestSize >> 1);
int size = latestSize + incr;
// but let's not create too big chunks
return Math.min(size, MAX_SEGMENT_LENGTH);
}
/*
/**********************************************************************
/* Methods for implementing Typed Access API
/**********************************************************************
*/
/**
* Method called by the stream reader to decode space-separated tokens
* that are part of the current text event (contents of which
* are stored within this buffer), using given decoder.
*/
public int decodeElements(TypedArrayDecoder tad, boolean reset)
throws TypedXMLStreamException
{
if (reset) {
resetForDecode();
}
int ptr = _decodePtr;
final char[] buf = _decodeBuffer;
int count = 0;
// And then let's decode
int start = ptr;
try {
final int end = _decodeEnd;
decode_loop:
while (ptr < end) {
// First, any space to skip?
while (buf[ptr] <= INT_SPACE) {
if (++ptr >= end) {
break decode_loop;
}
}
// Then let's figure out non-space char (token)
start = ptr;
++ptr;
while (ptr < end && buf[ptr] > INT_SPACE) {
++ptr;
}
++count;
int tokenEnd = ptr;
++ptr; // to skip trailing space (or, beyond end)
// And there we have it
if (tad.decodeValue(buf, start, tokenEnd)) {
break;
}
_decodePtr = ptr;
}
_decodePtr = ptr;
} catch (IllegalArgumentException iae) {
// Need to convert to a checked stream exception to return lexical
// -1 to move it back after being advanced earlier (to skip trailing space)
String lexical = new String(buf, start, (ptr-start-1));
throw new TypedXMLStreamException(lexical, iae.getMessage(), iae);
}
return count;
}
/**
* Method called to initialize given base64 decoder with data
* contained in this text buffer (for the current event).
*/
public void resetForBinaryDecode(Base64Variant v, CharArrayBase64Decoder dec, boolean firstChunk)
{
// just one special case, indentation...
if (_segments == null || _segments.size() == 0) { // single segment
if (_isIndentation) { // but special one, indent/ws
dec.init(v, firstChunk, _resultArray, 0, _resultArray.length, null);
return;
}
}
dec.init(v, firstChunk, _currentSegment, 0, _currentSize, _segments);
}
private final void resetForDecode()
{
/* This is very similar to getTextBuffer(), except
* for assignment to _decodeXxx fields
*/
_decodePtr = 0;
if (_segments == null || _segments.size() == 0) { // single segment
if (_isIndentation) { // but special one, indent/ws
_decodeBuffer = _resultArray;
_decodeEnd = _resultArray.length;
} else { // nope, just a regular buffer
_decodeBuffer = _currentSegment;
_decodeEnd = _currentSize;
}
} else {
// Nope, need to have/create a non-segmented array and return it
_decodeBuffer = contentsAsArray();
_decodeEnd = _decodeBuffer.length;
}
}
/*
/**********************************************************************
/* Standard methods:
/**********************************************************************
*/
/**
* Note: calling this method may not be as efficient as calling
* {@link #contentsAsString}, since it is guaranteed that resulting
* String is NOT cached (to ensure we see no stale data)
*/
@Override
public String toString() {
_resultString = null;
_resultArray = null;
return contentsAsString();
}
/*
/**********************************************************************
/* Internal methods:
/**********************************************************************
*/
private final char[] allocBuffer(int minNeeded)
{
int size = Math.max(DEF_INITIAL_BUFFER_SIZE, minNeeded);
char[] buf = null;
if (_config != null) {
buf = _config.allocMediumCBuffer(size);
if (buf != null) {
return buf;
}
}
return new char[size];
}
/**
* Method called when current segment is full, to allocate new
* segment.
*/
private void expand(int roomNeeded)
{
// First, let's move current segment to segment list:
if (_segments == null) {
_segments = new ArrayList<char[]>();
}
char[] curr = _currentSegment;
_segments.add(curr);
int oldLen = curr.length;
_segmentSize += oldLen;
int newSize = Math.max(roomNeeded, calcNewSize(oldLen));
curr = new char[newSize];
_currentSize = 0;
_currentSegment = curr;
}
private char[] buildResultArray()
{
if (_resultString != null) { // Can take a shortcut...
return _resultString.toCharArray();
}
char[] result;
int size = size();
if (size < 1) {
return sNoChars;
}
int offset = 0;
result = new char[size];
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] curr = _segments.get(i);
int currLen = curr.length;
System.arraycopy(curr, 0, result, offset, currLen);
offset += currLen;
}
}
System.arraycopy(_currentSegment, 0, result, offset, _currentSize);
return result;
}
}
| FasterXML/aalto-xml | src/main/java/com/fasterxml/aalto/util/TextBuilder.java | 7,831 | // Room in current segment? | line_comment | nl | package com.fasterxml.aalto.util;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.codehaus.stax2.typed.Base64Variant;
import org.codehaus.stax2.typed.TypedArrayDecoder;
import org.codehaus.stax2.typed.TypedXMLStreamException;
import org.codehaus.stax2.ri.typed.CharArrayBase64Decoder;
import com.fasterxml.aalto.in.ReaderConfig;
/**
* Class conceptually similar to {@link java.lang.StringBuilder}, but
* that allows for bit more efficient building, using segmented internal
* buffers, and direct access to these buffers.
*/
public final class TextBuilder
{
final static char[] sNoChars = new char[0];
/**
* Size of the first text segment buffer to allocate. Need not contain
* the biggest segment, since new ones will get allocated as needed.
* However, it's sensible to use something that often is big enough
* to contain typical segments.
*/
final static int DEF_INITIAL_BUFFER_SIZE = 500; // 1k
final static int MAX_SEGMENT_LENGTH = 256 * 1024;
final static int INT_SPACE = 0x0020;
// // // Configuration:
private final ReaderConfig _config;
// // // Internal non-shared collector buffers:
/**
* List of segments prior to currently active segment.
*/
private ArrayList<char[]> _segments;
// // // Currently used segment; not (yet) contained in _segments
/**
* Amount of characters in segments in {@link _segments}
*/
private int _segmentSize;
private char[] _currentSegment;
/**
* Number of characters in currently active (last) segment
*/
private int _currentSize;
// // // Temporary caching for Objects to return
/**
* String that will be constructed when the whole contents are
* needed; will be temporarily stored in case asked for again.
*/
private String _resultString;
private char[] _resultArray;
/**
* Indicator for length of data with <code>_resultArray</code>, iff
* the primary indicator (_currentSize) is invalid (-1).
*/
private int _resultLen;
/*
/**********************************************************************
/* Support for decoding, for Typed Access API
/**********************************************************************
*/
private char[] _decodeBuffer;
private int _decodePtr;
private int _decodeEnd;
/*
/**********************************************************************
/* Support for optimizating indentation segments:
/**********************************************************************
*/
/**
* Marker to know if the contents currently stored were created
* using "indentation detection". If so, it's known to be all
* white space
*/
private boolean _isIndentation = false;
// // // Canonical indentation objects (up to 32 spaces, 8 tabs)
public final static int MAX_INDENT_SPACES = 32;
public final static int MAX_INDENT_TABS = 8;
// Let's add one more space at the end, for safety...
private final static String sIndSpaces =
// 123456789012345678901234567890123
"\n ";
private final static char[] sIndSpacesArray = sIndSpaces.toCharArray();
private final static String[] sIndSpacesStrings = new String[sIndSpacesArray.length];
private final static String sIndTabs =
// 1 2 3 4 5 6 7 8 9
"\n\t\t\t\t\t\t\t\t\t";
private final static char[] sIndTabsArray = sIndTabs.toCharArray();
private final static String[] sIndTabsStrings = new String[sIndTabsArray.length];
/*
/**********************************************************************
/* Life-cycle
/**********************************************************************
*/
private TextBuilder(ReaderConfig cfg)
{
_config = cfg;
}
public static TextBuilder createRecyclableBuffer(ReaderConfig cfg)
{
return new TextBuilder(cfg);
}
/**
* Method called to indicate that the underlying buffers should now
* be recycled if they haven't yet been recycled. Although caller
* can still use this text buffer, it is not advisable to call this
* method if that is likely, since next time a buffer is needed,
* buffers need to reallocated.
* Note: calling this method automatically also clears contents
* of the buffer.
*/
public void recycle(boolean force)
{
if (_config != null && _currentSegment != null) {
if (force) {
/* shouldn't call resetWithEmpty, as that would allocate
* initial buffer; but need to inline
*/
_resultString = null;
_resultArray = null;
} else {
/* But if there's non-shared data (ie. buffer is still
* in use), can't return it yet:
*/
if ((_segmentSize + _currentSize) > 0) {
return;
}
}
// If no data (or only shared data), can continue
if (_segments != null && _segments.size() > 0) {
// No need to use anything from list, curr segment not null
_segments.clear();
_segmentSize = 0;
}
char[] buf = _currentSegment;
_currentSegment = null;
_config.freeMediumCBuffer(buf);
}
}
/**
* Method called to clear out any content text buffer may have, and
* initializes and returns the first segment to add characters to.
*/
public char[] resetWithEmpty()
{
_resultString = null;
_resultArray = null;
_isIndentation = false;
// And then reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
/* Since the current segment should be the biggest one
* (as we allocate 50% bigger each time), let's retain it,
* and clear others
*/
_segments.clear();
_segmentSize = 0;
}
_currentSize = 0;
if (_currentSegment == null) {
_currentSegment = allocBuffer(0);
}
return _currentSegment;
}
public void resetWithIndentation(int indCharCount, char indChar)
{
// First reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
_segments.clear();
_segmentSize = 0;
}
_currentSize = -1;
_isIndentation = true;
String text;
int strlen = indCharCount+1;
_resultLen = strlen;
if (indChar == '\t') { // tabs?
_resultArray = sIndTabsArray;
text = sIndTabsStrings[indCharCount];
if (text == null) {
sIndTabsStrings[indCharCount] = text = sIndTabs.substring(0, strlen);
}
} else { // nope, spaces (should assert indChar?)
_resultArray = sIndSpacesArray;
text = sIndSpacesStrings[indCharCount];
if (text == null) {
sIndSpacesStrings[indCharCount] = text = sIndSpaces.substring(0, strlen);
}
}
_resultString = text;
}
/**
* Method called to initialize the buffer with just a single char
*/
public void resetWithChar(char c)
{
_resultString = null;
_resultArray = null;
_isIndentation = false;
// And then reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
_segments.clear();
_segmentSize = 0;
}
_currentSize = 1;
if (_currentSegment == null) {
_currentSegment = allocBuffer(1);
}
_currentSegment[0] = c;
}
public void resetWithSurrogate(int c)
{
_resultString = null;
_resultArray = null;
_isIndentation = false;
// And then reset internal input buffers, if necessary:
if (_segments != null && _segments.size() > 0) {
_segments.clear();
_segmentSize = 0;
}
_currentSize = 2;
if (_currentSegment == null) {
_currentSegment = allocBuffer(2);
}
_currentSegment[0] = (char) (0xD800 | (c >> 10));
_currentSegment[1] = (char) (0xDC00 | (c & 0x3FF));
}
public char[] getBufferWithoutReset()
{
return _currentSegment;
}
/*
/**********************************************************************
/* Accessors for implementing StAX interface:
/**********************************************************************
*/
/**
* @return Number of characters currently stored by this collector
*/
public int size()
{
int size = _currentSize;
// Will be -1 only if we have shared white space
if (size < 0) {
return _resultLen;
}
return size + _segmentSize;
}
public char[] getTextBuffer()
{
// Does it fit in just one segment?
if (_segments == null || _segments.size() == 0) {
// But is it whitespace, actually?
if (_resultArray != null) {
return _resultArray;
}
return _currentSegment;
}
// Nope, need to have/create a non-segmented array and return it
return contentsAsArray();
}
/*
/**********************************************************************
/* Accessors for text contained
/**********************************************************************
*/
public String contentsAsString()
{
if (_resultString == null) {
// Has array been requested? Can make a shortcut, if so:
if (_resultArray != null) {
_resultString = new String(_resultArray);
} else {
// Let's optimize common case: nothing in extra segments:
int segLen = _segmentSize;
int currLen = _currentSize;
if (segLen == 0) {
_resultString = (currLen == 0) ? "" : new String(_currentSegment, 0, currLen);
return _resultString;
}
// Nope, need to combine:
StringBuilder sb = new StringBuilder(segLen + currLen);
// First stored segments
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] curr = (char[]) _segments.get(i);
sb.append(curr, 0, curr.length);
}
}
// And finally, current segment:
sb.append(_currentSegment, 0, currLen);
_resultString = sb.toString();
}
}
return _resultString;
}
public char[] contentsAsArray()
{
char[] result = _resultArray;
if (result == null) {
_resultArray = result = buildResultArray();
}
return result;
}
public int contentsToArray(int srcStart, char[] dst, int dstStart, int len) {
/* Could also check if we have array, but that'd only help with
* brain dead clients that get full array first, then segments...
* which hopefully aren't that common
*/
// Copying from segmented array is bit more involved:
int totalAmount = 0;
if (_segments != null) {
for (int i = 0, segc = _segments.size(); i < segc; ++i) {
char[] segment = (char[]) _segments.get(i);
int segLen = segment.length;
int amount = segLen - srcStart;
if (amount < 1) { // nothing from this segment?
srcStart -= segLen;
continue;
}
if (amount >= len) { // can get rest from this segment?
System.arraycopy(segment, srcStart, dst, dstStart, len);
return (totalAmount + len);
}
// Can get some from this segment, offset becomes zero:
System.arraycopy(segment, srcStart, dst, dstStart, amount);
totalAmount += amount;
dstStart += amount;
len -= amount;
srcStart = 0;
}
}
// Need to copy anything from last segment?
if (len > 0) {
int maxAmount = _currentSize - srcStart;
if (len > maxAmount) {
len = maxAmount;
}
if (len > 0) { // should always be true
System.arraycopy(_currentSegment, srcStart, dst, dstStart, len);
totalAmount += len;
}
}
return totalAmount;
}
/**
* Method that will stream contents of this buffer into specified
* Writer.
*/
public int rawContentsTo(Writer w)
throws IOException
{
// Let's first see if we have created helper objects:
if (_resultArray != null) {
w.write(_resultArray);
return _resultArray.length;
}
if (_resultString != null) {
w.write(_resultString);
return _resultString.length();
}
// Nope, need to do full segmented output
int rlen = 0;
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] ch = (char[]) _segments.get(i);
w.write(ch);
rlen += ch.length;
}
}
if (_currentSize > 0) {
w.write(_currentSegment, 0, _currentSize);
rlen += _currentSize;
}
return rlen;
}
public boolean isAllWhitespace()
{
if (_isIndentation) {
return true;
}
// Need to do full segmented output, otherwise
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] buf = (char[]) _segments.get(i);
for (int j = 0, len2 = buf.length; j < len2; ++j) {
if (buf[j] > 0x0020) {
return false;
}
}
}
}
char[] buf = _currentSegment;
for (int i = 0, len = _currentSize; i < len; ++i) {
if (buf[i] > 0x0020) {
return false;
}
}
return true;
}
/*
* Method that can be used to check if the contents of the buffer end
* in specified String.
*
* @return True if the textual content buffer contains ends with the
* specified String; false otherwise
public boolean endsWith(String str)
{
int segIndex = (_segments == null) ? 0 : _segments.size();
int inIndex = str.length() - 1;
char[] buf = _currentSegment;
int bufIndex = _currentSize-1;
while (inIndex >= 0) {
if (str.charAt(inIndex) != buf[bufIndex]) {
return false;
}
if (--inIndex == 0) {
break;
}
if (--bufIndex < 0) {
if (--segIndex < 0) { // no more data?
return false;
}
buf = (char[]) _segments.get(segIndex);
bufIndex = buf.length-1;
}
}
return true;
}
*/
/**
* Note: it is assumed that this method is not used often enough to
* be a bottleneck, or for long segments. Based on this, it is optimized
* for common simple cases where there is only one single character
* segment to use; fallback for other cases is to create such segment.
*/
public boolean equalsString(String str)
{
int expLen = str.length();
// Otherwise, segments:
if (expLen != size()) {
return false;
}
char[] seg;
if (_segments == null || _segments.size() == 0) {
// just one segment, still easy
seg = _currentSegment;
} else {
/* Ok; this is the sub-optimal case. Could obviously juggle through
* segments, but probably not worth the hassle, we seldom if ever
* get here...
*/
seg = contentsAsArray();
}
for (int i = 0; i < expLen; ++i) {
if (seg[i] != str.charAt(i)) {
return false;
}
}
return true;
}
/*
/**********************************************************************
/* Methods for generating SAX events
/**********************************************************************
*/
/**
* This is a specialized "accessor" method, which is basically
* to fire SAX characters() events in an optimal way, based on
* which internal buffers are being used
*/
public void fireSaxCharacterEvents(ContentHandler h)
throws SAXException
{
if (_resultArray != null) { // only happens for indentation
h.characters(_resultArray, 0, _resultLen);
} else {
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] ch = (char[]) _segments.get(i);
h.characters(ch, 0, ch.length);
}
}
if (_currentSize > 0) {
h.characters(_currentSegment, 0, _currentSize);
}
}
}
public void fireSaxSpaceEvents(ContentHandler h)
throws SAXException
{
if (_resultArray != null) { // only happens for indentation
h.ignorableWhitespace(_resultArray, 0, _resultLen);
} else {
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] ch = (char[]) _segments.get(i);
h.ignorableWhitespace(ch, 0, ch.length);
}
}
if (_currentSize > 0) {
h.ignorableWhitespace(_currentSegment, 0, _currentSize);
}
}
}
public void fireSaxCommentEvent(LexicalHandler h)
throws SAXException
{
// Comment can not be split, so may need to combine the array
if (_resultArray != null) { // only happens for indentation
h.comment(_resultArray, 0, _resultLen);
} else if (_segments != null && _segments.size() > 0) {
char[] ch = contentsAsArray();
h.comment(ch, 0, ch.length);
} else {
h.comment(_currentSegment, 0, _currentSize);
}
}
/*
/**********************************************************************
/* Support for validation
/**********************************************************************
*/
/*
public void validateText(XMLValidator vld, boolean lastSegment)
throws XMLValidationException
{
// Can either create a combine buffer, or construct
// a String. While former could be more efficient, let's do latter
// for now since current validator implementations work better
// with Strings.
vld.validateText(contentsAsString(), lastSegment);
}
*/
/*
/**********************************************************************
/* Public mutators:
/**********************************************************************
*/
public void append(char c)
{
_resultString = null;
_resultArray = null;
// Room in current segment?
char[] curr = _currentSegment;
if (_currentSize >= curr.length) {
expand(1);
}
curr[_currentSize++] = c;
}
public void appendSurrogate(int surr)
{
append((char) (0xD800 | (surr >> 10)));
append((char) (0xDC00 | (surr & 0x3FF)));
}
public void append(char[] c, int start, int len)
{
_resultString = null;
_resultArray = null;
// Room in current segment?
char[] curr = _currentSegment;
int max = curr.length - _currentSize;
if (max >= len) {
System.arraycopy(c, start, curr, _currentSize, len);
_currentSize += len;
} else {
// No room for all, need to copy part(s):
if (max > 0) {
System.arraycopy(c, start, curr, _currentSize, max);
start += max;
len -= max;
}
/* And then allocate new segment; we are guaranteed to now
* have enough room in segment.
*/
expand(len); // note: curr != _currentSegment after this
System.arraycopy(c, start, _currentSegment, 0, len);
_currentSize = len;
}
}
public void append(String str)
{
_resultString = null;
_resultArray = null;
int len = str.length();
// Room in<SUF>
char[] curr = _currentSegment;
int max = curr.length - _currentSize;
if (max >= len) {
str.getChars(0, len, curr, _currentSize);
_currentSize += len;
} else {
// No room for all, need to copy part(s):
if (max > 0) {
str.getChars(0, max, curr, _currentSize);
len -= max;
}
/* And then allocate new segment; we are guaranteed to now
* have enough room in segment.
*/
expand(len);
str.getChars(max, max+len, _currentSegment, 0);
_currentSize = len;
}
}
/*
/**********************************************************************
/* Raw access, for high-performance use:
/**********************************************************************
*/
public int getCurrentLength() {
return _currentSize;
}
public void setCurrentLength(int len) {
_currentSize = len;
}
public char[] finishCurrentSegment()
{
if (_segments == null) {
_segments = new ArrayList<char[]>();
}
_segments.add(_currentSegment);
int oldLen = _currentSegment.length;
_segmentSize += oldLen;
char[] curr = new char[calcNewSize(oldLen)];
_currentSize = 0;
_currentSegment = curr;
return curr;
}
private int calcNewSize(int latestSize)
{
// Let's grow segments by 50%, when over 8k
int incr = (latestSize < 8000) ? latestSize : (latestSize >> 1);
int size = latestSize + incr;
// but let's not create too big chunks
return Math.min(size, MAX_SEGMENT_LENGTH);
}
/*
/**********************************************************************
/* Methods for implementing Typed Access API
/**********************************************************************
*/
/**
* Method called by the stream reader to decode space-separated tokens
* that are part of the current text event (contents of which
* are stored within this buffer), using given decoder.
*/
public int decodeElements(TypedArrayDecoder tad, boolean reset)
throws TypedXMLStreamException
{
if (reset) {
resetForDecode();
}
int ptr = _decodePtr;
final char[] buf = _decodeBuffer;
int count = 0;
// And then let's decode
int start = ptr;
try {
final int end = _decodeEnd;
decode_loop:
while (ptr < end) {
// First, any space to skip?
while (buf[ptr] <= INT_SPACE) {
if (++ptr >= end) {
break decode_loop;
}
}
// Then let's figure out non-space char (token)
start = ptr;
++ptr;
while (ptr < end && buf[ptr] > INT_SPACE) {
++ptr;
}
++count;
int tokenEnd = ptr;
++ptr; // to skip trailing space (or, beyond end)
// And there we have it
if (tad.decodeValue(buf, start, tokenEnd)) {
break;
}
_decodePtr = ptr;
}
_decodePtr = ptr;
} catch (IllegalArgumentException iae) {
// Need to convert to a checked stream exception to return lexical
// -1 to move it back after being advanced earlier (to skip trailing space)
String lexical = new String(buf, start, (ptr-start-1));
throw new TypedXMLStreamException(lexical, iae.getMessage(), iae);
}
return count;
}
/**
* Method called to initialize given base64 decoder with data
* contained in this text buffer (for the current event).
*/
public void resetForBinaryDecode(Base64Variant v, CharArrayBase64Decoder dec, boolean firstChunk)
{
// just one special case, indentation...
if (_segments == null || _segments.size() == 0) { // single segment
if (_isIndentation) { // but special one, indent/ws
dec.init(v, firstChunk, _resultArray, 0, _resultArray.length, null);
return;
}
}
dec.init(v, firstChunk, _currentSegment, 0, _currentSize, _segments);
}
private final void resetForDecode()
{
/* This is very similar to getTextBuffer(), except
* for assignment to _decodeXxx fields
*/
_decodePtr = 0;
if (_segments == null || _segments.size() == 0) { // single segment
if (_isIndentation) { // but special one, indent/ws
_decodeBuffer = _resultArray;
_decodeEnd = _resultArray.length;
} else { // nope, just a regular buffer
_decodeBuffer = _currentSegment;
_decodeEnd = _currentSize;
}
} else {
// Nope, need to have/create a non-segmented array and return it
_decodeBuffer = contentsAsArray();
_decodeEnd = _decodeBuffer.length;
}
}
/*
/**********************************************************************
/* Standard methods:
/**********************************************************************
*/
/**
* Note: calling this method may not be as efficient as calling
* {@link #contentsAsString}, since it is guaranteed that resulting
* String is NOT cached (to ensure we see no stale data)
*/
@Override
public String toString() {
_resultString = null;
_resultArray = null;
return contentsAsString();
}
/*
/**********************************************************************
/* Internal methods:
/**********************************************************************
*/
private final char[] allocBuffer(int minNeeded)
{
int size = Math.max(DEF_INITIAL_BUFFER_SIZE, minNeeded);
char[] buf = null;
if (_config != null) {
buf = _config.allocMediumCBuffer(size);
if (buf != null) {
return buf;
}
}
return new char[size];
}
/**
* Method called when current segment is full, to allocate new
* segment.
*/
private void expand(int roomNeeded)
{
// First, let's move current segment to segment list:
if (_segments == null) {
_segments = new ArrayList<char[]>();
}
char[] curr = _currentSegment;
_segments.add(curr);
int oldLen = curr.length;
_segmentSize += oldLen;
int newSize = Math.max(roomNeeded, calcNewSize(oldLen));
curr = new char[newSize];
_currentSize = 0;
_currentSegment = curr;
}
private char[] buildResultArray()
{
if (_resultString != null) { // Can take a shortcut...
return _resultString.toCharArray();
}
char[] result;
int size = size();
if (size < 1) {
return sNoChars;
}
int offset = 0;
result = new char[size];
if (_segments != null) {
for (int i = 0, len = _segments.size(); i < len; ++i) {
char[] curr = _segments.get(i);
int currLen = curr.length;
System.arraycopy(curr, 0, result, offset, currLen);
offset += currLen;
}
}
System.arraycopy(_currentSegment, 0, result, offset, _currentSize);
return result;
}
}
|
90784_7 | package com.fasterxml.jackson.datatype.hibernate6;
import java.beans.Introspector;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.hibernate.proxy.pojo.BasicLazyInitializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap;
import com.fasterxml.jackson.databind.util.NameTransformer;
import jakarta.persistence.EntityNotFoundException;
/**
* Serializer to use for values proxied using {@link HibernateProxy}.
*<p>
* TODO: should try to make this work more like Jackson
* {@code BeanPropertyWriter}, possibly sub-classing
* it -- it handles much of functionality we need, and has
* access to more information than value serializers (like
* this one) have.
*/
public class Hibernate6ProxySerializer
extends JsonSerializer<HibernateProxy>
implements ContextualSerializer
{
/**
* Property that has proxy value to handle
*/
protected final BeanProperty _property;
protected final boolean _forceLazyLoading;
protected final boolean _serializeIdentifier;
protected final boolean _nullMissingEntities;
protected final boolean _wrappedIdentifier;
protected final Mapping _mapping;
// For datatype-hibernate#97
protected final NameTransformer _unwrapper;
/**
* For efficient serializer lookup, let's use this; most
* of the time, there's just one type and one serializer.
*/
protected PropertySerializerMap _dynamicSerializers;
/*
/**********************************************************************
/* Life cycle
/**********************************************************************
*/
public Hibernate6ProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier,
boolean nullMissingEntities, boolean wrappedIdentifier,
Mapping mapping)
{
this(forceLazyLoading, serializeIdentifier, nullMissingEntities, wrappedIdentifier,
mapping, null, null);
}
public Hibernate6ProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier,
boolean nullMissingEntities, boolean wrappedIdentifier,
Mapping mapping, BeanProperty property, NameTransformer unwrapper)
{
_forceLazyLoading = forceLazyLoading;
_serializeIdentifier = serializeIdentifier;
_nullMissingEntities = nullMissingEntities;
_wrappedIdentifier = wrappedIdentifier;
_mapping = mapping;
_property = property;
_unwrapper = unwrapper;
_dynamicSerializers = PropertySerializerMap.emptyForProperties();
}
protected Hibernate6ProxySerializer(Hibernate6ProxySerializer base,
BeanProperty property, NameTransformer unwrapper)
{
_forceLazyLoading = base._forceLazyLoading;
_serializeIdentifier = base._serializeIdentifier;
_nullMissingEntities = base._nullMissingEntities;
_wrappedIdentifier = base._wrappedIdentifier;
_mapping = base._mapping;
_property = property;
_unwrapper = unwrapper;
_dynamicSerializers = PropertySerializerMap.emptyForProperties();
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
return new Hibernate6ProxySerializer(this, property, _unwrapper);
}
@Override
public JsonSerializer<HibernateProxy> unwrappingSerializer(final NameTransformer unwrapper) {
return new Hibernate6ProxySerializer(this, _property, unwrapper);
}
@Override
public boolean isUnwrappingSerializer()
{
return _unwrapper != null;
}
/*
/**********************************************************************
/* JsonSerializer impl
/**********************************************************************
*/
@Override
public boolean isEmpty(SerializerProvider provider, HibernateProxy value) {
return (value == null) || (findProxied(value) == null);
}
@Override
public void serialize(HibernateProxy value, JsonGenerator g, SerializerProvider provider)
throws IOException
{
Object proxiedValue = findProxied(value);
// TODO: figure out how to suppress nulls, if necessary? (too late for that here)
if (proxiedValue == null) {
provider.defaultSerializeNull(g);
return;
}
findSerializer(provider, proxiedValue).serialize(proxiedValue, g, provider);
}
@Override
public void serializeWithType(HibernateProxy value, JsonGenerator g, SerializerProvider provider,
TypeSerializer typeSer)
throws IOException
{
Object proxiedValue = findProxied(value);
if (proxiedValue == null) {
provider.defaultSerializeNull(g);
return;
}
/* This isn't exactly right, since type serializer really refers to proxy
* object, not value. And we really don't either know static type (necessary
* to know how to apply additional type info) or other things;
* so it's not going to work well. But... we'll do out best.
*/
findSerializer(provider, proxiedValue).serializeWithType(proxiedValue, g, provider, typeSer);
}
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
throws JsonMappingException
{
SerializerProvider prov = visitor.getProvider();
if ((prov == null) || (_property == null)) {
super.acceptJsonFormatVisitor(visitor, typeHint);
} else {
JavaType type = _property.getType();
prov.findPrimaryPropertySerializer(type, _property)
.acceptJsonFormatVisitor(visitor, type);
}
}
/*
/**********************************************************************
/* Helper methods
/**********************************************************************
*/
protected JsonSerializer<Object> findSerializer(SerializerProvider provider, Object value)
throws IOException
{
/* TODO: if Hibernate did use generics, or we wanted to allow use of Jackson
* annotations to indicate type, should take that into account.
*/
Class<?> type = value.getClass();
/* we will use a map to contain serializers found so far, keyed by type:
* this avoids potentially costly lookup from global caches and/or construction
* of new serializers
*/
/* 18-Oct-2013, tatu: Whether this is for the primary property or secondary is
* really anyone's guess at this point; proxies can exist at any level?
*/
PropertySerializerMap.SerializerAndMapResult result =
_dynamicSerializers.findAndAddPrimarySerializer(type, provider, _property);
if (_dynamicSerializers != result.map) {
_dynamicSerializers = result.map;
}
if (_unwrapper != null)
{
return result.serializer.unwrappingSerializer(_unwrapper);
}
return result.serializer;
}
/**
* Helper method for finding value being proxied, if it is available
* or if it is to be forced to be loaded.
*/
protected Object findProxied(HibernateProxy proxy)
{
LazyInitializer init = proxy.getHibernateLazyInitializer();
if (!_forceLazyLoading && init.isUninitialized()) {
if (_serializeIdentifier) {
final Object idValue = init.getIdentifier();
if (_wrappedIdentifier) {
HashMap<String, Object> map = new HashMap<>();
map.put(getIdentifierPropertyName(init), idValue);
return map;
} else {
return idValue;
}
}
return null;
}
try {
return init.getImplementation();
} catch (EntityNotFoundException e) {
if (_nullMissingEntities) {
return null;
} else {
throw e;
}
}
}
/**
* Helper method to retrieve the name of the identifier property of the
* specified lazy initializer.
* @param init Lazy initializer to obtain identifier property name from.
* @return Name of the identity property of the specified lazy initializer.
*/
private String getIdentifierPropertyName(final LazyInitializer init) {
String idName;
if (_mapping != null) {
idName = _mapping.getIdentifierPropertyName(init.getEntityName());
} else {
idName = ProxySessionReader.getIdentifierPropertyName(init);
if (idName == null) {
idName = ProxyReader.getIdentifierPropertyName(init);
if (idName == null) {
idName = init.getEntityName();
}
}
}
return idName;
}
/**
* Inspects a Hibernate proxy to try and determine the name of the identifier property
* (Hibernate proxies know the getter of the identifier property because it receives special
* treatment in the invocation handler). Alas, the field storing the method reference is
* private and has no getter, so we must resort to ugly reflection hacks to read its value ...
*/
protected static class ProxyReader {
// static final so the JVM can inline the lookup
private static final Field getIdentifierMethodField;
static {
try {
getIdentifierMethodField = BasicLazyInitializer.class.getDeclaredField("getIdentifierMethod");
getIdentifierMethodField.setAccessible(true);
} catch (Exception e) {
// should never happen: the field exists in all versions of hibernate 4 and 5
throw new RuntimeException(e);
}
}
/**
* @return the name of the identifier property, or null if the name could not be determined
*/
static String getIdentifierPropertyName(LazyInitializer init) {
try {
Method idGetter = (Method) getIdentifierMethodField.get(init);
if (idGetter == null) {
return null;
}
String name = idGetter.getName();
if (name.startsWith("get")) {
name = Introspector.decapitalize(name.substring(3));
}
return name;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
/**
* Hibernate 5.2 broke abi compatibility of org.hibernate.proxy.LazyInitializer.getSession()
* The api contract changed
* from org.hibernate.proxy.LazyInitializer.getSession()Lorg.hibernate.engine.spi.SessionImplementor;
* to org.hibernate.proxy.LazyInitializer.getSession()Lorg.hibernate.engine.spi.SharedSessionContractImplementor
*
* On hibernate 5.2 the interface SessionImplementor extends SharedSessionContractImplementor.
* And an instance of org.hibernate.internal.SessionImpl is returned from getSession().
*/
protected static class ProxySessionReader {
/**
* The getSession method must be executed using reflection for compatibility purpose.
* For efficiency keep the method cached.
*/
protected static final Method lazyInitializerGetSessionMethod;
static {
try {
lazyInitializerGetSessionMethod = LazyInitializer.class.getMethod("getSession");
} catch (Exception e) {
// should never happen: the class and method exists in all versions of hibernate 5
throw new RuntimeException(e);
}
}
static String getIdentifierPropertyName(LazyInitializer init) {
final Object session;
try{
session = lazyInitializerGetSessionMethod.invoke(init);
} catch (Exception e) {
// Should never happen
throw new RuntimeException(e);
}
if(session instanceof SessionImplementor){
SessionFactoryImplementor factory = ((SessionImplementor)session).getFactory();
return factory.getIdentifierPropertyName(init.getEntityName());
}else if (session != null) {
// Should never happen: session should be an instance of org.hibernate.internal.SessionImpl
// factory = session.getClass().getMethod("getFactory").invoke(session);
throw new RuntimeException("Session is not instance of SessionImplementor");
}
return null;
}
}
}
| FasterXML/jackson-datatype-hibernate | hibernate6/src/main/java/com/fasterxml/jackson/datatype/hibernate6/Hibernate6ProxySerializer.java | 3,482 | /*
/**********************************************************************
/* Helper methods
/**********************************************************************
*/ | block_comment | nl | package com.fasterxml.jackson.datatype.hibernate6;
import java.beans.Introspector;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.hibernate.proxy.pojo.BasicLazyInitializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap;
import com.fasterxml.jackson.databind.util.NameTransformer;
import jakarta.persistence.EntityNotFoundException;
/**
* Serializer to use for values proxied using {@link HibernateProxy}.
*<p>
* TODO: should try to make this work more like Jackson
* {@code BeanPropertyWriter}, possibly sub-classing
* it -- it handles much of functionality we need, and has
* access to more information than value serializers (like
* this one) have.
*/
public class Hibernate6ProxySerializer
extends JsonSerializer<HibernateProxy>
implements ContextualSerializer
{
/**
* Property that has proxy value to handle
*/
protected final BeanProperty _property;
protected final boolean _forceLazyLoading;
protected final boolean _serializeIdentifier;
protected final boolean _nullMissingEntities;
protected final boolean _wrappedIdentifier;
protected final Mapping _mapping;
// For datatype-hibernate#97
protected final NameTransformer _unwrapper;
/**
* For efficient serializer lookup, let's use this; most
* of the time, there's just one type and one serializer.
*/
protected PropertySerializerMap _dynamicSerializers;
/*
/**********************************************************************
/* Life cycle
/**********************************************************************
*/
public Hibernate6ProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier,
boolean nullMissingEntities, boolean wrappedIdentifier,
Mapping mapping)
{
this(forceLazyLoading, serializeIdentifier, nullMissingEntities, wrappedIdentifier,
mapping, null, null);
}
public Hibernate6ProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier,
boolean nullMissingEntities, boolean wrappedIdentifier,
Mapping mapping, BeanProperty property, NameTransformer unwrapper)
{
_forceLazyLoading = forceLazyLoading;
_serializeIdentifier = serializeIdentifier;
_nullMissingEntities = nullMissingEntities;
_wrappedIdentifier = wrappedIdentifier;
_mapping = mapping;
_property = property;
_unwrapper = unwrapper;
_dynamicSerializers = PropertySerializerMap.emptyForProperties();
}
protected Hibernate6ProxySerializer(Hibernate6ProxySerializer base,
BeanProperty property, NameTransformer unwrapper)
{
_forceLazyLoading = base._forceLazyLoading;
_serializeIdentifier = base._serializeIdentifier;
_nullMissingEntities = base._nullMissingEntities;
_wrappedIdentifier = base._wrappedIdentifier;
_mapping = base._mapping;
_property = property;
_unwrapper = unwrapper;
_dynamicSerializers = PropertySerializerMap.emptyForProperties();
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
return new Hibernate6ProxySerializer(this, property, _unwrapper);
}
@Override
public JsonSerializer<HibernateProxy> unwrappingSerializer(final NameTransformer unwrapper) {
return new Hibernate6ProxySerializer(this, _property, unwrapper);
}
@Override
public boolean isUnwrappingSerializer()
{
return _unwrapper != null;
}
/*
/**********************************************************************
/* JsonSerializer impl
/**********************************************************************
*/
@Override
public boolean isEmpty(SerializerProvider provider, HibernateProxy value) {
return (value == null) || (findProxied(value) == null);
}
@Override
public void serialize(HibernateProxy value, JsonGenerator g, SerializerProvider provider)
throws IOException
{
Object proxiedValue = findProxied(value);
// TODO: figure out how to suppress nulls, if necessary? (too late for that here)
if (proxiedValue == null) {
provider.defaultSerializeNull(g);
return;
}
findSerializer(provider, proxiedValue).serialize(proxiedValue, g, provider);
}
@Override
public void serializeWithType(HibernateProxy value, JsonGenerator g, SerializerProvider provider,
TypeSerializer typeSer)
throws IOException
{
Object proxiedValue = findProxied(value);
if (proxiedValue == null) {
provider.defaultSerializeNull(g);
return;
}
/* This isn't exactly right, since type serializer really refers to proxy
* object, not value. And we really don't either know static type (necessary
* to know how to apply additional type info) or other things;
* so it's not going to work well. But... we'll do out best.
*/
findSerializer(provider, proxiedValue).serializeWithType(proxiedValue, g, provider, typeSer);
}
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
throws JsonMappingException
{
SerializerProvider prov = visitor.getProvider();
if ((prov == null) || (_property == null)) {
super.acceptJsonFormatVisitor(visitor, typeHint);
} else {
JavaType type = _property.getType();
prov.findPrimaryPropertySerializer(type, _property)
.acceptJsonFormatVisitor(visitor, type);
}
}
/*
/**********************************************************************
/* Helper methods
<SUF>*/
protected JsonSerializer<Object> findSerializer(SerializerProvider provider, Object value)
throws IOException
{
/* TODO: if Hibernate did use generics, or we wanted to allow use of Jackson
* annotations to indicate type, should take that into account.
*/
Class<?> type = value.getClass();
/* we will use a map to contain serializers found so far, keyed by type:
* this avoids potentially costly lookup from global caches and/or construction
* of new serializers
*/
/* 18-Oct-2013, tatu: Whether this is for the primary property or secondary is
* really anyone's guess at this point; proxies can exist at any level?
*/
PropertySerializerMap.SerializerAndMapResult result =
_dynamicSerializers.findAndAddPrimarySerializer(type, provider, _property);
if (_dynamicSerializers != result.map) {
_dynamicSerializers = result.map;
}
if (_unwrapper != null)
{
return result.serializer.unwrappingSerializer(_unwrapper);
}
return result.serializer;
}
/**
* Helper method for finding value being proxied, if it is available
* or if it is to be forced to be loaded.
*/
protected Object findProxied(HibernateProxy proxy)
{
LazyInitializer init = proxy.getHibernateLazyInitializer();
if (!_forceLazyLoading && init.isUninitialized()) {
if (_serializeIdentifier) {
final Object idValue = init.getIdentifier();
if (_wrappedIdentifier) {
HashMap<String, Object> map = new HashMap<>();
map.put(getIdentifierPropertyName(init), idValue);
return map;
} else {
return idValue;
}
}
return null;
}
try {
return init.getImplementation();
} catch (EntityNotFoundException e) {
if (_nullMissingEntities) {
return null;
} else {
throw e;
}
}
}
/**
* Helper method to retrieve the name of the identifier property of the
* specified lazy initializer.
* @param init Lazy initializer to obtain identifier property name from.
* @return Name of the identity property of the specified lazy initializer.
*/
private String getIdentifierPropertyName(final LazyInitializer init) {
String idName;
if (_mapping != null) {
idName = _mapping.getIdentifierPropertyName(init.getEntityName());
} else {
idName = ProxySessionReader.getIdentifierPropertyName(init);
if (idName == null) {
idName = ProxyReader.getIdentifierPropertyName(init);
if (idName == null) {
idName = init.getEntityName();
}
}
}
return idName;
}
/**
* Inspects a Hibernate proxy to try and determine the name of the identifier property
* (Hibernate proxies know the getter of the identifier property because it receives special
* treatment in the invocation handler). Alas, the field storing the method reference is
* private and has no getter, so we must resort to ugly reflection hacks to read its value ...
*/
protected static class ProxyReader {
// static final so the JVM can inline the lookup
private static final Field getIdentifierMethodField;
static {
try {
getIdentifierMethodField = BasicLazyInitializer.class.getDeclaredField("getIdentifierMethod");
getIdentifierMethodField.setAccessible(true);
} catch (Exception e) {
// should never happen: the field exists in all versions of hibernate 4 and 5
throw new RuntimeException(e);
}
}
/**
* @return the name of the identifier property, or null if the name could not be determined
*/
static String getIdentifierPropertyName(LazyInitializer init) {
try {
Method idGetter = (Method) getIdentifierMethodField.get(init);
if (idGetter == null) {
return null;
}
String name = idGetter.getName();
if (name.startsWith("get")) {
name = Introspector.decapitalize(name.substring(3));
}
return name;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
/**
* Hibernate 5.2 broke abi compatibility of org.hibernate.proxy.LazyInitializer.getSession()
* The api contract changed
* from org.hibernate.proxy.LazyInitializer.getSession()Lorg.hibernate.engine.spi.SessionImplementor;
* to org.hibernate.proxy.LazyInitializer.getSession()Lorg.hibernate.engine.spi.SharedSessionContractImplementor
*
* On hibernate 5.2 the interface SessionImplementor extends SharedSessionContractImplementor.
* And an instance of org.hibernate.internal.SessionImpl is returned from getSession().
*/
protected static class ProxySessionReader {
/**
* The getSession method must be executed using reflection for compatibility purpose.
* For efficiency keep the method cached.
*/
protected static final Method lazyInitializerGetSessionMethod;
static {
try {
lazyInitializerGetSessionMethod = LazyInitializer.class.getMethod("getSession");
} catch (Exception e) {
// should never happen: the class and method exists in all versions of hibernate 5
throw new RuntimeException(e);
}
}
static String getIdentifierPropertyName(LazyInitializer init) {
final Object session;
try{
session = lazyInitializerGetSessionMethod.invoke(init);
} catch (Exception e) {
// Should never happen
throw new RuntimeException(e);
}
if(session instanceof SessionImplementor){
SessionFactoryImplementor factory = ((SessionImplementor)session).getFactory();
return factory.getIdentifierPropertyName(init.getEntityName());
}else if (session != null) {
// Should never happen: session should be an instance of org.hibernate.internal.SessionImpl
// factory = session.getClass().getMethod("getFactory").invoke(session);
throw new RuntimeException("Session is not instance of SessionImplementor");
}
return null;
}
}
}
|
107948_4 | /* LanguageTool, a natural language style checker
* Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers.nl;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Dutch;
import org.languagetool.tokenizers.SRXSentenceTokenizer;
/**
* @author Daniel Naber
* @author Adapted by R. Baars for Dutch
* @author Pander OpenTaal added examples from Wikipedia and Taaladvies
*/
public class DutchSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Dutch());
@Test
public void testTokenize() {
// NOTE: sentences here need to end with a space character so they
// have correct whitespace when appended:
testSplit("Dit is een zin.");
testSplit("Dit is een zin. ", "Nog een.");
testSplit("Een zin! ", "Nog een.");
testSplit("‘Dat meen je niet!’ kirde Mandy.");
testSplit("Een zin... ", "Nog een.");
testSplit("'En nu.. daden!' aan premier Mark Rutte.");
testSplit("Op http://www.test.de vind je een website.");
testSplit("De brief is op 3-10 gedateerd.");
testSplit("De brief is op 31-1 gedateerd.");
testSplit("De brief is op 3-10-2000 gedateerd.");
testSplit("Vandaag is het 13-12-2004.");
testSplit("Op 24.09 begint het.");
testSplit("Om 17:00 begint het.");
testSplit("In paragraaf 3.9.1 is dat beschreven.");
testSplit("Januari jl. is dat vastgelegd.");
testSplit("Appel en pruimen enz. werden gekocht.");
testSplit("De afkorting n.v.t. betekent niet van toepassing.");
testSplit("Bla et al. blah blah.");
testSplit("Dat is,, of het is bla.");
testSplit("Dat is het.. ", "Zo gaat het verder.");
testSplit("Dit hier is een(!) zin.");
testSplit("Dit hier is een(!!) zin.");
testSplit("Dit hier is een(?) zin.");
testSplit("Dit hier is een(???) zin.");
testSplit("Dit hier is een(???) zin.");
testSplit("Als voetballer wordt hij nooit een prof. ", "Maar prof. N.A.W. Th.Ch. Janssen wordt dat wel.");
// TODO, zin na dubbele punt
testSplit("Dat was het: helemaal niets.");
testSplit("Dat was het: het is een nieuwe zin.");
// https://nl.wikipedia.org/wiki/Aanhalingsteken
testSplit("Jan zei: \"Hallo.\"");
testSplit("Jan zei: “Hallo.”");
testSplit("„Hallo,” zei Jan, „waar ga je naartoe?”");
testSplit("„Gisteren”, zei Jan, „was het veel beter weer.”");
testSplit("Jan zei: „Annette zei ‚Hallo’.”");
testSplit("Jan zei: “Annette zei ‘Hallo’.”");
testSplit("Jan zei: «Annette zei ‹Hallo›.»");
testSplit("Wegens zijn „ziekte” hoefde hij niet te werken.");
testSplit("de letter „a”");
testSplit("het woord „beta” is afkomstig van ...");
// http://taaladvies.net/taal/advies/vraag/11
testSplit("De voorzitter zei: 'Ik zie hier geen been in.'");
testSplit("De voorzitter zei: \"Ik zie hier geen been in.\"");
testSplit("De koning zei: \"Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.\"");
testSplit("De koning zei: 'Ik herinner me nog dat iemand \"Vive la république\" riep tijdens mijn eedaflegging.'");
testSplit("De koning zei: 'Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.'");
testSplit("Otto dacht: wat een nare verhalen hoor je toch tegenwoordig.");
// http://taaladvies.net/taal/advies/vraag/871
testSplit("'Ik vrees', zei Rob, 'dat de brug zal instorten.'");
testSplit("'Ieder land', aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'");
testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'");
testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'");
testSplit("'Ik vrees,' zei Rob, 'dat de brug zal instorten.'");
testSplit("'Ieder land,' aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'");
testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'");
testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'");
// http://taaladvies.net/taal/advies/vraag/872
testSplit("Zij antwoordde: 'Ik denk niet dat ik nog langer met je om wil gaan.'");
testSplit("Zij fluisterde iets van 'eeuwig trouw' en 'altijd blijven houden van'.");
testSplit("'Heb je dat boek al gelezen?', vroeg hij.");
testSplit("De auteur vermeldt: 'Deze opvatting van het vorstendom heeft lang doorgewerkt.'");
// http://taaladvies.net/taal/advies/vraag/1557
testSplit("'Gaat u zitten', zei zij. ", "'De dokter komt zo.'");
testSplit("'Mijn broer woont ook in Den Haag', vertelde ze. ", "'Hij woont al een paar jaar samen.'");
testSplit("'Je bent grappig', zei ze. ", "'Echt, ik vind je grappig.'");
testSplit("'Is Jan thuis?', vroeg Piet. ", "'Ik wil hem wat vragen.'");
testSplit("'Ik denk er niet over!', riep ze. ", "'Dat gaat echt te ver, hoor!'");
testSplit("'Ik vermoed', zei Piet, 'dat Jan al wel thuis is.'");
testSplit("Het is een .Net programma. ", "Of een .NEt programma.");
testSplit("Het is een .Net-programma. ", "Of een .NEt-programma.");
testSplit("SP werd in 2001 de sp.a (Socialistische Partij Anders) en heet sinds 2021 Vooruit.");
testSplit("SP.A grijpt terug naar naam met geschiedenis: VOORUIT.");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
| Fatalll/languagetool | languagetool-language-modules/nl/src/test/java/org/languagetool/tokenizers/nl/DutchSRXSentenceTokenizerTest.java | 2,066 | //www.test.de vind je een website."); | line_comment | nl | /* LanguageTool, a natural language style checker
* Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers.nl;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Dutch;
import org.languagetool.tokenizers.SRXSentenceTokenizer;
/**
* @author Daniel Naber
* @author Adapted by R. Baars for Dutch
* @author Pander OpenTaal added examples from Wikipedia and Taaladvies
*/
public class DutchSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Dutch());
@Test
public void testTokenize() {
// NOTE: sentences here need to end with a space character so they
// have correct whitespace when appended:
testSplit("Dit is een zin.");
testSplit("Dit is een zin. ", "Nog een.");
testSplit("Een zin! ", "Nog een.");
testSplit("‘Dat meen je niet!’ kirde Mandy.");
testSplit("Een zin... ", "Nog een.");
testSplit("'En nu.. daden!' aan premier Mark Rutte.");
testSplit("Op http://www.test.de vind<SUF>
testSplit("De brief is op 3-10 gedateerd.");
testSplit("De brief is op 31-1 gedateerd.");
testSplit("De brief is op 3-10-2000 gedateerd.");
testSplit("Vandaag is het 13-12-2004.");
testSplit("Op 24.09 begint het.");
testSplit("Om 17:00 begint het.");
testSplit("In paragraaf 3.9.1 is dat beschreven.");
testSplit("Januari jl. is dat vastgelegd.");
testSplit("Appel en pruimen enz. werden gekocht.");
testSplit("De afkorting n.v.t. betekent niet van toepassing.");
testSplit("Bla et al. blah blah.");
testSplit("Dat is,, of het is bla.");
testSplit("Dat is het.. ", "Zo gaat het verder.");
testSplit("Dit hier is een(!) zin.");
testSplit("Dit hier is een(!!) zin.");
testSplit("Dit hier is een(?) zin.");
testSplit("Dit hier is een(???) zin.");
testSplit("Dit hier is een(???) zin.");
testSplit("Als voetballer wordt hij nooit een prof. ", "Maar prof. N.A.W. Th.Ch. Janssen wordt dat wel.");
// TODO, zin na dubbele punt
testSplit("Dat was het: helemaal niets.");
testSplit("Dat was het: het is een nieuwe zin.");
// https://nl.wikipedia.org/wiki/Aanhalingsteken
testSplit("Jan zei: \"Hallo.\"");
testSplit("Jan zei: “Hallo.”");
testSplit("„Hallo,” zei Jan, „waar ga je naartoe?”");
testSplit("„Gisteren”, zei Jan, „was het veel beter weer.”");
testSplit("Jan zei: „Annette zei ‚Hallo’.”");
testSplit("Jan zei: “Annette zei ‘Hallo’.”");
testSplit("Jan zei: «Annette zei ‹Hallo›.»");
testSplit("Wegens zijn „ziekte” hoefde hij niet te werken.");
testSplit("de letter „a”");
testSplit("het woord „beta” is afkomstig van ...");
// http://taaladvies.net/taal/advies/vraag/11
testSplit("De voorzitter zei: 'Ik zie hier geen been in.'");
testSplit("De voorzitter zei: \"Ik zie hier geen been in.\"");
testSplit("De koning zei: \"Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.\"");
testSplit("De koning zei: 'Ik herinner me nog dat iemand \"Vive la république\" riep tijdens mijn eedaflegging.'");
testSplit("De koning zei: 'Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.'");
testSplit("Otto dacht: wat een nare verhalen hoor je toch tegenwoordig.");
// http://taaladvies.net/taal/advies/vraag/871
testSplit("'Ik vrees', zei Rob, 'dat de brug zal instorten.'");
testSplit("'Ieder land', aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'");
testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'");
testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'");
testSplit("'Ik vrees,' zei Rob, 'dat de brug zal instorten.'");
testSplit("'Ieder land,' aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'");
testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'");
testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'");
// http://taaladvies.net/taal/advies/vraag/872
testSplit("Zij antwoordde: 'Ik denk niet dat ik nog langer met je om wil gaan.'");
testSplit("Zij fluisterde iets van 'eeuwig trouw' en 'altijd blijven houden van'.");
testSplit("'Heb je dat boek al gelezen?', vroeg hij.");
testSplit("De auteur vermeldt: 'Deze opvatting van het vorstendom heeft lang doorgewerkt.'");
// http://taaladvies.net/taal/advies/vraag/1557
testSplit("'Gaat u zitten', zei zij. ", "'De dokter komt zo.'");
testSplit("'Mijn broer woont ook in Den Haag', vertelde ze. ", "'Hij woont al een paar jaar samen.'");
testSplit("'Je bent grappig', zei ze. ", "'Echt, ik vind je grappig.'");
testSplit("'Is Jan thuis?', vroeg Piet. ", "'Ik wil hem wat vragen.'");
testSplit("'Ik denk er niet over!', riep ze. ", "'Dat gaat echt te ver, hoor!'");
testSplit("'Ik vermoed', zei Piet, 'dat Jan al wel thuis is.'");
testSplit("Het is een .Net programma. ", "Of een .NEt programma.");
testSplit("Het is een .Net-programma. ", "Of een .NEt-programma.");
testSplit("SP werd in 2001 de sp.a (Socialistische Partij Anders) en heet sinds 2021 Vooruit.");
testSplit("SP.A grijpt terug naar naam met geschiedenis: VOORUIT.");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
|
69230_13 | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fedai.osx.broker.message;
import java.io.File;
public class MessageStoreConfig {
private String storePathRootDir = System.getProperty("user.home") + File.separator + "store";
private String storePathCommitLog = System.getProperty("user.home") + File.separator + "store"
+ File.separator + "commitlog";
private int mappedFileSizeCommitLog = 1024 * 1024 * 1024;
private int mappedFileSizeConsumeQueue = 300000 * 1;
private boolean enableConsumeQueueExt = false;
private int mappedFileSizeConsumeQueueExt = 48 * 1024 * 1024;
// Bit count of filter bit map.
// this will be set by pipe of calculate filter bit map.
private int bitMapLengthConsumeQueueExt = 64;
// CommitLog flush interval
// flush data to disk
private int flushIntervalCommitLog = 500;
// Only used if TransientStorePool enabled
// flush data to FileChannel
private int commitIntervalCommitLog = 200;
/**
* introduced since 4.0.x. Determine whether to use mutex reentrantLock when putting message.<br/>
* By default it is set to false indicating using spin lock when putting message.
*/
private boolean useReentrantLockWhenPutMessage = false;
// Whether schedule flush,default is real-time
private boolean flushCommitLogTimed = false;
// ConsumeQueue flush interval
private int flushIntervalConsumeQueue = 1000;
// Resource reclaim interval
private int cleanResourceInterval = 10000;
// CommitLog removal interval
private int deleteCommitLogFilesInterval = 100;
// ConsumeQueue removal interval
private int deleteConsumeQueueFilesInterval = 100;
private int destroyMapedFileIntervalForcibly = 1000 * 120;
private int redeleteHangedFileInterval = 1000 * 120;
// When to delete,default is at 4 am
private String deleteWhen = "04";
private int diskMaxUsedSpaceRatio = 75;
// The number of hours to keep a log file before deleting it (in hours)
private int fileReservedTime = 72;
// Flow control for ConsumeQueue
private int putMsgIndexHightWater = 600000;
// The maximum size of message,default is 4M
private int maxMessageSize = 1024 * 1024 * 4;
// Whether check the CRC32 of the records consumed.
// This ensures no on-the-wire or on-disk corruption to the messages occurred.
// This check adds some overhead,so it may be disabled in cases seeking extreme performance.
private boolean checkCRCOnRecover = true;
// How many pages are to be flushed when flush CommitLog
private int flushCommitLogLeastPages = 4;
// How many pages are to be committed when commit data to file
private int commitCommitLogLeastPages = 4;
// Flush page size when the disk in warming state
private int flushLeastPagesWhenWarmMapedFile = 1024 / 4 * 16;
// How many pages are to be flushed when flush ConsumeQueue
private int flushConsumeQueueLeastPages = 2;
private int flushCommitLogThoroughInterval = 1000 * 10;
private int commitCommitLogThoroughInterval = 200;
private int flushConsumeQueueThoroughInterval = 1000 * 60;
private int maxTransferBytesOnMessageInMemory = 1024 * 256;
private int maxTransferCountOnMessageInMemory = 32;
private int maxTransferBytesOnMessageInDisk = 1024 * 64;
private int maxTransferCountOnMessageInDisk = 8;
private int accessMessageInMemoryMaxRatio = 40;
private boolean messageIndexEnable = true;
private int maxHashSlotNum = 5000000;
private int maxIndexNum = 5000000 * 4;
private int maxMsgsNumBatch = 64;
private boolean messageIndexSafe = false;
private int haListenPort = 10912;
private int haSendHeartbeatInterval = 1000 * 5;
private int haHousekeepingInterval = 1000 * 20;
private int haTransferBatchSize = 1024 * 32;
private String haMasterAddress = null;
private int haSlaveFallbehindMax = 1024 * 1024 * 256;
//private BrokerRole brokerRole = BrokerRole.ASYNC_MASTER;
// private FlushDiskType flushDiskType = FlushDiskType.ASYNC_FLUSH;
private int syncFlushTimeout = 1000 * 5;
private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
private long flushDelayOffsetInterval = 1000 * 10;
private boolean cleanFileForciblyEnable = true;
private boolean warmMapedFileEnable = false;
private boolean offsetCheckInSlave = false;
private boolean debugLockEnable = false;
private boolean duplicationEnable = false;
private boolean diskFallRecorded = true;
private long osPageCacheBusyTimeOutMills = 1000;
private int defaultQueryMaxNum = 32;
private boolean transientStorePoolEnable = false;
private int transientStorePoolSize = 5;
private boolean fastFailIfNoBufferInStorePool = false;
private boolean enableDLegerCommitLog = false;
private String dLegerGroup;
private String dLegerPeers;
private String dLegerSelfId;
private String preferredLeaderId;
private boolean isEnableBatchPush = false;
private boolean enableScheduleMessageStats = true;
public boolean isDebugLockEnable() {
return debugLockEnable;
}
public void setDebugLockEnable(final boolean debugLockEnable) {
this.debugLockEnable = debugLockEnable;
}
public boolean isDuplicationEnable() {
return duplicationEnable;
}
public void setDuplicationEnable(final boolean duplicationEnable) {
this.duplicationEnable = duplicationEnable;
}
public long getOsPageCacheBusyTimeOutMills() {
return osPageCacheBusyTimeOutMills;
}
public void setOsPageCacheBusyTimeOutMills(final long osPageCacheBusyTimeOutMills) {
this.osPageCacheBusyTimeOutMills = osPageCacheBusyTimeOutMills;
}
public boolean isDiskFallRecorded() {
return diskFallRecorded;
}
public void setDiskFallRecorded(final boolean diskFallRecorded) {
this.diskFallRecorded = diskFallRecorded;
}
public boolean isWarmMapedFileEnable() {
return warmMapedFileEnable;
}
public void setWarmMapedFileEnable(boolean warmMapedFileEnable) {
this.warmMapedFileEnable = warmMapedFileEnable;
}
public int getMappedFileSizeCommitLog() {
return mappedFileSizeCommitLog;
}
public void setMappedFileSizeCommitLog(int mappedFileSizeCommitLog) {
this.mappedFileSizeCommitLog = mappedFileSizeCommitLog;
}
public int getMappedFileSizeConsumeQueue() {
int factor = (int) Math.ceil(this.mappedFileSizeConsumeQueue / (1 * 1.0));
return (int) (factor * 1);
}
public void setMappedFileSizeConsumeQueue(int mappedFileSizeConsumeQueue) {
this.mappedFileSizeConsumeQueue = mappedFileSizeConsumeQueue;
}
public boolean isEnableConsumeQueueExt() {
return enableConsumeQueueExt;
}
public void setEnableConsumeQueueExt(boolean enableConsumeQueueExt) {
this.enableConsumeQueueExt = enableConsumeQueueExt;
}
public int getMappedFileSizeConsumeQueueExt() {
return mappedFileSizeConsumeQueueExt;
}
public void setMappedFileSizeConsumeQueueExt(int mappedFileSizeConsumeQueueExt) {
this.mappedFileSizeConsumeQueueExt = mappedFileSizeConsumeQueueExt;
}
public int getBitMapLengthConsumeQueueExt() {
return bitMapLengthConsumeQueueExt;
}
public void setBitMapLengthConsumeQueueExt(int bitMapLengthConsumeQueueExt) {
this.bitMapLengthConsumeQueueExt = bitMapLengthConsumeQueueExt;
}
public int getFlushIntervalCommitLog() {
return flushIntervalCommitLog;
}
public void setFlushIntervalCommitLog(int flushIntervalCommitLog) {
this.flushIntervalCommitLog = flushIntervalCommitLog;
}
public int getFlushIntervalConsumeQueue() {
return flushIntervalConsumeQueue;
}
public void setFlushIntervalConsumeQueue(int flushIntervalConsumeQueue) {
this.flushIntervalConsumeQueue = flushIntervalConsumeQueue;
}
public int getPutMsgIndexHightWater() {
return putMsgIndexHightWater;
}
public void setPutMsgIndexHightWater(int putMsgIndexHightWater) {
this.putMsgIndexHightWater = putMsgIndexHightWater;
}
public int getCleanResourceInterval() {
return cleanResourceInterval;
}
public void setCleanResourceInterval(int cleanResourceInterval) {
this.cleanResourceInterval = cleanResourceInterval;
}
public int getMaxMessageSize() {
return maxMessageSize;
}
public void setMaxMessageSize(int maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
public boolean isCheckCRCOnRecover() {
return checkCRCOnRecover;
}
public boolean getCheckCRCOnRecover() {
return checkCRCOnRecover;
}
public void setCheckCRCOnRecover(boolean checkCRCOnRecover) {
this.checkCRCOnRecover = checkCRCOnRecover;
}
public String getStorePathCommitLog() {
return storePathCommitLog;
}
public void setStorePathCommitLog(String storePathCommitLog) {
this.storePathCommitLog = storePathCommitLog;
}
public String getDeleteWhen() {
return deleteWhen;
}
public void setDeleteWhen(String deleteWhen) {
this.deleteWhen = deleteWhen;
}
public int getDiskMaxUsedSpaceRatio() {
if (this.diskMaxUsedSpaceRatio < 10)
return 10;
if (this.diskMaxUsedSpaceRatio > 95)
return 95;
return diskMaxUsedSpaceRatio;
}
public void setDiskMaxUsedSpaceRatio(int diskMaxUsedSpaceRatio) {
this.diskMaxUsedSpaceRatio = diskMaxUsedSpaceRatio;
}
public int getDeleteCommitLogFilesInterval() {
return deleteCommitLogFilesInterval;
}
public void setDeleteCommitLogFilesInterval(int deleteCommitLogFilesInterval) {
this.deleteCommitLogFilesInterval = deleteCommitLogFilesInterval;
}
public int getDeleteConsumeQueueFilesInterval() {
return deleteConsumeQueueFilesInterval;
}
public void setDeleteConsumeQueueFilesInterval(int deleteConsumeQueueFilesInterval) {
this.deleteConsumeQueueFilesInterval = deleteConsumeQueueFilesInterval;
}
public int getMaxTransferBytesOnMessageInMemory() {
return maxTransferBytesOnMessageInMemory;
}
public void setMaxTransferBytesOnMessageInMemory(int maxTransferBytesOnMessageInMemory) {
this.maxTransferBytesOnMessageInMemory = maxTransferBytesOnMessageInMemory;
}
public int getMaxTransferCountOnMessageInMemory() {
return maxTransferCountOnMessageInMemory;
}
public void setMaxTransferCountOnMessageInMemory(int maxTransferCountOnMessageInMemory) {
this.maxTransferCountOnMessageInMemory = maxTransferCountOnMessageInMemory;
}
public int getMaxTransferBytesOnMessageInDisk() {
return maxTransferBytesOnMessageInDisk;
}
public void setMaxTransferBytesOnMessageInDisk(int maxTransferBytesOnMessageInDisk) {
this.maxTransferBytesOnMessageInDisk = maxTransferBytesOnMessageInDisk;
}
public int getMaxTransferCountOnMessageInDisk() {
return maxTransferCountOnMessageInDisk;
}
public void setMaxTransferCountOnMessageInDisk(int maxTransferCountOnMessageInDisk) {
this.maxTransferCountOnMessageInDisk = maxTransferCountOnMessageInDisk;
}
public int getFlushCommitLogLeastPages() {
return flushCommitLogLeastPages;
}
public void setFlushCommitLogLeastPages(int flushCommitLogLeastPages) {
this.flushCommitLogLeastPages = flushCommitLogLeastPages;
}
public int getFlushConsumeQueueLeastPages() {
return flushConsumeQueueLeastPages;
}
public void setFlushConsumeQueueLeastPages(int flushConsumeQueueLeastPages) {
this.flushConsumeQueueLeastPages = flushConsumeQueueLeastPages;
}
public int getFlushCommitLogThoroughInterval() {
return flushCommitLogThoroughInterval;
}
public void setFlushCommitLogThoroughInterval(int flushCommitLogThoroughInterval) {
this.flushCommitLogThoroughInterval = flushCommitLogThoroughInterval;
}
public int getFlushConsumeQueueThoroughInterval() {
return flushConsumeQueueThoroughInterval;
}
public void setFlushConsumeQueueThoroughInterval(int flushConsumeQueueThoroughInterval) {
this.flushConsumeQueueThoroughInterval = flushConsumeQueueThoroughInterval;
}
public int getDestroyMapedFileIntervalForcibly() {
return destroyMapedFileIntervalForcibly;
}
public void setDestroyMapedFileIntervalForcibly(int destroyMapedFileIntervalForcibly) {
this.destroyMapedFileIntervalForcibly = destroyMapedFileIntervalForcibly;
}
public int getFileReservedTime() {
return fileReservedTime;
}
public void setFileReservedTime(int fileReservedTime) {
this.fileReservedTime = fileReservedTime;
}
public int getRedeleteHangedFileInterval() {
return redeleteHangedFileInterval;
}
public void setRedeleteHangedFileInterval(int redeleteHangedFileInterval) {
this.redeleteHangedFileInterval = redeleteHangedFileInterval;
}
public int getAccessMessageInMemoryMaxRatio() {
return accessMessageInMemoryMaxRatio;
}
public void setAccessMessageInMemoryMaxRatio(int accessMessageInMemoryMaxRatio) {
this.accessMessageInMemoryMaxRatio = accessMessageInMemoryMaxRatio;
}
public boolean isMessageIndexEnable() {
return messageIndexEnable;
}
public void setMessageIndexEnable(boolean messageIndexEnable) {
this.messageIndexEnable = messageIndexEnable;
}
public int getMaxHashSlotNum() {
return maxHashSlotNum;
}
public void setMaxHashSlotNum(int maxHashSlotNum) {
this.maxHashSlotNum = maxHashSlotNum;
}
public int getMaxIndexNum() {
return maxIndexNum;
}
public void setMaxIndexNum(int maxIndexNum) {
this.maxIndexNum = maxIndexNum;
}
public int getMaxMsgsNumBatch() {
return maxMsgsNumBatch;
}
public void setMaxMsgsNumBatch(int maxMsgsNumBatch) {
this.maxMsgsNumBatch = maxMsgsNumBatch;
}
public int getHaListenPort() {
return haListenPort;
}
public void setHaListenPort(int haListenPort) {
this.haListenPort = haListenPort;
}
public int getHaSendHeartbeatInterval() {
return haSendHeartbeatInterval;
}
public void setHaSendHeartbeatInterval(int haSendHeartbeatInterval) {
this.haSendHeartbeatInterval = haSendHeartbeatInterval;
}
public int getHaHousekeepingInterval() {
return haHousekeepingInterval;
}
public void setHaHousekeepingInterval(int haHousekeepingInterval) {
this.haHousekeepingInterval = haHousekeepingInterval;
}
// public BrokerRole getBrokerRole() {
// return brokerRole;
// }
//
// public void setBrokerRole(BrokerRole brokerRole) {
// this.brokerRole = brokerRole;
// }
// public void setBrokerRole(String brokerRole) {
// this.brokerRole = BrokerRole.valueOf(brokerRole);
// }
public int getHaTransferBatchSize() {
return haTransferBatchSize;
}
public void setHaTransferBatchSize(int haTransferBatchSize) {
this.haTransferBatchSize = haTransferBatchSize;
}
public int getHaSlaveFallbehindMax() {
return haSlaveFallbehindMax;
}
public void setHaSlaveFallbehindMax(int haSlaveFallbehindMax) {
this.haSlaveFallbehindMax = haSlaveFallbehindMax;
}
// public FlushDiskType getFlushDiskType() {
// return flushDiskType;
// }
//
// public void setFlushDiskType(FlushDiskType flushDiskType) {
// this.flushDiskType = flushDiskType;
// }
//
// public void setFlushDiskType(String type) {
// this.flushDiskType = FlushDiskType.valueOf(type);
// }
public int getSyncFlushTimeout() {
return syncFlushTimeout;
}
public void setSyncFlushTimeout(int syncFlushTimeout) {
this.syncFlushTimeout = syncFlushTimeout;
}
public String getHaMasterAddress() {
return haMasterAddress;
}
public void setHaMasterAddress(String haMasterAddress) {
this.haMasterAddress = haMasterAddress;
}
public String getMessageDelayLevel() {
return messageDelayLevel;
}
public void setMessageDelayLevel(String messageDelayLevel) {
this.messageDelayLevel = messageDelayLevel;
}
public long getFlushDelayOffsetInterval() {
return flushDelayOffsetInterval;
}
public void setFlushDelayOffsetInterval(long flushDelayOffsetInterval) {
this.flushDelayOffsetInterval = flushDelayOffsetInterval;
}
public boolean isCleanFileForciblyEnable() {
return cleanFileForciblyEnable;
}
public void setCleanFileForciblyEnable(boolean cleanFileForciblyEnable) {
this.cleanFileForciblyEnable = cleanFileForciblyEnable;
}
public boolean isMessageIndexSafe() {
return messageIndexSafe;
}
public void setMessageIndexSafe(boolean messageIndexSafe) {
this.messageIndexSafe = messageIndexSafe;
}
public boolean isFlushCommitLogTimed() {
return flushCommitLogTimed;
}
public void setFlushCommitLogTimed(boolean flushCommitLogTimed) {
this.flushCommitLogTimed = flushCommitLogTimed;
}
public String getStorePathRootDir() {
return storePathRootDir;
}
public void setStorePathRootDir(String storePathRootDir) {
this.storePathRootDir = storePathRootDir;
}
public int getFlushLeastPagesWhenWarmMapedFile() {
return flushLeastPagesWhenWarmMapedFile;
}
public void setFlushLeastPagesWhenWarmMapedFile(int flushLeastPagesWhenWarmMapedFile) {
this.flushLeastPagesWhenWarmMapedFile = flushLeastPagesWhenWarmMapedFile;
}
public boolean isOffsetCheckInSlave() {
return offsetCheckInSlave;
}
public void setOffsetCheckInSlave(boolean offsetCheckInSlave) {
this.offsetCheckInSlave = offsetCheckInSlave;
}
public int getDefaultQueryMaxNum() {
return defaultQueryMaxNum;
}
public void setDefaultQueryMaxNum(int defaultQueryMaxNum) {
this.defaultQueryMaxNum = defaultQueryMaxNum;
}
/**
* Enable transient commitLog store pool only if transientStorePoolEnable is true and the FlushDiskType is
* ASYNC_FLUSH
*
* @return <tt>true</tt> or <tt>false</tt>
*/
// public boolean isTransientStorePoolEnable() {
// return transientStorePoolEnable && FlushDiskType.ASYNC_FLUSH == getFlushDiskType()
// && BrokerRole.SLAVE != getBrokerRole();
// }
public void setTransientStorePoolEnable(final boolean transientStorePoolEnable) {
this.transientStorePoolEnable = transientStorePoolEnable;
}
public int getTransientStorePoolSize() {
return transientStorePoolSize;
}
public void setTransientStorePoolSize(final int transientStorePoolSize) {
this.transientStorePoolSize = transientStorePoolSize;
}
public int getCommitIntervalCommitLog() {
return commitIntervalCommitLog;
}
public void setCommitIntervalCommitLog(final int commitIntervalCommitLog) {
this.commitIntervalCommitLog = commitIntervalCommitLog;
}
public boolean isFastFailIfNoBufferInStorePool() {
return fastFailIfNoBufferInStorePool;
}
public void setFastFailIfNoBufferInStorePool(final boolean fastFailIfNoBufferInStorePool) {
this.fastFailIfNoBufferInStorePool = fastFailIfNoBufferInStorePool;
}
public boolean isUseReentrantLockWhenPutMessage() {
return useReentrantLockWhenPutMessage;
}
public void setUseReentrantLockWhenPutMessage(final boolean useReentrantLockWhenPutMessage) {
this.useReentrantLockWhenPutMessage = useReentrantLockWhenPutMessage;
}
public int getCommitCommitLogLeastPages() {
return commitCommitLogLeastPages;
}
public void setCommitCommitLogLeastPages(final int commitCommitLogLeastPages) {
this.commitCommitLogLeastPages = commitCommitLogLeastPages;
}
public int getCommitCommitLogThoroughInterval() {
return commitCommitLogThoroughInterval;
}
public void setCommitCommitLogThoroughInterval(final int commitCommitLogThoroughInterval) {
this.commitCommitLogThoroughInterval = commitCommitLogThoroughInterval;
}
public String getdLegerGroup() {
return dLegerGroup;
}
public void setdLegerGroup(String dLegerGroup) {
this.dLegerGroup = dLegerGroup;
}
public String getdLegerPeers() {
return dLegerPeers;
}
public void setdLegerPeers(String dLegerPeers) {
this.dLegerPeers = dLegerPeers;
}
public String getdLegerSelfId() {
return dLegerSelfId;
}
public void setdLegerSelfId(String dLegerSelfId) {
this.dLegerSelfId = dLegerSelfId;
}
public boolean isEnableDLegerCommitLog() {
return enableDLegerCommitLog;
}
public void setEnableDLegerCommitLog(boolean enableDLegerCommitLog) {
this.enableDLegerCommitLog = enableDLegerCommitLog;
}
public String getPreferredLeaderId() {
return preferredLeaderId;
}
public void setPreferredLeaderId(String preferredLeaderId) {
this.preferredLeaderId = preferredLeaderId;
}
public boolean isEnableBatchPush() {
return isEnableBatchPush;
}
public void setEnableBatchPush(boolean enableBatchPush) {
isEnableBatchPush = enableBatchPush;
}
public boolean isEnableScheduleMessageStats() {
return enableScheduleMessageStats;
}
public void setEnableScheduleMessageStats(boolean enableScheduleMessageStats) {
this.enableScheduleMessageStats = enableScheduleMessageStats;
}
}
| FederatedAI/FATE | java/osx/osx-broker/src/main/java/org/fedai/osx/broker/message/MessageStoreConfig.java | 6,554 | // When to delete,default is at 4 am | line_comment | nl | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fedai.osx.broker.message;
import java.io.File;
public class MessageStoreConfig {
private String storePathRootDir = System.getProperty("user.home") + File.separator + "store";
private String storePathCommitLog = System.getProperty("user.home") + File.separator + "store"
+ File.separator + "commitlog";
private int mappedFileSizeCommitLog = 1024 * 1024 * 1024;
private int mappedFileSizeConsumeQueue = 300000 * 1;
private boolean enableConsumeQueueExt = false;
private int mappedFileSizeConsumeQueueExt = 48 * 1024 * 1024;
// Bit count of filter bit map.
// this will be set by pipe of calculate filter bit map.
private int bitMapLengthConsumeQueueExt = 64;
// CommitLog flush interval
// flush data to disk
private int flushIntervalCommitLog = 500;
// Only used if TransientStorePool enabled
// flush data to FileChannel
private int commitIntervalCommitLog = 200;
/**
* introduced since 4.0.x. Determine whether to use mutex reentrantLock when putting message.<br/>
* By default it is set to false indicating using spin lock when putting message.
*/
private boolean useReentrantLockWhenPutMessage = false;
// Whether schedule flush,default is real-time
private boolean flushCommitLogTimed = false;
// ConsumeQueue flush interval
private int flushIntervalConsumeQueue = 1000;
// Resource reclaim interval
private int cleanResourceInterval = 10000;
// CommitLog removal interval
private int deleteCommitLogFilesInterval = 100;
// ConsumeQueue removal interval
private int deleteConsumeQueueFilesInterval = 100;
private int destroyMapedFileIntervalForcibly = 1000 * 120;
private int redeleteHangedFileInterval = 1000 * 120;
// When to<SUF>
private String deleteWhen = "04";
private int diskMaxUsedSpaceRatio = 75;
// The number of hours to keep a log file before deleting it (in hours)
private int fileReservedTime = 72;
// Flow control for ConsumeQueue
private int putMsgIndexHightWater = 600000;
// The maximum size of message,default is 4M
private int maxMessageSize = 1024 * 1024 * 4;
// Whether check the CRC32 of the records consumed.
// This ensures no on-the-wire or on-disk corruption to the messages occurred.
// This check adds some overhead,so it may be disabled in cases seeking extreme performance.
private boolean checkCRCOnRecover = true;
// How many pages are to be flushed when flush CommitLog
private int flushCommitLogLeastPages = 4;
// How many pages are to be committed when commit data to file
private int commitCommitLogLeastPages = 4;
// Flush page size when the disk in warming state
private int flushLeastPagesWhenWarmMapedFile = 1024 / 4 * 16;
// How many pages are to be flushed when flush ConsumeQueue
private int flushConsumeQueueLeastPages = 2;
private int flushCommitLogThoroughInterval = 1000 * 10;
private int commitCommitLogThoroughInterval = 200;
private int flushConsumeQueueThoroughInterval = 1000 * 60;
private int maxTransferBytesOnMessageInMemory = 1024 * 256;
private int maxTransferCountOnMessageInMemory = 32;
private int maxTransferBytesOnMessageInDisk = 1024 * 64;
private int maxTransferCountOnMessageInDisk = 8;
private int accessMessageInMemoryMaxRatio = 40;
private boolean messageIndexEnable = true;
private int maxHashSlotNum = 5000000;
private int maxIndexNum = 5000000 * 4;
private int maxMsgsNumBatch = 64;
private boolean messageIndexSafe = false;
private int haListenPort = 10912;
private int haSendHeartbeatInterval = 1000 * 5;
private int haHousekeepingInterval = 1000 * 20;
private int haTransferBatchSize = 1024 * 32;
private String haMasterAddress = null;
private int haSlaveFallbehindMax = 1024 * 1024 * 256;
//private BrokerRole brokerRole = BrokerRole.ASYNC_MASTER;
// private FlushDiskType flushDiskType = FlushDiskType.ASYNC_FLUSH;
private int syncFlushTimeout = 1000 * 5;
private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
private long flushDelayOffsetInterval = 1000 * 10;
private boolean cleanFileForciblyEnable = true;
private boolean warmMapedFileEnable = false;
private boolean offsetCheckInSlave = false;
private boolean debugLockEnable = false;
private boolean duplicationEnable = false;
private boolean diskFallRecorded = true;
private long osPageCacheBusyTimeOutMills = 1000;
private int defaultQueryMaxNum = 32;
private boolean transientStorePoolEnable = false;
private int transientStorePoolSize = 5;
private boolean fastFailIfNoBufferInStorePool = false;
private boolean enableDLegerCommitLog = false;
private String dLegerGroup;
private String dLegerPeers;
private String dLegerSelfId;
private String preferredLeaderId;
private boolean isEnableBatchPush = false;
private boolean enableScheduleMessageStats = true;
public boolean isDebugLockEnable() {
return debugLockEnable;
}
public void setDebugLockEnable(final boolean debugLockEnable) {
this.debugLockEnable = debugLockEnable;
}
public boolean isDuplicationEnable() {
return duplicationEnable;
}
public void setDuplicationEnable(final boolean duplicationEnable) {
this.duplicationEnable = duplicationEnable;
}
public long getOsPageCacheBusyTimeOutMills() {
return osPageCacheBusyTimeOutMills;
}
public void setOsPageCacheBusyTimeOutMills(final long osPageCacheBusyTimeOutMills) {
this.osPageCacheBusyTimeOutMills = osPageCacheBusyTimeOutMills;
}
public boolean isDiskFallRecorded() {
return diskFallRecorded;
}
public void setDiskFallRecorded(final boolean diskFallRecorded) {
this.diskFallRecorded = diskFallRecorded;
}
public boolean isWarmMapedFileEnable() {
return warmMapedFileEnable;
}
public void setWarmMapedFileEnable(boolean warmMapedFileEnable) {
this.warmMapedFileEnable = warmMapedFileEnable;
}
public int getMappedFileSizeCommitLog() {
return mappedFileSizeCommitLog;
}
public void setMappedFileSizeCommitLog(int mappedFileSizeCommitLog) {
this.mappedFileSizeCommitLog = mappedFileSizeCommitLog;
}
public int getMappedFileSizeConsumeQueue() {
int factor = (int) Math.ceil(this.mappedFileSizeConsumeQueue / (1 * 1.0));
return (int) (factor * 1);
}
public void setMappedFileSizeConsumeQueue(int mappedFileSizeConsumeQueue) {
this.mappedFileSizeConsumeQueue = mappedFileSizeConsumeQueue;
}
public boolean isEnableConsumeQueueExt() {
return enableConsumeQueueExt;
}
public void setEnableConsumeQueueExt(boolean enableConsumeQueueExt) {
this.enableConsumeQueueExt = enableConsumeQueueExt;
}
public int getMappedFileSizeConsumeQueueExt() {
return mappedFileSizeConsumeQueueExt;
}
public void setMappedFileSizeConsumeQueueExt(int mappedFileSizeConsumeQueueExt) {
this.mappedFileSizeConsumeQueueExt = mappedFileSizeConsumeQueueExt;
}
public int getBitMapLengthConsumeQueueExt() {
return bitMapLengthConsumeQueueExt;
}
public void setBitMapLengthConsumeQueueExt(int bitMapLengthConsumeQueueExt) {
this.bitMapLengthConsumeQueueExt = bitMapLengthConsumeQueueExt;
}
public int getFlushIntervalCommitLog() {
return flushIntervalCommitLog;
}
public void setFlushIntervalCommitLog(int flushIntervalCommitLog) {
this.flushIntervalCommitLog = flushIntervalCommitLog;
}
public int getFlushIntervalConsumeQueue() {
return flushIntervalConsumeQueue;
}
public void setFlushIntervalConsumeQueue(int flushIntervalConsumeQueue) {
this.flushIntervalConsumeQueue = flushIntervalConsumeQueue;
}
public int getPutMsgIndexHightWater() {
return putMsgIndexHightWater;
}
public void setPutMsgIndexHightWater(int putMsgIndexHightWater) {
this.putMsgIndexHightWater = putMsgIndexHightWater;
}
public int getCleanResourceInterval() {
return cleanResourceInterval;
}
public void setCleanResourceInterval(int cleanResourceInterval) {
this.cleanResourceInterval = cleanResourceInterval;
}
public int getMaxMessageSize() {
return maxMessageSize;
}
public void setMaxMessageSize(int maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
public boolean isCheckCRCOnRecover() {
return checkCRCOnRecover;
}
public boolean getCheckCRCOnRecover() {
return checkCRCOnRecover;
}
public void setCheckCRCOnRecover(boolean checkCRCOnRecover) {
this.checkCRCOnRecover = checkCRCOnRecover;
}
public String getStorePathCommitLog() {
return storePathCommitLog;
}
public void setStorePathCommitLog(String storePathCommitLog) {
this.storePathCommitLog = storePathCommitLog;
}
public String getDeleteWhen() {
return deleteWhen;
}
public void setDeleteWhen(String deleteWhen) {
this.deleteWhen = deleteWhen;
}
public int getDiskMaxUsedSpaceRatio() {
if (this.diskMaxUsedSpaceRatio < 10)
return 10;
if (this.diskMaxUsedSpaceRatio > 95)
return 95;
return diskMaxUsedSpaceRatio;
}
public void setDiskMaxUsedSpaceRatio(int diskMaxUsedSpaceRatio) {
this.diskMaxUsedSpaceRatio = diskMaxUsedSpaceRatio;
}
public int getDeleteCommitLogFilesInterval() {
return deleteCommitLogFilesInterval;
}
public void setDeleteCommitLogFilesInterval(int deleteCommitLogFilesInterval) {
this.deleteCommitLogFilesInterval = deleteCommitLogFilesInterval;
}
public int getDeleteConsumeQueueFilesInterval() {
return deleteConsumeQueueFilesInterval;
}
public void setDeleteConsumeQueueFilesInterval(int deleteConsumeQueueFilesInterval) {
this.deleteConsumeQueueFilesInterval = deleteConsumeQueueFilesInterval;
}
public int getMaxTransferBytesOnMessageInMemory() {
return maxTransferBytesOnMessageInMemory;
}
public void setMaxTransferBytesOnMessageInMemory(int maxTransferBytesOnMessageInMemory) {
this.maxTransferBytesOnMessageInMemory = maxTransferBytesOnMessageInMemory;
}
public int getMaxTransferCountOnMessageInMemory() {
return maxTransferCountOnMessageInMemory;
}
public void setMaxTransferCountOnMessageInMemory(int maxTransferCountOnMessageInMemory) {
this.maxTransferCountOnMessageInMemory = maxTransferCountOnMessageInMemory;
}
public int getMaxTransferBytesOnMessageInDisk() {
return maxTransferBytesOnMessageInDisk;
}
public void setMaxTransferBytesOnMessageInDisk(int maxTransferBytesOnMessageInDisk) {
this.maxTransferBytesOnMessageInDisk = maxTransferBytesOnMessageInDisk;
}
public int getMaxTransferCountOnMessageInDisk() {
return maxTransferCountOnMessageInDisk;
}
public void setMaxTransferCountOnMessageInDisk(int maxTransferCountOnMessageInDisk) {
this.maxTransferCountOnMessageInDisk = maxTransferCountOnMessageInDisk;
}
public int getFlushCommitLogLeastPages() {
return flushCommitLogLeastPages;
}
public void setFlushCommitLogLeastPages(int flushCommitLogLeastPages) {
this.flushCommitLogLeastPages = flushCommitLogLeastPages;
}
public int getFlushConsumeQueueLeastPages() {
return flushConsumeQueueLeastPages;
}
public void setFlushConsumeQueueLeastPages(int flushConsumeQueueLeastPages) {
this.flushConsumeQueueLeastPages = flushConsumeQueueLeastPages;
}
public int getFlushCommitLogThoroughInterval() {
return flushCommitLogThoroughInterval;
}
public void setFlushCommitLogThoroughInterval(int flushCommitLogThoroughInterval) {
this.flushCommitLogThoroughInterval = flushCommitLogThoroughInterval;
}
public int getFlushConsumeQueueThoroughInterval() {
return flushConsumeQueueThoroughInterval;
}
public void setFlushConsumeQueueThoroughInterval(int flushConsumeQueueThoroughInterval) {
this.flushConsumeQueueThoroughInterval = flushConsumeQueueThoroughInterval;
}
public int getDestroyMapedFileIntervalForcibly() {
return destroyMapedFileIntervalForcibly;
}
public void setDestroyMapedFileIntervalForcibly(int destroyMapedFileIntervalForcibly) {
this.destroyMapedFileIntervalForcibly = destroyMapedFileIntervalForcibly;
}
public int getFileReservedTime() {
return fileReservedTime;
}
public void setFileReservedTime(int fileReservedTime) {
this.fileReservedTime = fileReservedTime;
}
public int getRedeleteHangedFileInterval() {
return redeleteHangedFileInterval;
}
public void setRedeleteHangedFileInterval(int redeleteHangedFileInterval) {
this.redeleteHangedFileInterval = redeleteHangedFileInterval;
}
public int getAccessMessageInMemoryMaxRatio() {
return accessMessageInMemoryMaxRatio;
}
public void setAccessMessageInMemoryMaxRatio(int accessMessageInMemoryMaxRatio) {
this.accessMessageInMemoryMaxRatio = accessMessageInMemoryMaxRatio;
}
public boolean isMessageIndexEnable() {
return messageIndexEnable;
}
public void setMessageIndexEnable(boolean messageIndexEnable) {
this.messageIndexEnable = messageIndexEnable;
}
public int getMaxHashSlotNum() {
return maxHashSlotNum;
}
public void setMaxHashSlotNum(int maxHashSlotNum) {
this.maxHashSlotNum = maxHashSlotNum;
}
public int getMaxIndexNum() {
return maxIndexNum;
}
public void setMaxIndexNum(int maxIndexNum) {
this.maxIndexNum = maxIndexNum;
}
public int getMaxMsgsNumBatch() {
return maxMsgsNumBatch;
}
public void setMaxMsgsNumBatch(int maxMsgsNumBatch) {
this.maxMsgsNumBatch = maxMsgsNumBatch;
}
public int getHaListenPort() {
return haListenPort;
}
public void setHaListenPort(int haListenPort) {
this.haListenPort = haListenPort;
}
public int getHaSendHeartbeatInterval() {
return haSendHeartbeatInterval;
}
public void setHaSendHeartbeatInterval(int haSendHeartbeatInterval) {
this.haSendHeartbeatInterval = haSendHeartbeatInterval;
}
public int getHaHousekeepingInterval() {
return haHousekeepingInterval;
}
public void setHaHousekeepingInterval(int haHousekeepingInterval) {
this.haHousekeepingInterval = haHousekeepingInterval;
}
// public BrokerRole getBrokerRole() {
// return brokerRole;
// }
//
// public void setBrokerRole(BrokerRole brokerRole) {
// this.brokerRole = brokerRole;
// }
// public void setBrokerRole(String brokerRole) {
// this.brokerRole = BrokerRole.valueOf(brokerRole);
// }
public int getHaTransferBatchSize() {
return haTransferBatchSize;
}
public void setHaTransferBatchSize(int haTransferBatchSize) {
this.haTransferBatchSize = haTransferBatchSize;
}
public int getHaSlaveFallbehindMax() {
return haSlaveFallbehindMax;
}
public void setHaSlaveFallbehindMax(int haSlaveFallbehindMax) {
this.haSlaveFallbehindMax = haSlaveFallbehindMax;
}
// public FlushDiskType getFlushDiskType() {
// return flushDiskType;
// }
//
// public void setFlushDiskType(FlushDiskType flushDiskType) {
// this.flushDiskType = flushDiskType;
// }
//
// public void setFlushDiskType(String type) {
// this.flushDiskType = FlushDiskType.valueOf(type);
// }
public int getSyncFlushTimeout() {
return syncFlushTimeout;
}
public void setSyncFlushTimeout(int syncFlushTimeout) {
this.syncFlushTimeout = syncFlushTimeout;
}
public String getHaMasterAddress() {
return haMasterAddress;
}
public void setHaMasterAddress(String haMasterAddress) {
this.haMasterAddress = haMasterAddress;
}
public String getMessageDelayLevel() {
return messageDelayLevel;
}
public void setMessageDelayLevel(String messageDelayLevel) {
this.messageDelayLevel = messageDelayLevel;
}
public long getFlushDelayOffsetInterval() {
return flushDelayOffsetInterval;
}
public void setFlushDelayOffsetInterval(long flushDelayOffsetInterval) {
this.flushDelayOffsetInterval = flushDelayOffsetInterval;
}
public boolean isCleanFileForciblyEnable() {
return cleanFileForciblyEnable;
}
public void setCleanFileForciblyEnable(boolean cleanFileForciblyEnable) {
this.cleanFileForciblyEnable = cleanFileForciblyEnable;
}
public boolean isMessageIndexSafe() {
return messageIndexSafe;
}
public void setMessageIndexSafe(boolean messageIndexSafe) {
this.messageIndexSafe = messageIndexSafe;
}
public boolean isFlushCommitLogTimed() {
return flushCommitLogTimed;
}
public void setFlushCommitLogTimed(boolean flushCommitLogTimed) {
this.flushCommitLogTimed = flushCommitLogTimed;
}
public String getStorePathRootDir() {
return storePathRootDir;
}
public void setStorePathRootDir(String storePathRootDir) {
this.storePathRootDir = storePathRootDir;
}
public int getFlushLeastPagesWhenWarmMapedFile() {
return flushLeastPagesWhenWarmMapedFile;
}
public void setFlushLeastPagesWhenWarmMapedFile(int flushLeastPagesWhenWarmMapedFile) {
this.flushLeastPagesWhenWarmMapedFile = flushLeastPagesWhenWarmMapedFile;
}
public boolean isOffsetCheckInSlave() {
return offsetCheckInSlave;
}
public void setOffsetCheckInSlave(boolean offsetCheckInSlave) {
this.offsetCheckInSlave = offsetCheckInSlave;
}
public int getDefaultQueryMaxNum() {
return defaultQueryMaxNum;
}
public void setDefaultQueryMaxNum(int defaultQueryMaxNum) {
this.defaultQueryMaxNum = defaultQueryMaxNum;
}
/**
* Enable transient commitLog store pool only if transientStorePoolEnable is true and the FlushDiskType is
* ASYNC_FLUSH
*
* @return <tt>true</tt> or <tt>false</tt>
*/
// public boolean isTransientStorePoolEnable() {
// return transientStorePoolEnable && FlushDiskType.ASYNC_FLUSH == getFlushDiskType()
// && BrokerRole.SLAVE != getBrokerRole();
// }
public void setTransientStorePoolEnable(final boolean transientStorePoolEnable) {
this.transientStorePoolEnable = transientStorePoolEnable;
}
public int getTransientStorePoolSize() {
return transientStorePoolSize;
}
public void setTransientStorePoolSize(final int transientStorePoolSize) {
this.transientStorePoolSize = transientStorePoolSize;
}
public int getCommitIntervalCommitLog() {
return commitIntervalCommitLog;
}
public void setCommitIntervalCommitLog(final int commitIntervalCommitLog) {
this.commitIntervalCommitLog = commitIntervalCommitLog;
}
public boolean isFastFailIfNoBufferInStorePool() {
return fastFailIfNoBufferInStorePool;
}
public void setFastFailIfNoBufferInStorePool(final boolean fastFailIfNoBufferInStorePool) {
this.fastFailIfNoBufferInStorePool = fastFailIfNoBufferInStorePool;
}
public boolean isUseReentrantLockWhenPutMessage() {
return useReentrantLockWhenPutMessage;
}
public void setUseReentrantLockWhenPutMessage(final boolean useReentrantLockWhenPutMessage) {
this.useReentrantLockWhenPutMessage = useReentrantLockWhenPutMessage;
}
public int getCommitCommitLogLeastPages() {
return commitCommitLogLeastPages;
}
public void setCommitCommitLogLeastPages(final int commitCommitLogLeastPages) {
this.commitCommitLogLeastPages = commitCommitLogLeastPages;
}
public int getCommitCommitLogThoroughInterval() {
return commitCommitLogThoroughInterval;
}
public void setCommitCommitLogThoroughInterval(final int commitCommitLogThoroughInterval) {
this.commitCommitLogThoroughInterval = commitCommitLogThoroughInterval;
}
public String getdLegerGroup() {
return dLegerGroup;
}
public void setdLegerGroup(String dLegerGroup) {
this.dLegerGroup = dLegerGroup;
}
public String getdLegerPeers() {
return dLegerPeers;
}
public void setdLegerPeers(String dLegerPeers) {
this.dLegerPeers = dLegerPeers;
}
public String getdLegerSelfId() {
return dLegerSelfId;
}
public void setdLegerSelfId(String dLegerSelfId) {
this.dLegerSelfId = dLegerSelfId;
}
public boolean isEnableDLegerCommitLog() {
return enableDLegerCommitLog;
}
public void setEnableDLegerCommitLog(boolean enableDLegerCommitLog) {
this.enableDLegerCommitLog = enableDLegerCommitLog;
}
public String getPreferredLeaderId() {
return preferredLeaderId;
}
public void setPreferredLeaderId(String preferredLeaderId) {
this.preferredLeaderId = preferredLeaderId;
}
public boolean isEnableBatchPush() {
return isEnableBatchPush;
}
public void setEnableBatchPush(boolean enableBatchPush) {
isEnableBatchPush = enableBatchPush;
}
public boolean isEnableScheduleMessageStats() {
return enableScheduleMessageStats;
}
public void setEnableScheduleMessageStats(boolean enableScheduleMessageStats) {
this.enableScheduleMessageStats = enableScheduleMessageStats;
}
}
|
55423_1 | /*
* Copyright (c) 2022, FPS BOSA DG DT
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package be.gov.data.scrapers.vlaanderen;
import be.gov.data.helpers.Storage;
import be.gov.data.scrapers.Cache;
import be.gov.data.scrapers.Dcat;
import be.gov.data.scrapers.Page;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.Set;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParseException;
/**
* Vlaanderen via DCAT-AP catalog.
*
* @see https://opendata.vlaanderen.be/
* @author Bart Hanssens
*/
public class GeonetVlaanderen extends Dcat {
@Override
public void generateDcat(Cache cache, Storage store) throws RepositoryException, MalformedURLException {
Set<URL> urls = cache.retrievePageList();
for (URL url: urls) {
Page page = cache.retrievePage(url).get("all");
// fix buggy input
try (InputStream in = new ByteArrayInputStream(page.getContent().getBytes(StandardCharsets.UTF_8))) {
store.add(in, RDFFormat.RDFXML);
} catch (RDFParseException | IOException ex) {
if (ex.getMessage().contains("Premature end")) {
LOG.warn("Premature end of file in {}", url);
} else {
throw new RepositoryException(url.toString(), ex);
}
}
}
generateCatalog(store);
}
/**
* Scrape DCAT catalog.
*
* @param cache
* @throws IOException
*/
@Override
protected void scrapeCat(Cache cache) throws IOException {
int size = 20;
for(int start = 0; ;start += size) {
URL url = new URL(getBase().toString() + "?startindex=" + start + "&limit=" + size + "&f=dcat_ap_vl");
String xml = makeRequest(url);
if (!xml.contains("Dataset") && !xml.contains("DataService")) {
LOG.info("Last (empty) page");
break;
}
cache.storePage(url, "all", new Page(url, xml));
}
}
@Override
public void scrape() throws IOException {
LOG.info("Start scraping");
Cache cache = getCache();
Set<URL> urls = cache.retrievePageList();
if (urls.isEmpty()) {
scrapeCat(cache);
}
LOG.info("Done scraping");
}
/**
* Constructor.
*
* @param prop
* @throws IOException
*/
public GeonetVlaanderen(Properties prop) throws IOException {
super(prop);
setName("vlaanderen");
}
}
| Fedict/dcattools | scrapers/src/main/java/be/gov/data/scrapers/vlaanderen/GeonetVlaanderen.java | 1,253 | /**
* Vlaanderen via DCAT-AP catalog.
*
* @see https://opendata.vlaanderen.be/
* @author Bart Hanssens
*/ | block_comment | nl | /*
* Copyright (c) 2022, FPS BOSA DG DT
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package be.gov.data.scrapers.vlaanderen;
import be.gov.data.helpers.Storage;
import be.gov.data.scrapers.Cache;
import be.gov.data.scrapers.Dcat;
import be.gov.data.scrapers.Page;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.Set;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParseException;
/**
* Vlaanderen via DCAT-AP<SUF>*/
public class GeonetVlaanderen extends Dcat {
@Override
public void generateDcat(Cache cache, Storage store) throws RepositoryException, MalformedURLException {
Set<URL> urls = cache.retrievePageList();
for (URL url: urls) {
Page page = cache.retrievePage(url).get("all");
// fix buggy input
try (InputStream in = new ByteArrayInputStream(page.getContent().getBytes(StandardCharsets.UTF_8))) {
store.add(in, RDFFormat.RDFXML);
} catch (RDFParseException | IOException ex) {
if (ex.getMessage().contains("Premature end")) {
LOG.warn("Premature end of file in {}", url);
} else {
throw new RepositoryException(url.toString(), ex);
}
}
}
generateCatalog(store);
}
/**
* Scrape DCAT catalog.
*
* @param cache
* @throws IOException
*/
@Override
protected void scrapeCat(Cache cache) throws IOException {
int size = 20;
for(int start = 0; ;start += size) {
URL url = new URL(getBase().toString() + "?startindex=" + start + "&limit=" + size + "&f=dcat_ap_vl");
String xml = makeRequest(url);
if (!xml.contains("Dataset") && !xml.contains("DataService")) {
LOG.info("Last (empty) page");
break;
}
cache.storePage(url, "all", new Page(url, xml));
}
}
@Override
public void scrape() throws IOException {
LOG.info("Start scraping");
Cache cache = getCache();
Set<URL> urls = cache.retrievePageList();
if (urls.isEmpty()) {
scrapeCat(cache);
}
LOG.info("Done scraping");
}
/**
* Constructor.
*
* @param prop
* @throws IOException
*/
public GeonetVlaanderen(Properties prop) throws IOException {
super(prop);
setName("vlaanderen");
}
}
|
106041_3 | /**
* Project Zelula
*
* Contextproject TI2800
* TU Delft - University of Technology
*
* Authors:
* Felix Akkermans, Niels Doekemeijer, Thomas van Helden
* Albert ten Napel, Jan Pieter Waagmeester
*
* https://github.com/FelixAkk/synthbio
*/
package synthbio.models;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Point representation
* @author jieter
*/
public class Position{
private double x;
private double y;
public Position(double x, double y){
this.x=x;
this.y=y;
}
/**
* Create a undefined position defaulting to 0,0
*/
public Position(){
this(0, 0);
}
/**
* getters
*/
public double getX(){
return this.x;
}
public double getY(){
return this.y;
}
/**
* Calculate the distance between two positions
*
* @param that Position to calculate distance to.
* @return The distance between this and that.
*/
public double distanceTo(Position that){
return Math.sqrt(
Math.pow(this.getX()-that.getX(), 2) +
Math.pow(this.getY()-that.getY(), 2)
);
}
public boolean equals(Object other){
if(!(other instanceof Position)){
return false;
}
Position that=(Position)other;
return this.getX()==that.getX() && this.getY()==that.getY();
}
/**
* Return a simple String representation
*/
public String toString(){
return "("+this.getX()+","+this.getY()+")";
}
/**
* Deserialize JSON to a Position
*/
public static Position fromJSON(String json) throws JSONException{
return Position.fromJSON(new JSONObject(json));
}
public static Position fromJSON(JSONObject json) throws JSONException{
return new Position(json.getDouble("x"), json.getDouble("y"));
}
}
| FelixAkk/synthbio | program/WEB-INF/src/synthbio/models/Position.java | 583 | /**
* getters
*/ | block_comment | nl | /**
* Project Zelula
*
* Contextproject TI2800
* TU Delft - University of Technology
*
* Authors:
* Felix Akkermans, Niels Doekemeijer, Thomas van Helden
* Albert ten Napel, Jan Pieter Waagmeester
*
* https://github.com/FelixAkk/synthbio
*/
package synthbio.models;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Point representation
* @author jieter
*/
public class Position{
private double x;
private double y;
public Position(double x, double y){
this.x=x;
this.y=y;
}
/**
* Create a undefined position defaulting to 0,0
*/
public Position(){
this(0, 0);
}
/**
* getters
<SUF>*/
public double getX(){
return this.x;
}
public double getY(){
return this.y;
}
/**
* Calculate the distance between two positions
*
* @param that Position to calculate distance to.
* @return The distance between this and that.
*/
public double distanceTo(Position that){
return Math.sqrt(
Math.pow(this.getX()-that.getX(), 2) +
Math.pow(this.getY()-that.getY(), 2)
);
}
public boolean equals(Object other){
if(!(other instanceof Position)){
return false;
}
Position that=(Position)other;
return this.getX()==that.getX() && this.getY()==that.getY();
}
/**
* Return a simple String representation
*/
public String toString(){
return "("+this.getX()+","+this.getY()+")";
}
/**
* Deserialize JSON to a Position
*/
public static Position fromJSON(String json) throws JSONException{
return Position.fromJSON(new JSONObject(json));
}
public static Position fromJSON(JSONObject json) throws JSONException{
return new Position(json.getDouble("x"), json.getDouble("y"));
}
}
|
31824_2 | package drie.nieuw.relatiesindrie.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity
public class Pagina {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String title;
private String subtitle;
private String author;
@Column(length=20000) // Q:het heeft GEEN effect op de varchar size in de database,
// het wordt een text-veld -> ik begrijp het verschil niet met song.java uit SONGBOOK
// bovendien heb ik het veld handmatig goed gezet in phpMyAdmin... dat moet beter!
String codetext;
@OneToMany(mappedBy = "pagina", cascade = CascadeType.REMOVE)
private List<PaginaPerLijst> lijsten;
//-------------------------------------------------
public String getAuthor() {
return author;
}
//-------------------------------------------------
public void setAuthor(String author) {
this.author = author;
}
//-------------------------------------------------
public String getCodetext() {
return codetext;
}
//-------------------------------------------------
public void setCodetext(String codetext) {
this.codetext = codetext;
}
//------------------------------------------------
public String getSubtitle() {
return subtitle;
}
//-------------------------------------------------
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
//-------------------------------------------------
public long getId() {
return id;
}
//-------------------------------------------------
public void setId(long id) {
this.id = id;
}
//-------------------------------------------------
public String getTitle() {
return title;
}
//-------------------------------------------------
public void setTitle(String title) {
this.title = title;
}
//-------------------------------------------------
@JsonIgnore
public List<PaginaPerLijst> getLijsten() {
return lijsten;
}
//-------------------------------------------------
@JsonIgnore
public void setLijsten(List<PaginaPerLijst> lijsten) {
this.lijsten = lijsten;
}
//-------------------------------------------------
}
| FelixvL/mavendriemanytomanyspring | src/main/java/drie/nieuw/relatiesindrie/model/Pagina.java | 691 | // bovendien heb ik het veld handmatig goed gezet in phpMyAdmin... dat moet beter! | line_comment | nl | package drie.nieuw.relatiesindrie.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity
public class Pagina {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String title;
private String subtitle;
private String author;
@Column(length=20000) // Q:het heeft GEEN effect op de varchar size in de database,
// het wordt een text-veld -> ik begrijp het verschil niet met song.java uit SONGBOOK
// bovendien heb<SUF>
String codetext;
@OneToMany(mappedBy = "pagina", cascade = CascadeType.REMOVE)
private List<PaginaPerLijst> lijsten;
//-------------------------------------------------
public String getAuthor() {
return author;
}
//-------------------------------------------------
public void setAuthor(String author) {
this.author = author;
}
//-------------------------------------------------
public String getCodetext() {
return codetext;
}
//-------------------------------------------------
public void setCodetext(String codetext) {
this.codetext = codetext;
}
//------------------------------------------------
public String getSubtitle() {
return subtitle;
}
//-------------------------------------------------
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
//-------------------------------------------------
public long getId() {
return id;
}
//-------------------------------------------------
public void setId(long id) {
this.id = id;
}
//-------------------------------------------------
public String getTitle() {
return title;
}
//-------------------------------------------------
public void setTitle(String title) {
this.title = title;
}
//-------------------------------------------------
@JsonIgnore
public List<PaginaPerLijst> getLijsten() {
return lijsten;
}
//-------------------------------------------------
@JsonIgnore
public void setLijsten(List<PaginaPerLijst> lijsten) {
this.lijsten = lijsten;
}
//-------------------------------------------------
}
|
15252_1 | package com.lilithsthrone.game.dialogue.places.global;
import com.lilithsthrone.game.dialogue.DialogueNode;
import com.lilithsthrone.game.dialogue.responses.Response;
import com.lilithsthrone.game.dialogue.responses.ResponseEffectsOnly;
import com.lilithsthrone.game.dialogue.utils.UtilText;
import com.lilithsthrone.main.Main;
import com.lilithsthrone.world.WorldType;
import com.lilithsthrone.world.places.AbstractGlobalPlaceType;
import com.lilithsthrone.world.places.AbstractPlaceType;
/**
* @since 0.3.1
* @version 0.3.1
* @author Innoxia
*/
public class GlobalFoloiFields {
public static final DialogueNode DOMINION_EXTERIOR = new DialogueNode("Dominion", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "DOMINION_EXTERIOR");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new ResponseEffectsOnly("Enter", "Head into Dominion.") {
@Override
public void effects() {
WorldType wt = ((AbstractGlobalPlaceType) Main.game.getPlayer().getGlobalCell().getPlace().getPlaceType()).getGlobalLinkedWorldType();
AbstractPlaceType pt = ((AbstractGlobalPlaceType) Main.game.getPlayer().getGlobalCell().getPlace().getPlaceType()).getGlobalLinkedWorldType().getEntryFromGlobalMapLocation();
Main.game.getPlayer().setLocation(
wt,
Main.game.getWorlds().get(wt).getCell(pt).getLocation(),
false);
Main.game.setContent(new Response("", "", Main.game.getDefaultDialogueNoEncounter()));
}
};
} else {
return null;
}
}
};
public static final DialogueNode FOLOI_FIELDS = new DialogueNode("Foloi Fields", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "FOLOI_FIELDS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Farm work", "Approach one of the farms which is requesting help and see what it is you'd have to do in order to earn some flames.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate world
}
};
} else {
return null;
}
}
};
public static final DialogueNode FOLOI_FOREST = new DialogueNode("Foloi Forest", "", false) {
@Override
public int getSecondsPassed() {
return 2 * 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "FOLOI_FOREST");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Explore", "Take some time to explore this area of the forest and see what you can find.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate world
}
};
} else {
return null;
}
}
};
public static final DialogueNode GRASSLAND_WILDERNESS = new DialogueNode("Grassland Wilderness", "", false) {
@Override
public int getSecondsPassed() {
return 2 * 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "GRASSLAND_WILDERNESS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Explore", "Explore some of the valleys and see what you can find.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate world
}
};
} else {
return null;
}
}
};
public static final DialogueNode RIVER_HUBUR = new DialogueNode("River Hubur", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "RIVER_HUBUR");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Explore", "Take some time to explore the shores of the river.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate world
}
};
} else {
return null;
}
}
};
public static final DialogueNode ELIS = new DialogueNode("Elis", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "ELIS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Approach", "Approach the walls of Elis, and head towards the main gatehouse.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO
}
};
} else {
return null;
}
}
};
}
| Felyndiira/liliths-throne-public | src/com/lilithsthrone/game/dialogue/places/global/GlobalFoloiFields.java | 1,787 | //TODO generate world | line_comment | nl | package com.lilithsthrone.game.dialogue.places.global;
import com.lilithsthrone.game.dialogue.DialogueNode;
import com.lilithsthrone.game.dialogue.responses.Response;
import com.lilithsthrone.game.dialogue.responses.ResponseEffectsOnly;
import com.lilithsthrone.game.dialogue.utils.UtilText;
import com.lilithsthrone.main.Main;
import com.lilithsthrone.world.WorldType;
import com.lilithsthrone.world.places.AbstractGlobalPlaceType;
import com.lilithsthrone.world.places.AbstractPlaceType;
/**
* @since 0.3.1
* @version 0.3.1
* @author Innoxia
*/
public class GlobalFoloiFields {
public static final DialogueNode DOMINION_EXTERIOR = new DialogueNode("Dominion", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "DOMINION_EXTERIOR");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new ResponseEffectsOnly("Enter", "Head into Dominion.") {
@Override
public void effects() {
WorldType wt = ((AbstractGlobalPlaceType) Main.game.getPlayer().getGlobalCell().getPlace().getPlaceType()).getGlobalLinkedWorldType();
AbstractPlaceType pt = ((AbstractGlobalPlaceType) Main.game.getPlayer().getGlobalCell().getPlace().getPlaceType()).getGlobalLinkedWorldType().getEntryFromGlobalMapLocation();
Main.game.getPlayer().setLocation(
wt,
Main.game.getWorlds().get(wt).getCell(pt).getLocation(),
false);
Main.game.setContent(new Response("", "", Main.game.getDefaultDialogueNoEncounter()));
}
};
} else {
return null;
}
}
};
public static final DialogueNode FOLOI_FIELDS = new DialogueNode("Foloi Fields", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "FOLOI_FIELDS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Farm work", "Approach one of the farms which is requesting help and see what it is you'd have to do in order to earn some flames.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate<SUF>
}
};
} else {
return null;
}
}
};
public static final DialogueNode FOLOI_FOREST = new DialogueNode("Foloi Forest", "", false) {
@Override
public int getSecondsPassed() {
return 2 * 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "FOLOI_FOREST");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Explore", "Take some time to explore this area of the forest and see what you can find.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate world
}
};
} else {
return null;
}
}
};
public static final DialogueNode GRASSLAND_WILDERNESS = new DialogueNode("Grassland Wilderness", "", false) {
@Override
public int getSecondsPassed() {
return 2 * 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "GRASSLAND_WILDERNESS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Explore", "Explore some of the valleys and see what you can find.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate world
}
};
} else {
return null;
}
}
};
public static final DialogueNode RIVER_HUBUR = new DialogueNode("River Hubur", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "RIVER_HUBUR");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Explore", "Take some time to explore the shores of the river.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO generate world
}
};
} else {
return null;
}
}
};
public static final DialogueNode ELIS = new DialogueNode("Elis", "", false) {
@Override
public int getSecondsPassed() {
return 60 * 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/global/globalPlaces", "ELIS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Approach", "Approach the walls of Elis, and head towards the main gatehouse.<br/>[style.italicsBad(Will be added in v0.3.4!)]", null) {
@Override
public void effects() {
//TODO
}
};
} else {
return null;
}
}
};
}
|
62337_13 |
package nl.koffiepot.Stratego.model;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Bord {
//variables
private long id;
private String naam = "default";
Object[][] speelBord = new Object[10][10];
private Blokkade blokkade = new Blokkade();
//Constructor(s), de default constructor
public Bord(boolean RandomPlacement) {
if (RandomPlacement) {
List<Speelstuk> team1 = Speler.createteam(0); //De tijdelijk functie om een team aan te maken aante roepen
List<Speelstuk> team2 = Speler.createteam(1); //
Random rand = new Random();
LOOP:
while (true) {
for (int y = 0; y < 4; y++) { //het bord vullen
for (int x = 0; x < 10; x++) {
int ind = rand.nextInt(team1.size());
speelBord[y][x] = team1.get(ind);
team1.remove(ind);
ind = rand.nextInt(team2.size()); //dit kan gelijk voor team 2, de x coordinaat wordt alleen met 6 verhoogd.
speelBord[y + 6][x] = team2.get(ind);
team2.remove(ind);
if (team1.isEmpty()) break LOOP;
}
}
}
}
//hardcoded blokkades
speelBord[4][2] = blokkade; //coordinaten 5,3
speelBord[4][3] = blokkade; //coordinaten 5,4
speelBord[5][2] = blokkade;
speelBord[5][3] = blokkade;
speelBord[4][6] = blokkade;
speelBord[4][7] = blokkade;
speelBord[5][6] = blokkade;
speelBord[5][7] = blokkade;
}
public void setPiece(int y, int x, Speelstuk speelstuk){
speelBord[y][x] = speelstuk;
}
//method for asking pion (int y, int x)
// calls method if pion is own team
// calls method if pion can move in any direction
boolean checkValidPiece(int pionYLocation, int pionXLocation, int team){
Object gekozenStuk = speelBord[pionYLocation][pionXLocation];
if(gekozenStuk == blokkade){
System.out.println("Je hebt een blokkade gekozen");
return false;
} else if (gekozenStuk == null){
System.out.println("Je hebt een lege plek gekozen");
return false;
} else {
Speelstuk gekozenSpeelStuk = (Speelstuk)gekozenStuk; //casten naar een Speelstuk object
if (gekozenSpeelStuk.getTeam() != team){
System.out.println("het gekozen speelstuk is niet van jouw team");
return false;
} else { //als het gekozen speelstuk eindelijk wel goed is, dan even kijken of er een beweegbare plek is (1 plek omheen die 'null' is)
//if (speelBord[pionYLocation][pionXLocation+1] == null || speelBord[pionYLocation][pionXLocation-1] == null //deze check heeft een bug als een correcte speelstuk aan de rand is gekozen omdat hij dan buiten het bord check of de index 'null' is. Maar buiten het bord is er geen index dus krijg je een ArrayIndexOutOfboundsException.
// || speelBord[pionYLocation-1][pionXLocation] == null || speelBord[pionYLocation+1][pionXLocation] == null){
if (gekozenSpeelStuk.getNaam().equals("bom")) {
System.out.println("Je kunt geen bom bewegen");
return false;
} else if (gekozenSpeelStuk.getNaam().equals("vlag")) {
System.out.println("Je kunt geen vlag bewegen");
return false;
} else if (movementCheck(pionYLocation, pionXLocation + 1, false, team) //in deze if statement wordt elke richting gecheckt, als er eentje mogelijk is dan komt er True uit en is het gekozen speelstuk een Valid Piece. Als het gekozen speelstuk van eigen team is maar geen enkele kant op kan dan komt hier false uit dus is het niet mogelijk
|| movementCheck(pionYLocation,pionXLocation-1, false,team)
|| movementCheck(pionYLocation + 1, pionXLocation,false,team)
|| movementCheck(pionYLocation - 1, pionXLocation,false,team)){
return true;
} else {
System.out.println("Je hebt een speelstuk gekozen dat niet bewogen kan worden");
return false;
}
}
} //else return true;
}
private boolean movementCheck (int pionYLocation, int pionXLocation, boolean printInfo, int team) {
//Check of de nieuwe plaats wel op het bord ligt
//RICX: ik heb deze methode iets aangepakt zodat ik deze ook kan aanroepen in checkValidPiece om te kijken of het gekozen speelstuk uberhaupt kan bewegen.
//nu wordt elke richting a.d.h.v. deze functie gecheck om te kijken of het mogelijk is, maar in checkValidPiec wordt enige informatie niet geprint.
//bij movePiece wordt deze check ook uigevoerd met de ingegeven mogelijkheden en dan wordt de informatie wel gecheckt.
if (pionYLocation < 0 || pionYLocation > 9 || pionXLocation < 0 || pionXLocation > 9) { //check even of dit niet out of bounds geeft
if (printInfo) {
System.out.println("Deze locatie zit buiten het bord");
}
return false; // out of bounds -> dus mag je niet bewegen
} else if (speelBord[pionYLocation][pionXLocation] instanceof Speelstuk) {
Speelstuk tempSpeelstuk = (Speelstuk) speelBord[pionYLocation][pionXLocation];
if (tempSpeelstuk.getTeam() == team) {
if (printInfo) System.out.println("Hier staat je eigen pion");
return false; //instance of speelstuk, maar eigen team --> dus je mag niet bewegen
// } else if (speelBord[pionYLocation][pionXLocation] instanceof Vlag) { //check voor de vlag ingebouwd, maar ook hier geldt, vlag van zowel beide teams (nog team specifiek maken)
// if (printInfo) System.out.println("JE HEBT GEWONNEN, GEFELICITEERD!!!!"); //en de game moet nog eindigen....
// return true; //instance of speelstuk, niet van je eigen team maar wel een vlag --> dus je mag wel bewegen
} else {
return true; //instance of speelstuk, niet van eigen team --> je mag wel bewegen
}
} else if (speelBord[pionYLocation][pionXLocation] instanceof Blokkade) {
if (printInfo) System.out.println("Hier kun je niet doorheen!");
return false; //instance of blokkade, je mag niet bewegen
} else {
return true; //nieuwe positie is leeg, dus je kan wel bewegen.
}
}
//Deze code verplaatst de stukken, maar kan alleen aangeroepen worden nadat de movement check is uitgevoerd
//Daarom is deze ook private!
//kijkt eerst of de nieuwe locatie een speelstuk bevat, zo ja, vergelijkt die de values met elkaar MOET NOG TEAM SPECIFIEK MAKEN, NU KAN JE OOK JE EIGEN SPEELSTUK AANVALLEN
private void movePiece (int pionYLocationNew, int pionXLocationNew, int pionYLocationOld, int pionXLocationOld, Speler speler) {
if (speelBord[pionYLocationNew][pionXLocationNew] instanceof Speelstuk) {
Speelstuk enemy = (Speelstuk) speelBord[pionYLocationNew][pionXLocationNew];
Speelstuk eigenSpeelstuk = (Speelstuk) speelBord[pionYLocationOld][pionXLocationOld];
System.out.println("----- ATTACK! -----" + '\n' + "Je valt aan met " + eigenSpeelstuk.getNaam() + "(" + eigenSpeelstuk.getValue() + ")");
switch (enemy.getNaam()) {
case "vlag":
System.out.println("Je hebt een vlag aangevallen " + '\n' + "----- U heeft gewonnen! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
speelBord[pionYLocationOld][pionXLocationOld] = null;
speler.setGewonnen(true);
break;
case "bom":
if (eigenSpeelstuk.getNaam().equals("mineur")) {
System.out.println("Je hebt een bom aangevallen " + '\n' + "----- YOU WIN!! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
} else {
System.out.println("Je hebt een bom aangevallen " + '\n' + "----- YOU LOST! -----");
}
speelBord[pionYLocationOld][pionXLocationOld] = null;
break;
case "maarschalk":
if (eigenSpeelstuk.getNaam().equals("spion")) {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU WIN!! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
} else {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU LOST! -----");
}
speelBord[pionYLocationOld][pionXLocationOld] = null;
break;
default:
if (eigenSpeelstuk.getValue() > enemy.getValue()) {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU WIN!! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
} else if (eigenSpeelstuk.getValue() < enemy.getValue()) {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU LOST! -----");
} else if (eigenSpeelstuk.getValue() == enemy.getValue()) { //Deze kijkt als hij gelijk is en maakt beide posities leeg
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- BOTH LOOSE! -----");
speelBord[pionYLocationNew][pionXLocationNew] = null;
} else {
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
}
speelBord[pionYLocationOld][pionXLocationOld] = null;
break;
}
} else {
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
speelBord[pionYLocationOld][pionXLocationOld] = null;
}
}
public boolean FrondEndMove(int pionXLocation, int pionYLocation, String direction, Speler speler) {
switch (direction) {
case "u":
//Check of hij wel in deze richting kan bewegen, zo ja: voer move uit, zo nee: nieuwe input vragen
if (movementCheck(pionYLocation - 1, pionXLocation, true, speler.getSpelerTeam())) {
movePiece(pionYLocation - 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "d":
if (movementCheck(pionYLocation + 1, pionXLocation, true, speler.getSpelerTeam())) {
movePiece(pionYLocation + 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "r":
if (movementCheck(pionYLocation, pionXLocation + 1, true, speler.getSpelerTeam())) {
movePiece(pionYLocation, pionXLocation + 1, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "l":
if (movementCheck(pionYLocation, pionXLocation - 1, true, speler.getSpelerTeam())) {
movePiece(pionYLocation, pionXLocation - 1, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
default:
return false;
}
}
//methode om movement te kiezen en te checken
public boolean moveChooser(int pionYLocation, int pionXLocation, Speler speler) {
Scanner scanner = new Scanner(System.in);
String movementDirection = scanner.next();
//Kijk of de input voldoet aan een van de volgende cases "u,d,r,l"
switch (movementDirection) {
case "u":
//Check of hij wel in deze richting kan bewegen, zo ja: voer move uit, zo nee: nieuwe input vragen
if (movementCheck(pionYLocation - 1,pionXLocation,true,speler.getSpelerTeam())){
movePiece(pionYLocation - 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "d":
if (movementCheck(pionYLocation + 1,pionXLocation,true,speler.getSpelerTeam())){
movePiece(pionYLocation + 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "r":
if (movementCheck(pionYLocation,pionXLocation + 1,true,speler.getSpelerTeam())){
movePiece(pionYLocation, pionXLocation + 1, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "l":
if (movementCheck(pionYLocation,pionXLocation - 1,true,speler.getSpelerTeam())){
movePiece(pionYLocation, pionXLocation - 1, pionYLocation, pionXLocation, speler);
return true;
} else{
return false;
}
default:
//Als geen geldige input wordt ingevuld, als "w,a,s" of "dr", dan komt hij hier in terecht en
//vraagt hij om nieuwe input.
System.out.println("U heeft een ongeldige richting gekozen, kies uit: Up (u), Down (d), Left (l), Right (r)");
return false;
}
}
//hieronder wordt het hele bord geprint, zie volgende methode voor team specifiek bord printen
public void bordPrinten(){
StringBuilder bordstring = new StringBuilder();
bordstring.append("X: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 | \n"); //deze coordinaten worden geprint boven het bord
bordstring.append(" -----------------------------------------\n"); // dit is een afscheiding van coordinaten tov gevulde matrix
bordstring.append("Y: +---+---+---+---+---+---+---+---+---+---+\n");
for (int y = 0; y < 10; y++) {
int yCoordinaat = y + 1;//deze y-coordinaat wordt gedefinieerd zodat deze geprint kan worden als coordinatenstelsel
if (yCoordinaat < 10) {
bordstring.append(" ");//getallen kleiner dan 10, krijgen extra spatie (voor uitlijning)
}
bordstring.append(yCoordinaat + " ");
for (int x = 0; x < 10; x++) { //deze forloop voegt voor ieder vakje de value van het spelstuk toe of een "o" als het vakje leeg is.
String spelstukString;
if (speelBord[y][x] instanceof Speelstuk) {
Speelstuk speelstuk = (Speelstuk) speelBord[y][x];
if (speelstuk.getValue() < 10) {
spelstukString = "| " + speelstuk.getValue() + " "; //een extra spatie toevoegen als de waarde kleiner is dan tien, zodat de uitlijning mooi klopt.
} else {
spelstukString = "|" + speelstuk.getValue() + " ";
}
} else if (speelBord[y][x] instanceof Blokkade) { //Als er een String wordt gevonden dan is het een blokkade
spelstukString = "| x ";
} else { //Leeg stuk ruimte waar heen gelopen kan worden
spelstukString = "| ";
}
bordstring.append(spelstukString);
}
bordstring.append("|\n");//Aan het einde komt nog een rechtstreepje en dan een niewline character
bordstring.append(" +---+---+---+---+---+---+---+---+---+---+\n");
}
System.out.println(bordstring);
}
public String bordPrinten2(){
StringBuilder bordstring = new StringBuilder();
bordstring.append("X: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 | \n"); //deze coordinaten worden geprint boven het bord
bordstring.append(" -----------------------------------------\n"); // dit is een afscheiding van coordinaten tov gevulde matrix
bordstring.append("Y: +---+---+---+---+---+---+---+---+---+---+\n");
for (int y = 0; y < 10; y++) {
int yCoordinaat = y + 1;//deze y-coordinaat wordt gedefinieerd zodat deze geprint kan worden als coordinatenstelsel
if (yCoordinaat < 10) {
bordstring.append(" ");//getallen kleiner dan 10, krijgen extra spatie (voor uitlijning)
}
bordstring.append(yCoordinaat + " ");
for (int x = 0; x < 10; x++) { //deze forloop voegt voor ieder vakje de value van het spelstuk toe of een "o" als het vakje leeg is.
String spelstukString;
if (speelBord[y][x] instanceof Speelstuk) {
Speelstuk speelstuk = (Speelstuk) speelBord[y][x];
if (speelstuk.getValue() < 10) {
spelstukString = "| " + speelstuk.getValue() + " "; //een extra spatie toevoegen als de waarde kleiner is dan tien, zodat de uitlijning mooi klopt.
} else {
spelstukString = "|" + speelstuk.getValue() + " ";
}
} else if (speelBord[y][x] instanceof Blokkade) { //Als er een String wordt gevonden dan is het een blokkade
spelstukString = "| x ";
} else { //Leeg stuk ruimte waar heen gelopen kan worden
spelstukString = "| ";
}
bordstring.append(spelstukString);
}
bordstring.append("|\n");//Aan het einde komt nog een rechtstreepje en dan een niewline character
bordstring.append(" +---+---+---+---+---+---+---+---+---+---+\n");
}
return bordstring.toString();
}
//met onderstaande methode wordt het bord geprint teamspecifiek, je geeft dan het team mee in de methode
public void bordPrinten(int huidigeTeam){
StringBuilder bordstring = new StringBuilder();
bordstring.append("X: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 | \n"); //deze coordinaten worden geprint boven het bord
bordstring.append(" -----------------------------------------\n"); // dit is een afscheiding van coordinaten tov gevulde matrix
bordstring.append("Y: +---+---+---+---+---+---+---+---+---+---+\n");
for (int y = 0; y < 10; y++) {
int yCoordinaat = y+1; //deze y-coordinaat wordt gedefinieerd zodat deze geprint kan worden als coordinatenstelsel
if(yCoordinaat<10) {
bordstring.append(" ");//getallen kleiner dan 10, krijgen extra spatie (voor uitlijning)
}
bordstring.append(yCoordinaat + " ");
for (int x = 0; x < 10; x++) { //deze forloop voegt voor ieder vakje de value van het spelstuk toe of een "o" als het vakje leeg is.
String spelstukString;
if (speelBord[y][x] instanceof Speelstuk) {
Speelstuk speelstuk = (Speelstuk) speelBord[y][x];
if (speelstuk.getTeam()==huidigeTeam){ //als team gelijk is aan huidigeteam --> print de values van speelstuk
if (speelstuk.getValue() < 10) {
spelstukString = "| " + speelstuk.getValue() + " "; //een extra spatie toevoegen als de waarde kleiner is dan tien, zodat de uitlijning mooi klopt.
} else {
spelstukString = "|" + speelstuk.getValue() + " ";
}
}else {
spelstukString = "|xxx"; //print xx voor speelstuk van tegenstander (andere team)
}
} else if (speelBord[y][x] instanceof Blokkade) { //Als er een String wordt gevonden dan is het een blokkade
spelstukString = "| x ";
} else { //Leeg stuk ruimte waar heen gelopen kan worden
spelstukString = "| ";
}
bordstring.append(spelstukString);
}
bordstring.append("|\n");//Aan het einde komt nog een rechtstreepje en dan een niewline character
bordstring.append(" +---+---+---+---+---+---+---+---+---+---+\n");
}
System.out.println(bordstring);
}
//getters and setter
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Object[][] getSpeelBord() {
return speelBord;
}
}
class Blokkade{}
| FernonE/Stratego | src/main/java/nl/koffiepot/Stratego/model/Bord.java | 6,664 | //Check of de nieuwe plaats wel op het bord ligt | line_comment | nl |
package nl.koffiepot.Stratego.model;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Bord {
//variables
private long id;
private String naam = "default";
Object[][] speelBord = new Object[10][10];
private Blokkade blokkade = new Blokkade();
//Constructor(s), de default constructor
public Bord(boolean RandomPlacement) {
if (RandomPlacement) {
List<Speelstuk> team1 = Speler.createteam(0); //De tijdelijk functie om een team aan te maken aante roepen
List<Speelstuk> team2 = Speler.createteam(1); //
Random rand = new Random();
LOOP:
while (true) {
for (int y = 0; y < 4; y++) { //het bord vullen
for (int x = 0; x < 10; x++) {
int ind = rand.nextInt(team1.size());
speelBord[y][x] = team1.get(ind);
team1.remove(ind);
ind = rand.nextInt(team2.size()); //dit kan gelijk voor team 2, de x coordinaat wordt alleen met 6 verhoogd.
speelBord[y + 6][x] = team2.get(ind);
team2.remove(ind);
if (team1.isEmpty()) break LOOP;
}
}
}
}
//hardcoded blokkades
speelBord[4][2] = blokkade; //coordinaten 5,3
speelBord[4][3] = blokkade; //coordinaten 5,4
speelBord[5][2] = blokkade;
speelBord[5][3] = blokkade;
speelBord[4][6] = blokkade;
speelBord[4][7] = blokkade;
speelBord[5][6] = blokkade;
speelBord[5][7] = blokkade;
}
public void setPiece(int y, int x, Speelstuk speelstuk){
speelBord[y][x] = speelstuk;
}
//method for asking pion (int y, int x)
// calls method if pion is own team
// calls method if pion can move in any direction
boolean checkValidPiece(int pionYLocation, int pionXLocation, int team){
Object gekozenStuk = speelBord[pionYLocation][pionXLocation];
if(gekozenStuk == blokkade){
System.out.println("Je hebt een blokkade gekozen");
return false;
} else if (gekozenStuk == null){
System.out.println("Je hebt een lege plek gekozen");
return false;
} else {
Speelstuk gekozenSpeelStuk = (Speelstuk)gekozenStuk; //casten naar een Speelstuk object
if (gekozenSpeelStuk.getTeam() != team){
System.out.println("het gekozen speelstuk is niet van jouw team");
return false;
} else { //als het gekozen speelstuk eindelijk wel goed is, dan even kijken of er een beweegbare plek is (1 plek omheen die 'null' is)
//if (speelBord[pionYLocation][pionXLocation+1] == null || speelBord[pionYLocation][pionXLocation-1] == null //deze check heeft een bug als een correcte speelstuk aan de rand is gekozen omdat hij dan buiten het bord check of de index 'null' is. Maar buiten het bord is er geen index dus krijg je een ArrayIndexOutOfboundsException.
// || speelBord[pionYLocation-1][pionXLocation] == null || speelBord[pionYLocation+1][pionXLocation] == null){
if (gekozenSpeelStuk.getNaam().equals("bom")) {
System.out.println("Je kunt geen bom bewegen");
return false;
} else if (gekozenSpeelStuk.getNaam().equals("vlag")) {
System.out.println("Je kunt geen vlag bewegen");
return false;
} else if (movementCheck(pionYLocation, pionXLocation + 1, false, team) //in deze if statement wordt elke richting gecheckt, als er eentje mogelijk is dan komt er True uit en is het gekozen speelstuk een Valid Piece. Als het gekozen speelstuk van eigen team is maar geen enkele kant op kan dan komt hier false uit dus is het niet mogelijk
|| movementCheck(pionYLocation,pionXLocation-1, false,team)
|| movementCheck(pionYLocation + 1, pionXLocation,false,team)
|| movementCheck(pionYLocation - 1, pionXLocation,false,team)){
return true;
} else {
System.out.println("Je hebt een speelstuk gekozen dat niet bewogen kan worden");
return false;
}
}
} //else return true;
}
private boolean movementCheck (int pionYLocation, int pionXLocation, boolean printInfo, int team) {
//Check of<SUF>
//RICX: ik heb deze methode iets aangepakt zodat ik deze ook kan aanroepen in checkValidPiece om te kijken of het gekozen speelstuk uberhaupt kan bewegen.
//nu wordt elke richting a.d.h.v. deze functie gecheck om te kijken of het mogelijk is, maar in checkValidPiec wordt enige informatie niet geprint.
//bij movePiece wordt deze check ook uigevoerd met de ingegeven mogelijkheden en dan wordt de informatie wel gecheckt.
if (pionYLocation < 0 || pionYLocation > 9 || pionXLocation < 0 || pionXLocation > 9) { //check even of dit niet out of bounds geeft
if (printInfo) {
System.out.println("Deze locatie zit buiten het bord");
}
return false; // out of bounds -> dus mag je niet bewegen
} else if (speelBord[pionYLocation][pionXLocation] instanceof Speelstuk) {
Speelstuk tempSpeelstuk = (Speelstuk) speelBord[pionYLocation][pionXLocation];
if (tempSpeelstuk.getTeam() == team) {
if (printInfo) System.out.println("Hier staat je eigen pion");
return false; //instance of speelstuk, maar eigen team --> dus je mag niet bewegen
// } else if (speelBord[pionYLocation][pionXLocation] instanceof Vlag) { //check voor de vlag ingebouwd, maar ook hier geldt, vlag van zowel beide teams (nog team specifiek maken)
// if (printInfo) System.out.println("JE HEBT GEWONNEN, GEFELICITEERD!!!!"); //en de game moet nog eindigen....
// return true; //instance of speelstuk, niet van je eigen team maar wel een vlag --> dus je mag wel bewegen
} else {
return true; //instance of speelstuk, niet van eigen team --> je mag wel bewegen
}
} else if (speelBord[pionYLocation][pionXLocation] instanceof Blokkade) {
if (printInfo) System.out.println("Hier kun je niet doorheen!");
return false; //instance of blokkade, je mag niet bewegen
} else {
return true; //nieuwe positie is leeg, dus je kan wel bewegen.
}
}
//Deze code verplaatst de stukken, maar kan alleen aangeroepen worden nadat de movement check is uitgevoerd
//Daarom is deze ook private!
//kijkt eerst of de nieuwe locatie een speelstuk bevat, zo ja, vergelijkt die de values met elkaar MOET NOG TEAM SPECIFIEK MAKEN, NU KAN JE OOK JE EIGEN SPEELSTUK AANVALLEN
private void movePiece (int pionYLocationNew, int pionXLocationNew, int pionYLocationOld, int pionXLocationOld, Speler speler) {
if (speelBord[pionYLocationNew][pionXLocationNew] instanceof Speelstuk) {
Speelstuk enemy = (Speelstuk) speelBord[pionYLocationNew][pionXLocationNew];
Speelstuk eigenSpeelstuk = (Speelstuk) speelBord[pionYLocationOld][pionXLocationOld];
System.out.println("----- ATTACK! -----" + '\n' + "Je valt aan met " + eigenSpeelstuk.getNaam() + "(" + eigenSpeelstuk.getValue() + ")");
switch (enemy.getNaam()) {
case "vlag":
System.out.println("Je hebt een vlag aangevallen " + '\n' + "----- U heeft gewonnen! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
speelBord[pionYLocationOld][pionXLocationOld] = null;
speler.setGewonnen(true);
break;
case "bom":
if (eigenSpeelstuk.getNaam().equals("mineur")) {
System.out.println("Je hebt een bom aangevallen " + '\n' + "----- YOU WIN!! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
} else {
System.out.println("Je hebt een bom aangevallen " + '\n' + "----- YOU LOST! -----");
}
speelBord[pionYLocationOld][pionXLocationOld] = null;
break;
case "maarschalk":
if (eigenSpeelstuk.getNaam().equals("spion")) {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU WIN!! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
} else {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU LOST! -----");
}
speelBord[pionYLocationOld][pionXLocationOld] = null;
break;
default:
if (eigenSpeelstuk.getValue() > enemy.getValue()) {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU WIN!! -----");
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
} else if (eigenSpeelstuk.getValue() < enemy.getValue()) {
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- YOU LOST! -----");
} else if (eigenSpeelstuk.getValue() == enemy.getValue()) { //Deze kijkt als hij gelijk is en maakt beide posities leeg
System.out.println("Je hebt een " + enemy.getNaam() + " aangevallen " + "(" + enemy.getValue() + ")" + '\n' + "----- BOTH LOOSE! -----");
speelBord[pionYLocationNew][pionXLocationNew] = null;
} else {
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
}
speelBord[pionYLocationOld][pionXLocationOld] = null;
break;
}
} else {
speelBord[pionYLocationNew][pionXLocationNew] = speelBord[pionYLocationOld][pionXLocationOld];
speelBord[pionYLocationOld][pionXLocationOld] = null;
}
}
public boolean FrondEndMove(int pionXLocation, int pionYLocation, String direction, Speler speler) {
switch (direction) {
case "u":
//Check of hij wel in deze richting kan bewegen, zo ja: voer move uit, zo nee: nieuwe input vragen
if (movementCheck(pionYLocation - 1, pionXLocation, true, speler.getSpelerTeam())) {
movePiece(pionYLocation - 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "d":
if (movementCheck(pionYLocation + 1, pionXLocation, true, speler.getSpelerTeam())) {
movePiece(pionYLocation + 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "r":
if (movementCheck(pionYLocation, pionXLocation + 1, true, speler.getSpelerTeam())) {
movePiece(pionYLocation, pionXLocation + 1, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "l":
if (movementCheck(pionYLocation, pionXLocation - 1, true, speler.getSpelerTeam())) {
movePiece(pionYLocation, pionXLocation - 1, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
default:
return false;
}
}
//methode om movement te kiezen en te checken
public boolean moveChooser(int pionYLocation, int pionXLocation, Speler speler) {
Scanner scanner = new Scanner(System.in);
String movementDirection = scanner.next();
//Kijk of de input voldoet aan een van de volgende cases "u,d,r,l"
switch (movementDirection) {
case "u":
//Check of hij wel in deze richting kan bewegen, zo ja: voer move uit, zo nee: nieuwe input vragen
if (movementCheck(pionYLocation - 1,pionXLocation,true,speler.getSpelerTeam())){
movePiece(pionYLocation - 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "d":
if (movementCheck(pionYLocation + 1,pionXLocation,true,speler.getSpelerTeam())){
movePiece(pionYLocation + 1, pionXLocation, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "r":
if (movementCheck(pionYLocation,pionXLocation + 1,true,speler.getSpelerTeam())){
movePiece(pionYLocation, pionXLocation + 1, pionYLocation, pionXLocation, speler);
return true;
} else {
return false;
}
case "l":
if (movementCheck(pionYLocation,pionXLocation - 1,true,speler.getSpelerTeam())){
movePiece(pionYLocation, pionXLocation - 1, pionYLocation, pionXLocation, speler);
return true;
} else{
return false;
}
default:
//Als geen geldige input wordt ingevuld, als "w,a,s" of "dr", dan komt hij hier in terecht en
//vraagt hij om nieuwe input.
System.out.println("U heeft een ongeldige richting gekozen, kies uit: Up (u), Down (d), Left (l), Right (r)");
return false;
}
}
//hieronder wordt het hele bord geprint, zie volgende methode voor team specifiek bord printen
public void bordPrinten(){
StringBuilder bordstring = new StringBuilder();
bordstring.append("X: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 | \n"); //deze coordinaten worden geprint boven het bord
bordstring.append(" -----------------------------------------\n"); // dit is een afscheiding van coordinaten tov gevulde matrix
bordstring.append("Y: +---+---+---+---+---+---+---+---+---+---+\n");
for (int y = 0; y < 10; y++) {
int yCoordinaat = y + 1;//deze y-coordinaat wordt gedefinieerd zodat deze geprint kan worden als coordinatenstelsel
if (yCoordinaat < 10) {
bordstring.append(" ");//getallen kleiner dan 10, krijgen extra spatie (voor uitlijning)
}
bordstring.append(yCoordinaat + " ");
for (int x = 0; x < 10; x++) { //deze forloop voegt voor ieder vakje de value van het spelstuk toe of een "o" als het vakje leeg is.
String spelstukString;
if (speelBord[y][x] instanceof Speelstuk) {
Speelstuk speelstuk = (Speelstuk) speelBord[y][x];
if (speelstuk.getValue() < 10) {
spelstukString = "| " + speelstuk.getValue() + " "; //een extra spatie toevoegen als de waarde kleiner is dan tien, zodat de uitlijning mooi klopt.
} else {
spelstukString = "|" + speelstuk.getValue() + " ";
}
} else if (speelBord[y][x] instanceof Blokkade) { //Als er een String wordt gevonden dan is het een blokkade
spelstukString = "| x ";
} else { //Leeg stuk ruimte waar heen gelopen kan worden
spelstukString = "| ";
}
bordstring.append(spelstukString);
}
bordstring.append("|\n");//Aan het einde komt nog een rechtstreepje en dan een niewline character
bordstring.append(" +---+---+---+---+---+---+---+---+---+---+\n");
}
System.out.println(bordstring);
}
public String bordPrinten2(){
StringBuilder bordstring = new StringBuilder();
bordstring.append("X: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 | \n"); //deze coordinaten worden geprint boven het bord
bordstring.append(" -----------------------------------------\n"); // dit is een afscheiding van coordinaten tov gevulde matrix
bordstring.append("Y: +---+---+---+---+---+---+---+---+---+---+\n");
for (int y = 0; y < 10; y++) {
int yCoordinaat = y + 1;//deze y-coordinaat wordt gedefinieerd zodat deze geprint kan worden als coordinatenstelsel
if (yCoordinaat < 10) {
bordstring.append(" ");//getallen kleiner dan 10, krijgen extra spatie (voor uitlijning)
}
bordstring.append(yCoordinaat + " ");
for (int x = 0; x < 10; x++) { //deze forloop voegt voor ieder vakje de value van het spelstuk toe of een "o" als het vakje leeg is.
String spelstukString;
if (speelBord[y][x] instanceof Speelstuk) {
Speelstuk speelstuk = (Speelstuk) speelBord[y][x];
if (speelstuk.getValue() < 10) {
spelstukString = "| " + speelstuk.getValue() + " "; //een extra spatie toevoegen als de waarde kleiner is dan tien, zodat de uitlijning mooi klopt.
} else {
spelstukString = "|" + speelstuk.getValue() + " ";
}
} else if (speelBord[y][x] instanceof Blokkade) { //Als er een String wordt gevonden dan is het een blokkade
spelstukString = "| x ";
} else { //Leeg stuk ruimte waar heen gelopen kan worden
spelstukString = "| ";
}
bordstring.append(spelstukString);
}
bordstring.append("|\n");//Aan het einde komt nog een rechtstreepje en dan een niewline character
bordstring.append(" +---+---+---+---+---+---+---+---+---+---+\n");
}
return bordstring.toString();
}
//met onderstaande methode wordt het bord geprint teamspecifiek, je geeft dan het team mee in de methode
public void bordPrinten(int huidigeTeam){
StringBuilder bordstring = new StringBuilder();
bordstring.append("X: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 | \n"); //deze coordinaten worden geprint boven het bord
bordstring.append(" -----------------------------------------\n"); // dit is een afscheiding van coordinaten tov gevulde matrix
bordstring.append("Y: +---+---+---+---+---+---+---+---+---+---+\n");
for (int y = 0; y < 10; y++) {
int yCoordinaat = y+1; //deze y-coordinaat wordt gedefinieerd zodat deze geprint kan worden als coordinatenstelsel
if(yCoordinaat<10) {
bordstring.append(" ");//getallen kleiner dan 10, krijgen extra spatie (voor uitlijning)
}
bordstring.append(yCoordinaat + " ");
for (int x = 0; x < 10; x++) { //deze forloop voegt voor ieder vakje de value van het spelstuk toe of een "o" als het vakje leeg is.
String spelstukString;
if (speelBord[y][x] instanceof Speelstuk) {
Speelstuk speelstuk = (Speelstuk) speelBord[y][x];
if (speelstuk.getTeam()==huidigeTeam){ //als team gelijk is aan huidigeteam --> print de values van speelstuk
if (speelstuk.getValue() < 10) {
spelstukString = "| " + speelstuk.getValue() + " "; //een extra spatie toevoegen als de waarde kleiner is dan tien, zodat de uitlijning mooi klopt.
} else {
spelstukString = "|" + speelstuk.getValue() + " ";
}
}else {
spelstukString = "|xxx"; //print xx voor speelstuk van tegenstander (andere team)
}
} else if (speelBord[y][x] instanceof Blokkade) { //Als er een String wordt gevonden dan is het een blokkade
spelstukString = "| x ";
} else { //Leeg stuk ruimte waar heen gelopen kan worden
spelstukString = "| ";
}
bordstring.append(spelstukString);
}
bordstring.append("|\n");//Aan het einde komt nog een rechtstreepje en dan een niewline character
bordstring.append(" +---+---+---+---+---+---+---+---+---+---+\n");
}
System.out.println(bordstring);
}
//getters and setter
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Object[][] getSpeelBord() {
return speelBord;
}
}
class Blokkade{}
|
13777_23 | package gna;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* The example JUnit test described in Practicum 3.
* <p>
* Make sure you write sufficient tests of your own as well.
*/
public class ExampleTests {
@Test
public void testPracticumExampleNotSufficientEnergy() {
// Example given in practicum
// | . . M . . . |
// | H M . . X X |
// | H . E . . E |
// | E E X . . . |
String[][] tiles = new String[][]{
{".", ".", "M", ".", ".", "."},
{"H", "M", ".", ".", "X", "X"},
{"H", ".", "E", ".", "E", "E"},
{"E", "E", "X", ".", ".", "."}};
int energy = 4;
Board board = new Board(tiles, energy);
boolean isSolvable = board.isSolvable();
/* Check if isSolveable */
String message = "Voor bord {{. . M . . .},{H M . . X X},{H . E . . E},{E E X . . .}} met begin-energie 6 zou je de finish niet mogen halen. Jij doet dat echter wel";
assertFalse(message, isSolvable);
}
@Test
public void testPracticumExampleSufficientEnergy() {
// Example given in practicum
// | . . M . . . |
// | H M . . X X |
// | H . E . E E |
// | E E X . . . |
String[][] tiles = new String[][]{
{".", ".", "M", ".", ".", "."},
{"H", "M", ".", ".", "X", "X"},
{"H", ".", "E", ".", "E", "E"},
{"E", "E", "X", ".", ".", "."}};
int energy = 5;
Board board = new Board(tiles, energy);
int energyAtFinish = board.getFinishTileEnergy();
/* Check if finish tile energy is 2 */
String messageEnergy = "Voor bord {{. . M . . .},{H M . . X X},{H . E . . E},{E E X . . .}} met begin-energie 10 zou je nog 2 energie-punten over moeten hebben bij de finish. Bij jou is dat echter: " + energyAtFinish;
assertTrue(messageEnergy, energyAtFinish == 2);
}
@Test
public void testWalls() {
// ?o possible path due to wall positioning
// | . . . . |
// | . . . . |
// | . . X X |
// | . . X . |
String[][] tiles = new String[][]{
{".", ".", ".", "."},
{".", ".", ".", "."},
{".", ".", "X", "X"},
{".", ".", "X", "."}};
int energy = 100;
Board board = new Board(tiles, energy);
boolean isSolvable = board.isSolvable();
String message = "Bord {{. . . . }, {. . X X}, {. . X .}} zou geen oplossing mogen hebben door de omringende muren. Jouw isSolvable geeft echter true.";
assertFalse(message, isSolvable);
}
@Test
public void testNonSquareBoard() {
// Check non-square board
// | . H . . . E .|
// | . X . M . H .|
// | . E . . . M .|
String[][] tiles = new String[][]{
{".", "H", ".", ".", ".", "E", "."},
{".", ".", ".", "M", ".", "H", "."},
{".", "E", ".", ".", ".", "M", "."}};
int energy = 10;
try {
Board board = new Board(tiles, energy);
int energyAtFinish = board.getFinishTileEnergy();
/* Check if energy left is 10 */
String messageEnergy = "Voor bord {{. H . . . E .}, {. . . M . H .}, {. E . . . M .}} met begin-energie 10, verwachten we dat je nog 3 energie-punten over hebt, maar bij jouw is dat nog: " + energyAtFinish;
assertTrue(messageEnergy, energyAtFinish == 3);
} catch (Error e) {
throw new AssertionError("Bij het oplossen van bord {{. H . . . E .}, {. . . M . H .}, {. E . . . M .}} krijgen we een error."); /* TODO: kijk zelf welke error */
}
}
@Test
public void testLargeBoardNeedsToPassEnergy() {
// Needs to pass both energy tiles in order to reach the finish.
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . E . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . E . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . | (11x11)
String[][] tiles = new String[][]{
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", "E", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", "E", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."}};
int energy = 17;
Board board = new Board(tiles, energy);
String[] path = board.getPathSequence();
/* Check if they find a solution */
String messageSolution = "Voor een 11x11 bord met slechts twee energie-tiles op positie 3x7 en 5x9, en met begin-energie 19, is oplosbaar (enkel indien je beide energietiles passeert). Jouw oplossing zegt echter dat dit niet oplosbaar is.";
assertTrue(messageSolution, board.isSolvable());
/* Check if only one energy is left at the finish */
int energyAtFinish = board.getFinishTileEnergy();
String messageEnergy = "Voor een 11x11 bord met slechts twee energie-tiles op positie 3x7 en 5x9, en met begin-energie 19, zou je nog maar 1 energiepunt over mogen hebben bij de finish. Jij hebt er echter nog:" + energyAtFinish;
assertTrue(messageEnergy, energyAtFinish == 1);
// assertTrue("messagePath", path.length == 20); // Dit moet ook waar zijn, maar nodig om hier nog eens te testen?
}
}
| Ferrevdv/Datastructs_Algs_2 | src/gna/ExampleTests.java | 2,060 | /* TODO: kijk zelf welke error */ | block_comment | nl | package gna;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* The example JUnit test described in Practicum 3.
* <p>
* Make sure you write sufficient tests of your own as well.
*/
public class ExampleTests {
@Test
public void testPracticumExampleNotSufficientEnergy() {
// Example given in practicum
// | . . M . . . |
// | H M . . X X |
// | H . E . . E |
// | E E X . . . |
String[][] tiles = new String[][]{
{".", ".", "M", ".", ".", "."},
{"H", "M", ".", ".", "X", "X"},
{"H", ".", "E", ".", "E", "E"},
{"E", "E", "X", ".", ".", "."}};
int energy = 4;
Board board = new Board(tiles, energy);
boolean isSolvable = board.isSolvable();
/* Check if isSolveable */
String message = "Voor bord {{. . M . . .},{H M . . X X},{H . E . . E},{E E X . . .}} met begin-energie 6 zou je de finish niet mogen halen. Jij doet dat echter wel";
assertFalse(message, isSolvable);
}
@Test
public void testPracticumExampleSufficientEnergy() {
// Example given in practicum
// | . . M . . . |
// | H M . . X X |
// | H . E . E E |
// | E E X . . . |
String[][] tiles = new String[][]{
{".", ".", "M", ".", ".", "."},
{"H", "M", ".", ".", "X", "X"},
{"H", ".", "E", ".", "E", "E"},
{"E", "E", "X", ".", ".", "."}};
int energy = 5;
Board board = new Board(tiles, energy);
int energyAtFinish = board.getFinishTileEnergy();
/* Check if finish tile energy is 2 */
String messageEnergy = "Voor bord {{. . M . . .},{H M . . X X},{H . E . . E},{E E X . . .}} met begin-energie 10 zou je nog 2 energie-punten over moeten hebben bij de finish. Bij jou is dat echter: " + energyAtFinish;
assertTrue(messageEnergy, energyAtFinish == 2);
}
@Test
public void testWalls() {
// ?o possible path due to wall positioning
// | . . . . |
// | . . . . |
// | . . X X |
// | . . X . |
String[][] tiles = new String[][]{
{".", ".", ".", "."},
{".", ".", ".", "."},
{".", ".", "X", "X"},
{".", ".", "X", "."}};
int energy = 100;
Board board = new Board(tiles, energy);
boolean isSolvable = board.isSolvable();
String message = "Bord {{. . . . }, {. . X X}, {. . X .}} zou geen oplossing mogen hebben door de omringende muren. Jouw isSolvable geeft echter true.";
assertFalse(message, isSolvable);
}
@Test
public void testNonSquareBoard() {
// Check non-square board
// | . H . . . E .|
// | . X . M . H .|
// | . E . . . M .|
String[][] tiles = new String[][]{
{".", "H", ".", ".", ".", "E", "."},
{".", ".", ".", "M", ".", "H", "."},
{".", "E", ".", ".", ".", "M", "."}};
int energy = 10;
try {
Board board = new Board(tiles, energy);
int energyAtFinish = board.getFinishTileEnergy();
/* Check if energy left is 10 */
String messageEnergy = "Voor bord {{. H . . . E .}, {. . . M . H .}, {. E . . . M .}} met begin-energie 10, verwachten we dat je nog 3 energie-punten over hebt, maar bij jouw is dat nog: " + energyAtFinish;
assertTrue(messageEnergy, energyAtFinish == 3);
} catch (Error e) {
throw new AssertionError("Bij het oplossen van bord {{. H . . . E .}, {. . . M . H .}, {. E . . . M .}} krijgen we een error."); /* TODO: kijk zelf<SUF>*/
}
}
@Test
public void testLargeBoardNeedsToPassEnergy() {
// Needs to pass both energy tiles in order to reach the finish.
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . E . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . E . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . |
// | . . . . . . . . . . . | (11x11)
String[][] tiles = new String[][]{
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", "E", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", "E", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."},
{".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."}};
int energy = 17;
Board board = new Board(tiles, energy);
String[] path = board.getPathSequence();
/* Check if they find a solution */
String messageSolution = "Voor een 11x11 bord met slechts twee energie-tiles op positie 3x7 en 5x9, en met begin-energie 19, is oplosbaar (enkel indien je beide energietiles passeert). Jouw oplossing zegt echter dat dit niet oplosbaar is.";
assertTrue(messageSolution, board.isSolvable());
/* Check if only one energy is left at the finish */
int energyAtFinish = board.getFinishTileEnergy();
String messageEnergy = "Voor een 11x11 bord met slechts twee energie-tiles op positie 3x7 en 5x9, en met begin-energie 19, zou je nog maar 1 energiepunt over mogen hebben bij de finish. Jij hebt er echter nog:" + energyAtFinish;
assertTrue(messageEnergy, energyAtFinish == 1);
// assertTrue("messagePath", path.length == 20); // Dit moet ook waar zijn, maar nodig om hier nog eens te testen?
}
}
|
92121_5 | /*******************************************************************************
* Copyright (c) 2009-2013 CWI
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* * Wietse Venema - [email protected] - CWI
* * Paul Klint - [email protected] - CWI
*******************************************************************************/
package org.rascalmpl.library.experiments.Compiler.Rascal2muRascal;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.Calendar;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IMapWriter;
import org.eclipse.imp.pdb.facts.ISet;
import org.eclipse.imp.pdb.facts.ISetWriter;
import org.eclipse.imp.pdb.facts.ISourceLocation;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.IValueFactory;
import org.eclipse.imp.pdb.facts.type.ITypeVisitor;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.type.TypeStore;
import org.rascalmpl.interpreter.control_exceptions.Throw;
import org.rascalmpl.library.cobra.RandomType;
import org.rascalmpl.uri.URIUtil;
import org.rascalmpl.values.ValueFactoryFactory;
public class RandomValueTypeVisitor implements ITypeVisitor<IValue, RuntimeException> {
private static final Random stRandom = new Random();
private final IValueFactory vf;
private final TypeFactory tf = TypeFactory.getInstance();
//private final ModuleEnvironment rootEnv;
TypeStore definitions;
private final int maxDepth;
private final Map<Type, Type> typeParameters;
public RandomValueTypeVisitor(IValueFactory vf, int maxDepth, Map<Type, Type> typeParameters, TypeStore definitions) {
this.vf = vf;
//this.rootEnv = rootEnv;
this.maxDepth = maxDepth;
//this.generators = generators;
this.typeParameters = typeParameters;
this.definitions = definitions;
}
private RandomValueTypeVisitor descend() {
RandomValueTypeVisitor visitor = new RandomValueTypeVisitor(vf, maxDepth - 1, typeParameters, definitions);
return visitor;
}
public IValue generate(Type t) {
return t.accept(this);
}
private IValue genSet(Type type) {
ISetWriter writer = vf.setWriter(); // type.writer(vf);
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return writer.done();
} else {
RandomValueTypeVisitor visitor = descend();
ISet set = (ISet) visitor.generate(type);
IValue element = null;
int recursionGuard = 0; // Domain of set can be small.
while ((element == null || set.contains(element))
&& recursionGuard < 1000) {
recursionGuard += 1;
element = visitor.generate(type.getElementType());
}
writer.insertAll(set);
if (element != null) {
writer.insert(element);
}
return writer.done();
}
}
@Override
public IValue visitAbstractData(Type type) {
LinkedList<Type> alternatives = new LinkedList<Type>();
alternatives.addAll(definitions.lookupAlternatives(type));
Collections.shuffle(alternatives);
for (Type pick : alternatives) {
IConstructor result = (IConstructor) this.generate(pick);
if (result != null) {
RandomValueTypeVisitor visitor = descend();
Map<String, Type> annotations = definitions.getAnnotations(type);
for (Map.Entry<String, Type> entry : annotations.entrySet()) {
IValue value = visitor.generate(entry.getValue());
if (value == null) {
return null;
}
result = result.asAnnotatable().setAnnotation(entry.getKey(), value);
}
return result;
}
}
return null;
}
@Override
public IValue visitAlias(Type type) {
// Het is niet mogelijk om een circulaire alias te maken dus dit kost
// geen diepte.
return this.generate(type.getAliased());
}
@Override
public IValue visitBool(Type boolType) {
return vf.bool(stRandom.nextBoolean());
}
@Override
public IValue visitConstructor(Type type) {
/*
* Following the common definition of depth of tree, the depth of an
* algebraic datatype with zero arguments is 0 and the depth of an
* alternative with more than 0 arguments is defined as the maximum
* depth of the list of arguments plus 1.
*/
if (type.getArity() == 0) { // Diepte 0 dus we mogen altijd opleveren.
return vf.constructor(type);
} else if (this.maxDepth <= 0) {
return null;
}
RandomValueTypeVisitor visitor = descend();
LinkedList<IValue> values = new LinkedList<IValue>();
for (int i = 0; i < type.getArity(); i++) {
Type fieldType = type.getFieldType(i);
IValue argument = visitor.generate(fieldType);
if (argument == null) {
return null;
/*
* Het is onmogelijk om de constructor te bouwen als ������n
* argument null is.
*/
}
values.add(argument);
}
return vf.constructor(type, values.toArray(new IValue[values.size()]));
}
@Override
public IValue visitDateTime(Type type) {
Calendar cal = Calendar.getInstance();
int milliOffset = stRandom.nextInt(1000) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MILLISECOND, milliOffset);
int second = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.SECOND, second);
int minute = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MINUTE, minute);
int hour = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.HOUR_OF_DAY, hour);
int day = stRandom.nextInt(30) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.DAY_OF_MONTH, day);
int month = stRandom.nextInt(12) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MONTH, month);
// make sure we do not go over the 4 digit year limit, which breaks things
int year = stRandom.nextInt(5000) * (stRandom.nextBoolean() ? -1 : 1);
// make sure we don't go into negative territory
if (cal.get(Calendar.YEAR) + year < 1)
cal.add(Calendar.YEAR, 1);
else
cal.add(Calendar.YEAR, year);
return vf.datetime(cal.getTimeInMillis());
}
@Override
public IValue visitExternal(Type externalType) {
throw new Throw(vf.string("Can't handle ExternalType."),
(ISourceLocation) null, null);
}
@Override
public IValue visitInteger(Type type) {
return vf.integer(stRandom.nextInt());
}
private IValue genList(Type type){
IListWriter writer = vf.listWriter(); // type.writer(vf);
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return writer.done();
} else {
RandomValueTypeVisitor visitor = descend();
IValue element = visitor.generate(type.getElementType());
if (element != null) {
writer.append(element);
}
writer.appendAll((IList) visitor.generate(type));
return writer.done();
}
}
@Override
public IValue visitList(Type type) {
return genList(type);
}
@Override
public IValue visitMap(Type type) {
IMapWriter writer = vf.mapWriter(); // type.writer(vf);
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return writer.done();
} else {
RandomValueTypeVisitor visitor = descend();
IValue key = visitor.generate(type.getKeyType());
IValue value = visitor.generate(type.getValueType());
if (key != null && value != null) {
writer.put(key, value);
}
writer.putAll((IMap) visitor.generate(type));
return writer.done();
}
}
@Override
public IValue visitNode(Type type) {
String str = Math.random() > 0.5 ? RandomStringUtils.random(stRandom.nextInt(5)) : RandomStringUtils.randomAlphanumeric(stRandom.nextInt(5));
int arity = maxDepth <= 0 ? 0: stRandom.nextInt(5);
IValue[] args = new IValue[arity];
for (int i = 0; i < arity; i++) {
args[i] = descend().generate(tf.valueType());
}
return vf.node(str, args);
}
@Override
public IValue visitNumber(Type type) {
switch (stRandom.nextInt(3)) {
case 0:
return this.visitInteger(type);
case 1:
return this.visitReal(type);
default:
return this.visitRational(type);
}
}
@Override
public IValue visitParameter(Type parameterType) {
// FIXME Type parameters binden aan echte type van actual value in call.
Type type = typeParameters.get(parameterType);
if(type == null){
throw new IllegalArgumentException("Unbound type parameter " + parameterType);
}
return this.generate(type);
}
@Override
public IValue visitRational(Type type) {
return vf.rational(stRandom.nextInt(), stRandom.nextInt());
}
@Override
public IValue visitReal(Type type) {
return vf.real(stRandom.nextDouble());
}
@Override
public IValue visitSet(Type type) {
return genSet(type);
}
@Override
public IValue visitSourceLocation(Type type) {
if (maxDepth <= 0) {
return vf.sourceLocation(URIUtil.assumeCorrect("tmp:///"));
}
else {
try {
String path = Math.random() < 0.9 ? RandomStringUtils.randomAlphanumeric(stRandom.nextInt(5)) : RandomStringUtils.random(stRandom.nextInt(5));
String nested = "";
URI uri = URIUtil.assumeCorrect("tmp:///");
if (Math.random() > 0.5) {
RandomValueTypeVisitor visitor = descend();
ISourceLocation loc = (ISourceLocation) visitor.generate(type);
uri = loc.getURI();
nested = uri.getPath();
}
path = path.startsWith("/") ? path : "/" + path;
uri = URIUtil.changePath(uri, nested.length() > 0 && !nested.equals("/") ? nested + path : path);
return vf.sourceLocation(uri);
} catch (URISyntaxException e) {
// generated illegal URI?
return vf.sourceLocation(URIUtil.assumeCorrect("tmp:///"));
}
}
}
@Override
public IValue visitString(Type type) {
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return vf.string("");
} else {
RandomValueTypeVisitor visitor = descend();
IString str = vf.string(visitor.generate(type).toString());
IString result = str.concat(vf.string(RandomStringUtils.random(1)));
// make sure we are not generating very strange sequences
String normalized = Normalizer.normalize(result.getValue(), Form.NFC);
return vf.string(normalized);
}
}
@Override
public IValue visitTuple(Type type) {
RandomValueTypeVisitor visitor = descend();
IValue[] elems = new IValue[type.getArity()];
for (int i = 0; i < type.getArity(); i++) {
Type fieldType = type.getFieldType(i);
IValue element = visitor.generate(fieldType);
if (element == null) {
return null;
}
elems[i] = visitor.generate(fieldType);
}
return vf.tuple(elems);
}
@Override
public IValue visitValue(Type type) {
RandomType rt = new RandomType();
return this.generate(rt.getType(maxDepth));
}
@Override
public IValue visitVoid(Type type) {
throw new Throw(vf.string("void has no values."),
(ISourceLocation) null, null);
}
public static void main(String[] args) {
RandomValueTypeVisitor r = new RandomValueTypeVisitor(ValueFactoryFactory.getValueFactory(), 3, null, null);
Type intType = r.tf.integerType();
Type strType = r.tf.stringType();
System.out.println(r.generate(r.tf.setType(intType)));
}
}
| FerryRiet/Rascal-clone | src/org/rascalmpl/library/experiments/Compiler/Rascal2muRascal/RandomValueTypeVisitor.java | 3,905 | // Het is niet mogelijk om een circulaire alias te maken dus dit kost | line_comment | nl | /*******************************************************************************
* Copyright (c) 2009-2013 CWI
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* * Wietse Venema - [email protected] - CWI
* * Paul Klint - [email protected] - CWI
*******************************************************************************/
package org.rascalmpl.library.experiments.Compiler.Rascal2muRascal;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.Calendar;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IMapWriter;
import org.eclipse.imp.pdb.facts.ISet;
import org.eclipse.imp.pdb.facts.ISetWriter;
import org.eclipse.imp.pdb.facts.ISourceLocation;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.IValueFactory;
import org.eclipse.imp.pdb.facts.type.ITypeVisitor;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.type.TypeStore;
import org.rascalmpl.interpreter.control_exceptions.Throw;
import org.rascalmpl.library.cobra.RandomType;
import org.rascalmpl.uri.URIUtil;
import org.rascalmpl.values.ValueFactoryFactory;
public class RandomValueTypeVisitor implements ITypeVisitor<IValue, RuntimeException> {
private static final Random stRandom = new Random();
private final IValueFactory vf;
private final TypeFactory tf = TypeFactory.getInstance();
//private final ModuleEnvironment rootEnv;
TypeStore definitions;
private final int maxDepth;
private final Map<Type, Type> typeParameters;
public RandomValueTypeVisitor(IValueFactory vf, int maxDepth, Map<Type, Type> typeParameters, TypeStore definitions) {
this.vf = vf;
//this.rootEnv = rootEnv;
this.maxDepth = maxDepth;
//this.generators = generators;
this.typeParameters = typeParameters;
this.definitions = definitions;
}
private RandomValueTypeVisitor descend() {
RandomValueTypeVisitor visitor = new RandomValueTypeVisitor(vf, maxDepth - 1, typeParameters, definitions);
return visitor;
}
public IValue generate(Type t) {
return t.accept(this);
}
private IValue genSet(Type type) {
ISetWriter writer = vf.setWriter(); // type.writer(vf);
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return writer.done();
} else {
RandomValueTypeVisitor visitor = descend();
ISet set = (ISet) visitor.generate(type);
IValue element = null;
int recursionGuard = 0; // Domain of set can be small.
while ((element == null || set.contains(element))
&& recursionGuard < 1000) {
recursionGuard += 1;
element = visitor.generate(type.getElementType());
}
writer.insertAll(set);
if (element != null) {
writer.insert(element);
}
return writer.done();
}
}
@Override
public IValue visitAbstractData(Type type) {
LinkedList<Type> alternatives = new LinkedList<Type>();
alternatives.addAll(definitions.lookupAlternatives(type));
Collections.shuffle(alternatives);
for (Type pick : alternatives) {
IConstructor result = (IConstructor) this.generate(pick);
if (result != null) {
RandomValueTypeVisitor visitor = descend();
Map<String, Type> annotations = definitions.getAnnotations(type);
for (Map.Entry<String, Type> entry : annotations.entrySet()) {
IValue value = visitor.generate(entry.getValue());
if (value == null) {
return null;
}
result = result.asAnnotatable().setAnnotation(entry.getKey(), value);
}
return result;
}
}
return null;
}
@Override
public IValue visitAlias(Type type) {
// Het is<SUF>
// geen diepte.
return this.generate(type.getAliased());
}
@Override
public IValue visitBool(Type boolType) {
return vf.bool(stRandom.nextBoolean());
}
@Override
public IValue visitConstructor(Type type) {
/*
* Following the common definition of depth of tree, the depth of an
* algebraic datatype with zero arguments is 0 and the depth of an
* alternative with more than 0 arguments is defined as the maximum
* depth of the list of arguments plus 1.
*/
if (type.getArity() == 0) { // Diepte 0 dus we mogen altijd opleveren.
return vf.constructor(type);
} else if (this.maxDepth <= 0) {
return null;
}
RandomValueTypeVisitor visitor = descend();
LinkedList<IValue> values = new LinkedList<IValue>();
for (int i = 0; i < type.getArity(); i++) {
Type fieldType = type.getFieldType(i);
IValue argument = visitor.generate(fieldType);
if (argument == null) {
return null;
/*
* Het is onmogelijk om de constructor te bouwen als ������n
* argument null is.
*/
}
values.add(argument);
}
return vf.constructor(type, values.toArray(new IValue[values.size()]));
}
@Override
public IValue visitDateTime(Type type) {
Calendar cal = Calendar.getInstance();
int milliOffset = stRandom.nextInt(1000) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MILLISECOND, milliOffset);
int second = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.SECOND, second);
int minute = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MINUTE, minute);
int hour = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.HOUR_OF_DAY, hour);
int day = stRandom.nextInt(30) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.DAY_OF_MONTH, day);
int month = stRandom.nextInt(12) * (stRandom.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MONTH, month);
// make sure we do not go over the 4 digit year limit, which breaks things
int year = stRandom.nextInt(5000) * (stRandom.nextBoolean() ? -1 : 1);
// make sure we don't go into negative territory
if (cal.get(Calendar.YEAR) + year < 1)
cal.add(Calendar.YEAR, 1);
else
cal.add(Calendar.YEAR, year);
return vf.datetime(cal.getTimeInMillis());
}
@Override
public IValue visitExternal(Type externalType) {
throw new Throw(vf.string("Can't handle ExternalType."),
(ISourceLocation) null, null);
}
@Override
public IValue visitInteger(Type type) {
return vf.integer(stRandom.nextInt());
}
private IValue genList(Type type){
IListWriter writer = vf.listWriter(); // type.writer(vf);
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return writer.done();
} else {
RandomValueTypeVisitor visitor = descend();
IValue element = visitor.generate(type.getElementType());
if (element != null) {
writer.append(element);
}
writer.appendAll((IList) visitor.generate(type));
return writer.done();
}
}
@Override
public IValue visitList(Type type) {
return genList(type);
}
@Override
public IValue visitMap(Type type) {
IMapWriter writer = vf.mapWriter(); // type.writer(vf);
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return writer.done();
} else {
RandomValueTypeVisitor visitor = descend();
IValue key = visitor.generate(type.getKeyType());
IValue value = visitor.generate(type.getValueType());
if (key != null && value != null) {
writer.put(key, value);
}
writer.putAll((IMap) visitor.generate(type));
return writer.done();
}
}
@Override
public IValue visitNode(Type type) {
String str = Math.random() > 0.5 ? RandomStringUtils.random(stRandom.nextInt(5)) : RandomStringUtils.randomAlphanumeric(stRandom.nextInt(5));
int arity = maxDepth <= 0 ? 0: stRandom.nextInt(5);
IValue[] args = new IValue[arity];
for (int i = 0; i < arity; i++) {
args[i] = descend().generate(tf.valueType());
}
return vf.node(str, args);
}
@Override
public IValue visitNumber(Type type) {
switch (stRandom.nextInt(3)) {
case 0:
return this.visitInteger(type);
case 1:
return this.visitReal(type);
default:
return this.visitRational(type);
}
}
@Override
public IValue visitParameter(Type parameterType) {
// FIXME Type parameters binden aan echte type van actual value in call.
Type type = typeParameters.get(parameterType);
if(type == null){
throw new IllegalArgumentException("Unbound type parameter " + parameterType);
}
return this.generate(type);
}
@Override
public IValue visitRational(Type type) {
return vf.rational(stRandom.nextInt(), stRandom.nextInt());
}
@Override
public IValue visitReal(Type type) {
return vf.real(stRandom.nextDouble());
}
@Override
public IValue visitSet(Type type) {
return genSet(type);
}
@Override
public IValue visitSourceLocation(Type type) {
if (maxDepth <= 0) {
return vf.sourceLocation(URIUtil.assumeCorrect("tmp:///"));
}
else {
try {
String path = Math.random() < 0.9 ? RandomStringUtils.randomAlphanumeric(stRandom.nextInt(5)) : RandomStringUtils.random(stRandom.nextInt(5));
String nested = "";
URI uri = URIUtil.assumeCorrect("tmp:///");
if (Math.random() > 0.5) {
RandomValueTypeVisitor visitor = descend();
ISourceLocation loc = (ISourceLocation) visitor.generate(type);
uri = loc.getURI();
nested = uri.getPath();
}
path = path.startsWith("/") ? path : "/" + path;
uri = URIUtil.changePath(uri, nested.length() > 0 && !nested.equals("/") ? nested + path : path);
return vf.sourceLocation(uri);
} catch (URISyntaxException e) {
// generated illegal URI?
return vf.sourceLocation(URIUtil.assumeCorrect("tmp:///"));
}
}
}
@Override
public IValue visitString(Type type) {
if (maxDepth <= 0 || (stRandom.nextInt(2) == 0)) {
return vf.string("");
} else {
RandomValueTypeVisitor visitor = descend();
IString str = vf.string(visitor.generate(type).toString());
IString result = str.concat(vf.string(RandomStringUtils.random(1)));
// make sure we are not generating very strange sequences
String normalized = Normalizer.normalize(result.getValue(), Form.NFC);
return vf.string(normalized);
}
}
@Override
public IValue visitTuple(Type type) {
RandomValueTypeVisitor visitor = descend();
IValue[] elems = new IValue[type.getArity()];
for (int i = 0; i < type.getArity(); i++) {
Type fieldType = type.getFieldType(i);
IValue element = visitor.generate(fieldType);
if (element == null) {
return null;
}
elems[i] = visitor.generate(fieldType);
}
return vf.tuple(elems);
}
@Override
public IValue visitValue(Type type) {
RandomType rt = new RandomType();
return this.generate(rt.getType(maxDepth));
}
@Override
public IValue visitVoid(Type type) {
throw new Throw(vf.string("void has no values."),
(ISourceLocation) null, null);
}
public static void main(String[] args) {
RandomValueTypeVisitor r = new RandomValueTypeVisitor(ValueFactoryFactory.getValueFactory(), 3, null, null);
Type intType = r.tf.integerType();
Type strType = r.tf.stringType();
System.out.println(r.generate(r.tf.setType(intType)));
}
}
|
102045_2 | import entity.*;
import org.junit.Test;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class Deel2 {
//Schrijf een consumer die er voor zorgt dat de de laatste twee characters van alle strings uit een List van strings wordt verwijderd
@Test
public void consumer_1() {
Consumer<List<String>> edit = l -> {
for (int i = 0; i < l.size(); i++) {
String s = l.get(i);
l.set(i, s.substring(0, s.length() - 2));
}
};
List<String> list = new ArrayList<>(Arrays.asList("Joske", "Bertje", "Jeanke"));
edit.accept(list);
assertEquals("Jos", list.get(0));
assertEquals("Bert", list.get(1));
assertEquals("Jean", list.get(2));
}
//Schrijf een function die een Kat omvormt tot een Hond en zijn naam laat beginnen met Hond
@Test
public void function_1() {
//Pas aan
Function<Kat, Hond> transform = cat -> new Hond("Hond" + cat.getNaam());
String naam = "Garfield";
Kat h = new Kat(naam);
Dier d = transform.apply(h);
assertTrue(d instanceof Hond);
assertEquals("HondGarfield", d.getNaam());
}
//Schrijf een predicate die enkel true terugstuurt als een persoon geen huisdier heeft (null) of wanneer hij wel een huisdier bezit, maar hij de juiste vergunning heeft of het dier vergunningstype GEEN heeft.
@Test
public void predicate_1() {
Predicate<Persoon> controleer = p -> {
if (p.getDier() == null) {
return true;
}
Dier animal = p.getDier();
if (animal.getVergunning() == Dier.Vergunningstype.GEEN) {
return true;
}
return p.getVergunningen().contains(animal.getVergunning());
};
Persoon p1 = new Persoon("Jef", new Hond("Samson"));
Persoon p2 = new Persoon("Jos");
Persoon p3 = new Persoon("Jan", new Kat("Shadow"));
Persoon p4 = new Persoon("Jimmy", new GiftigeSlang("Ka"));
Persoon p5 = new Persoon("Jil", new GiftigeSlang("Ka"));
p5.addVergunningen(Dier.Vergunningstype.MILEUVERGUNNING);
assertTrue(controleer.test(p1));
assertTrue(controleer.test(p2));
assertTrue(controleer.test(p3));
assertFalse(controleer.test(p4));
assertTrue(controleer.test(p5));
}
//Verwijder alle personen uit de lijst die een GiftigeSlang hebben als huisdier.
@Test
public void predicate_2() {
List<Persoon> personen = new ArrayList<>(Arrays.asList(
new Persoon("Jef", new Hond("Samson")),
new Persoon("Jos"),
new Persoon("Jan", new Kat("Shadow")),
new Persoon("Jimmy", new GiftigeSlang("Ka")),
new Persoon("Jil", new GiftigeSlang("Ka")),
new Persoon("Jeremy", new Kat("Garfield"))
));
//Pas aan
personen.removeIf(p -> p.getDier() instanceof GiftigeSlang);
assertFalse(personen.stream().anyMatch((p) -> p.getNaam().equals("Jimmy") || p.getNaam().equals("Jil")));
assertEquals(personen.size(), 4);
}
class Planeet
{
private String naam;
private int grootte;
private double gewicht;
public Planeet(String naam, int grootte, double gewicht) {
this.naam = naam;
this.grootte = grootte;
this.gewicht = gewicht;
}
}
private List<Planeet> planeten = Arrays.asList(
new Planeet("Aarde", 3, 2.2),
new Planeet("Aarde", 4, 2.2),
new Planeet("Tatooine", 3, 2.2),
new Planeet("Coruuscant", 20, 2.2),
new Planeet("Hoth", 20, 2.2),
null,
new Planeet("Naboo", 4, 2.2),
new Planeet("Coruuscant", 2, 5.2),
null,
new Planeet("Alderaan", 3, 8),
new Planeet("Kashyyyk", 77, 7),
new Planeet("Yavin", 33, 3)
);
//Schrijf een Comparator dat Planeten vergelijkt op grootte en daarna op gewicht. als een planeet wordt vergeleken met null is de null kleiner (eerst)
@Test
public void comparator_1() {
Comparator<Planeet> vglplaneet = (p1, p2) -> {
if (p2 == null) {
return 1;
}
if (p1 == null) {
return -1;
}
if (p1.grootte != p2.grootte) {
return p1.grootte - p2.grootte;
}
if (p1.gewicht != p2.gewicht) {
return (int) (p1.gewicht - p2.gewicht);
}
return 0;
};
assertTrue(vglplaneet.compare(planeten.get(3), planeten.get(4)) == 0);
assertTrue(vglplaneet.compare(planeten.get(2), planeten.get(9)) < 0);
planeten.sort(vglplaneet);
assertEquals(planeten.get(0), null);
assertEquals(planeten.get(1), null);
assertEquals(planeten.get(2).naam, "Coruuscant");
assertEquals(planeten.get(planeten.size()-1).naam, "Kashyyyk");
}
// Implementeer een functie die alle planeten die groter zijn dan 25 en een a hebben in hun naam (niet hoofdlettergevoelig) gaat samensmelten in één string (elke planeet wordt gevolgd door een komma en een spatie).
// Gebruik hiervoor een stream. Doe dit in één statement. (één schakeling van stream functies)
@Test
public void toonBepaaldePlaneten()
{
//vul aan
String s = planeten
.stream()
.filter(Objects::nonNull)
.filter(p -> p.grootte > 25)
.filter(p -> p.naam.toLowerCase().contains("a"))
.map(p -> p.naam + ", ")
.collect(Collectors.joining());
assertEquals("Kashyyyk, Yavin, ", s);
}
@Test
// Gebruik een stream om van een lijst van strings te gaan naar een lijst van planeten. De strings hebben volgende format: <naam planeet>:<grootte planeet>:<gewicht planeet>
// Doe dit in één statement. (één aaneenschakeling van stream functies)
public void mapPlaneten()
{
List<String> splaneten = Arrays.asList(
"Aarde:2:10",
"Venus:2:8",
"Mars:3:8.5",
"Jupiter:2:7.6",
"Venus:30:10.5");
//vul aan
List<Planeet> planeten = splaneten.
stream()
.map(s -> s.split(":"))
.map(l -> {
String name = l[0];
Integer grootte = Integer.parseInt(l[1]);
Double gewicht = Double.parseDouble(l[2]);
return new Planeet(name, grootte, gewicht);
})
.toList();
assertEquals(planeten.get(3).naam, "Jupiter");
assertEquals(planeten.get(3).grootte, 2);
assertEquals(planeten.get(3).gewicht, 7.6, 0);
}
}
| Fesaa/EHB | BA2/Java-Advanced/Voorbeeldexamen/vraag1/src/test/java/Deel2.java | 2,303 | //Schrijf een predicate die enkel true terugstuurt als een persoon geen huisdier heeft (null) of wanneer hij wel een huisdier bezit, maar hij de juiste vergunning heeft of het dier vergunningstype GEEN heeft. | line_comment | nl | import entity.*;
import org.junit.Test;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class Deel2 {
//Schrijf een consumer die er voor zorgt dat de de laatste twee characters van alle strings uit een List van strings wordt verwijderd
@Test
public void consumer_1() {
Consumer<List<String>> edit = l -> {
for (int i = 0; i < l.size(); i++) {
String s = l.get(i);
l.set(i, s.substring(0, s.length() - 2));
}
};
List<String> list = new ArrayList<>(Arrays.asList("Joske", "Bertje", "Jeanke"));
edit.accept(list);
assertEquals("Jos", list.get(0));
assertEquals("Bert", list.get(1));
assertEquals("Jean", list.get(2));
}
//Schrijf een function die een Kat omvormt tot een Hond en zijn naam laat beginnen met Hond
@Test
public void function_1() {
//Pas aan
Function<Kat, Hond> transform = cat -> new Hond("Hond" + cat.getNaam());
String naam = "Garfield";
Kat h = new Kat(naam);
Dier d = transform.apply(h);
assertTrue(d instanceof Hond);
assertEquals("HondGarfield", d.getNaam());
}
//Schrijf een<SUF>
@Test
public void predicate_1() {
Predicate<Persoon> controleer = p -> {
if (p.getDier() == null) {
return true;
}
Dier animal = p.getDier();
if (animal.getVergunning() == Dier.Vergunningstype.GEEN) {
return true;
}
return p.getVergunningen().contains(animal.getVergunning());
};
Persoon p1 = new Persoon("Jef", new Hond("Samson"));
Persoon p2 = new Persoon("Jos");
Persoon p3 = new Persoon("Jan", new Kat("Shadow"));
Persoon p4 = new Persoon("Jimmy", new GiftigeSlang("Ka"));
Persoon p5 = new Persoon("Jil", new GiftigeSlang("Ka"));
p5.addVergunningen(Dier.Vergunningstype.MILEUVERGUNNING);
assertTrue(controleer.test(p1));
assertTrue(controleer.test(p2));
assertTrue(controleer.test(p3));
assertFalse(controleer.test(p4));
assertTrue(controleer.test(p5));
}
//Verwijder alle personen uit de lijst die een GiftigeSlang hebben als huisdier.
@Test
public void predicate_2() {
List<Persoon> personen = new ArrayList<>(Arrays.asList(
new Persoon("Jef", new Hond("Samson")),
new Persoon("Jos"),
new Persoon("Jan", new Kat("Shadow")),
new Persoon("Jimmy", new GiftigeSlang("Ka")),
new Persoon("Jil", new GiftigeSlang("Ka")),
new Persoon("Jeremy", new Kat("Garfield"))
));
//Pas aan
personen.removeIf(p -> p.getDier() instanceof GiftigeSlang);
assertFalse(personen.stream().anyMatch((p) -> p.getNaam().equals("Jimmy") || p.getNaam().equals("Jil")));
assertEquals(personen.size(), 4);
}
class Planeet
{
private String naam;
private int grootte;
private double gewicht;
public Planeet(String naam, int grootte, double gewicht) {
this.naam = naam;
this.grootte = grootte;
this.gewicht = gewicht;
}
}
private List<Planeet> planeten = Arrays.asList(
new Planeet("Aarde", 3, 2.2),
new Planeet("Aarde", 4, 2.2),
new Planeet("Tatooine", 3, 2.2),
new Planeet("Coruuscant", 20, 2.2),
new Planeet("Hoth", 20, 2.2),
null,
new Planeet("Naboo", 4, 2.2),
new Planeet("Coruuscant", 2, 5.2),
null,
new Planeet("Alderaan", 3, 8),
new Planeet("Kashyyyk", 77, 7),
new Planeet("Yavin", 33, 3)
);
//Schrijf een Comparator dat Planeten vergelijkt op grootte en daarna op gewicht. als een planeet wordt vergeleken met null is de null kleiner (eerst)
@Test
public void comparator_1() {
Comparator<Planeet> vglplaneet = (p1, p2) -> {
if (p2 == null) {
return 1;
}
if (p1 == null) {
return -1;
}
if (p1.grootte != p2.grootte) {
return p1.grootte - p2.grootte;
}
if (p1.gewicht != p2.gewicht) {
return (int) (p1.gewicht - p2.gewicht);
}
return 0;
};
assertTrue(vglplaneet.compare(planeten.get(3), planeten.get(4)) == 0);
assertTrue(vglplaneet.compare(planeten.get(2), planeten.get(9)) < 0);
planeten.sort(vglplaneet);
assertEquals(planeten.get(0), null);
assertEquals(planeten.get(1), null);
assertEquals(planeten.get(2).naam, "Coruuscant");
assertEquals(planeten.get(planeten.size()-1).naam, "Kashyyyk");
}
// Implementeer een functie die alle planeten die groter zijn dan 25 en een a hebben in hun naam (niet hoofdlettergevoelig) gaat samensmelten in één string (elke planeet wordt gevolgd door een komma en een spatie).
// Gebruik hiervoor een stream. Doe dit in één statement. (één schakeling van stream functies)
@Test
public void toonBepaaldePlaneten()
{
//vul aan
String s = planeten
.stream()
.filter(Objects::nonNull)
.filter(p -> p.grootte > 25)
.filter(p -> p.naam.toLowerCase().contains("a"))
.map(p -> p.naam + ", ")
.collect(Collectors.joining());
assertEquals("Kashyyyk, Yavin, ", s);
}
@Test
// Gebruik een stream om van een lijst van strings te gaan naar een lijst van planeten. De strings hebben volgende format: <naam planeet>:<grootte planeet>:<gewicht planeet>
// Doe dit in één statement. (één aaneenschakeling van stream functies)
public void mapPlaneten()
{
List<String> splaneten = Arrays.asList(
"Aarde:2:10",
"Venus:2:8",
"Mars:3:8.5",
"Jupiter:2:7.6",
"Venus:30:10.5");
//vul aan
List<Planeet> planeten = splaneten.
stream()
.map(s -> s.split(":"))
.map(l -> {
String name = l[0];
Integer grootte = Integer.parseInt(l[1]);
Double gewicht = Double.parseDouble(l[2]);
return new Planeet(name, grootte, gewicht);
})
.toList();
assertEquals(planeten.get(3).naam, "Jupiter");
assertEquals(planeten.get(3).grootte, 2);
assertEquals(planeten.get(3).gewicht, 7.6, 0);
}
}
|
12211_1 | package program;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class Controller /*implements Runnable*/{
private List<String> checkedUrls = new ArrayList();
private List<String> brokenUrls = new ArrayList();
//private String theUrl; //enkel voor multithreading
/**
* De list leeg maken.
*/
public void resetCheckedUrls(){
checkedUrls.clear();
}
/**
* De list leeg maken.
*/
public void resetBrokenUrls(){
brokenUrls.clear();
}
/* Enkel voor
@Override
public void run(){
getWebpage(theUrl);
}*/
/**
* valideert of de url een lokale url is.
* @param url
* @return
*/
public static boolean validateUrl(String url) {
return url.matches("((https?://)?localhost){1}([a-zA-Z0-9]*)?/?([a-zA-Z0-9\\:\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~])*");
}
/**
* Poging om de header(HEAD) van een website te krijgen.
* Krijgen we een header, wilt dit zeggen dat de link werkt, anders werkt de link niet.
* @param targetUrl
* @return
* http://singztechmusings.wordpress.com/2011/05/26/java-how-to-check-if-a-web-page-exists-and-is-available/
*/
public static boolean urlExists(String targetUrl) {
HttpURLConnection httpUrlConn;
try {
httpUrlConn = (HttpURLConnection) new URL(targetUrl)
.openConnection();
httpUrlConn.setRequestMethod("HEAD");
// Set timeouts in milliseconds
httpUrlConn.setConnectTimeout(30000);
httpUrlConn.setReadTimeout(30000);
// Print HTTP status code/message for your information.
System.out.println("Response Code: "
+ httpUrlConn.getResponseCode());
System.out.println("Response Message: "
+ httpUrlConn.getResponseMessage() +" - " + targetUrl);
return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return false;
}
}
/**
* In de huidige lijn wordt gekeken of er "<a href=" gevonden wordt want dit wil zeggen dat daarachter een link staat.
* @param line
* @return
**/
public static boolean checkForUrl(String line){
return line.matches("(.)*(<a href=){1}(.)*");
}
/**
* controleert of de url nog nagekeken is.
* @param url
* @return
**/
public boolean notYetChecked(String url){
for(String s:checkedUrls){
if(url.equals(s)) return false;
}
return true;
}
/**
* Heel de webpagina wordt ingeladen en er wordt naar links gezocht.
* @param url
* @return
**/
public List[] getWebpage(String url){
List[] allUrls = new List[2];
String address = "127.0.0.1";
int port = 80;
String get = url.split("http://localhost")[1];
String header = "GET " + get + " HTTP/1.1\n"
+ "Host: localhost\n"
+ "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\n"
+ "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n"
+ "Accept-Language: en-us,en;q=0.5\n"
+ "Accept-Encoding: gzip,deflate\n"
+ "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n"
+ "Keep-Alive: 115\n"
+ "Connection: keep-alive\n"
+ "\r\n";
String link;
//url toevoegen aan de lijst met reeds gecontroleerde url's.
checkedUrls.add(url);
try {
//nieuwe socket aanmaken
Socket sck = new Socket(address, port);
//website inlezen
BufferedReader rd = new BufferedReader(new InputStreamReader(sck.getInputStream()));
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(sck.getOutputStream(), "ISO-8859-1"));
wr.write(header);
wr.flush();
System.out.println("REQUEST HEADER");
System.out.println(header);
System.out.println("RESPONSE HEADER");
String line;
//1 voor 1 elke lijn afgaan.
while ((line = rd.readLine()) != null) {
//System.out.println(line);
if(checkForUrl(line)){
//Er staat een url op deze lijn.
//tekst splitsen waar 'a href="' staat.
String[] parts = line.split("a href=\"");
for(int i=0; i<parts.length; i++){
if(parts[i].matches("http.*")){
//Dit gesplitste deel bevat een url met mss nog wat overbodige tekst achter.
//verwijderen van tekst die nog achter de link staat.
link = parts[i].substring(0, parts[i].indexOf("\""));
if(urlExists(link)){
//De url is een werkende url
if(validateUrl(link) && notYetChecked(link) && !link.matches("(.)*.(pdf|jpg|png)")){
//link is een lokale url die nog niet gecontroleerd is.
/*theUrl = link;
Thread t = new Thread();
t.start();*/
getWebpage(link);
} else {}
}else{
//deze url is "broken"
brokenUrls.add("Broken link:\t" + link + "\n On page:\t" + url + "\n\n");
}
}
}
}
}
wr.close();
rd.close();
sck.close();
} catch (Exception e) {
e.printStackTrace();
}
//alle pagina's die gecontroleerd zijn.
allUrls[0] = checkedUrls;
//alle url's die een foutmelding gaven.
allUrls[1] = brokenUrls;
return allUrls;
}
} | FestiPedia-Java/JavaApplication | Linkrot/src/program/Controller.java | 1,963 | /**
* De list leeg maken.
*/ | block_comment | nl | package program;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class Controller /*implements Runnable*/{
private List<String> checkedUrls = new ArrayList();
private List<String> brokenUrls = new ArrayList();
//private String theUrl; //enkel voor multithreading
/**
* De list leeg<SUF>*/
public void resetCheckedUrls(){
checkedUrls.clear();
}
/**
* De list leeg maken.
*/
public void resetBrokenUrls(){
brokenUrls.clear();
}
/* Enkel voor
@Override
public void run(){
getWebpage(theUrl);
}*/
/**
* valideert of de url een lokale url is.
* @param url
* @return
*/
public static boolean validateUrl(String url) {
return url.matches("((https?://)?localhost){1}([a-zA-Z0-9]*)?/?([a-zA-Z0-9\\:\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~])*");
}
/**
* Poging om de header(HEAD) van een website te krijgen.
* Krijgen we een header, wilt dit zeggen dat de link werkt, anders werkt de link niet.
* @param targetUrl
* @return
* http://singztechmusings.wordpress.com/2011/05/26/java-how-to-check-if-a-web-page-exists-and-is-available/
*/
public static boolean urlExists(String targetUrl) {
HttpURLConnection httpUrlConn;
try {
httpUrlConn = (HttpURLConnection) new URL(targetUrl)
.openConnection();
httpUrlConn.setRequestMethod("HEAD");
// Set timeouts in milliseconds
httpUrlConn.setConnectTimeout(30000);
httpUrlConn.setReadTimeout(30000);
// Print HTTP status code/message for your information.
System.out.println("Response Code: "
+ httpUrlConn.getResponseCode());
System.out.println("Response Message: "
+ httpUrlConn.getResponseMessage() +" - " + targetUrl);
return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return false;
}
}
/**
* In de huidige lijn wordt gekeken of er "<a href=" gevonden wordt want dit wil zeggen dat daarachter een link staat.
* @param line
* @return
**/
public static boolean checkForUrl(String line){
return line.matches("(.)*(<a href=){1}(.)*");
}
/**
* controleert of de url nog nagekeken is.
* @param url
* @return
**/
public boolean notYetChecked(String url){
for(String s:checkedUrls){
if(url.equals(s)) return false;
}
return true;
}
/**
* Heel de webpagina wordt ingeladen en er wordt naar links gezocht.
* @param url
* @return
**/
public List[] getWebpage(String url){
List[] allUrls = new List[2];
String address = "127.0.0.1";
int port = 80;
String get = url.split("http://localhost")[1];
String header = "GET " + get + " HTTP/1.1\n"
+ "Host: localhost\n"
+ "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\n"
+ "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n"
+ "Accept-Language: en-us,en;q=0.5\n"
+ "Accept-Encoding: gzip,deflate\n"
+ "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n"
+ "Keep-Alive: 115\n"
+ "Connection: keep-alive\n"
+ "\r\n";
String link;
//url toevoegen aan de lijst met reeds gecontroleerde url's.
checkedUrls.add(url);
try {
//nieuwe socket aanmaken
Socket sck = new Socket(address, port);
//website inlezen
BufferedReader rd = new BufferedReader(new InputStreamReader(sck.getInputStream()));
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(sck.getOutputStream(), "ISO-8859-1"));
wr.write(header);
wr.flush();
System.out.println("REQUEST HEADER");
System.out.println(header);
System.out.println("RESPONSE HEADER");
String line;
//1 voor 1 elke lijn afgaan.
while ((line = rd.readLine()) != null) {
//System.out.println(line);
if(checkForUrl(line)){
//Er staat een url op deze lijn.
//tekst splitsen waar 'a href="' staat.
String[] parts = line.split("a href=\"");
for(int i=0; i<parts.length; i++){
if(parts[i].matches("http.*")){
//Dit gesplitste deel bevat een url met mss nog wat overbodige tekst achter.
//verwijderen van tekst die nog achter de link staat.
link = parts[i].substring(0, parts[i].indexOf("\""));
if(urlExists(link)){
//De url is een werkende url
if(validateUrl(link) && notYetChecked(link) && !link.matches("(.)*.(pdf|jpg|png)")){
//link is een lokale url die nog niet gecontroleerd is.
/*theUrl = link;
Thread t = new Thread();
t.start();*/
getWebpage(link);
} else {}
}else{
//deze url is "broken"
brokenUrls.add("Broken link:\t" + link + "\n On page:\t" + url + "\n\n");
}
}
}
}
}
wr.close();
rd.close();
sck.close();
} catch (Exception e) {
e.printStackTrace();
}
//alle pagina's die gecontroleerd zijn.
allUrls[0] = checkedUrls;
//alle url's die een foutmelding gaven.
allUrls[1] = brokenUrls;
return allUrls;
}
} |
53445_0 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class RunFromFile {
private static final String IP_ADDRESS = "192.168.43.1";
private static BufferedReader br;
private static DatagramSocket datagramSocket;
private static int i = 0;
public static void main(String[] args) throws InterruptedException, IOException {
initFile();
byte[] tempBytes;
datagramSocket = new DatagramSocket(9000);
tempBytes = getLine();
while (tempBytes != null) {
System.out.println("Sending Packet..");
System.out.println();
sendPacket(tempBytes);
//receivePacket();
Thread.sleep(100);
tempBytes = getLine();
}
}
public static void initFile() throws FileNotFoundException {
br = new BufferedReader(new FileReader("engine_data.txt"));
}
public static byte[] getLine() throws IOException {
String line;
if ((line = br.readLine()) != null) {
byte[] bytearray = new byte[10];
for (int i = 0; i < 20; i += 2) {
byte byte1 = (byte) (Integer.parseInt(line.substring(i, i + 2), 16) & 0xff);
bytearray[i / 2] = byte1;
}
return bytearray;
} else {
br.close();
return null;
}
}
public static String bytArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder();
for (byte b : a)
sb.append(String.format("%02x ", b & 0xff));
return sb.toString();
}
public static void sendPacket(byte[] stream) throws IOException {
InetAddress address = InetAddress.getByName(IP_ADDRESS); // IP-adres van de ontvanger hier zetten
DatagramPacket packet = new DatagramPacket(stream, stream.length, address, 9000);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packet);
}
public static void receivePacket() throws IOException {
Thread thread = new Thread() {
public void run() {
i++;
System.out.println("Receiving packet..");
byte[] buffer2 = new byte[10];
try {
DatagramPacket packet = new DatagramPacket(buffer2, buffer2.length);
datagramSocket.receive(packet);
buffer2 = packet.getData();
if (buffer2 != null) {
System.out.println("UDP Packet " + i + ": " + bytArrayToHex(buffer2));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
// Generate data is een functie om een custom ID en een integer value om te zetten naar bytes. Heb je niet echt nodig maar hebben het in het project laten staan.
public static byte[] generateData(int id, int value) {
byte[] array1 = new byte[10];
array1[0] = (byte) id;
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.nativeOrder());
b.putInt(value);
for (int i = 0; i < 8; i++) {
array1[i + 2] = b.array()[7 - i];
}
return array1;
}
}
| FezzFest/FastradaTI | Mock Data/src/main/java/RunFromFile.java | 955 | // IP-adres van de ontvanger hier zetten | line_comment | nl | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class RunFromFile {
private static final String IP_ADDRESS = "192.168.43.1";
private static BufferedReader br;
private static DatagramSocket datagramSocket;
private static int i = 0;
public static void main(String[] args) throws InterruptedException, IOException {
initFile();
byte[] tempBytes;
datagramSocket = new DatagramSocket(9000);
tempBytes = getLine();
while (tempBytes != null) {
System.out.println("Sending Packet..");
System.out.println();
sendPacket(tempBytes);
//receivePacket();
Thread.sleep(100);
tempBytes = getLine();
}
}
public static void initFile() throws FileNotFoundException {
br = new BufferedReader(new FileReader("engine_data.txt"));
}
public static byte[] getLine() throws IOException {
String line;
if ((line = br.readLine()) != null) {
byte[] bytearray = new byte[10];
for (int i = 0; i < 20; i += 2) {
byte byte1 = (byte) (Integer.parseInt(line.substring(i, i + 2), 16) & 0xff);
bytearray[i / 2] = byte1;
}
return bytearray;
} else {
br.close();
return null;
}
}
public static String bytArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder();
for (byte b : a)
sb.append(String.format("%02x ", b & 0xff));
return sb.toString();
}
public static void sendPacket(byte[] stream) throws IOException {
InetAddress address = InetAddress.getByName(IP_ADDRESS); // IP-adres van<SUF>
DatagramPacket packet = new DatagramPacket(stream, stream.length, address, 9000);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packet);
}
public static void receivePacket() throws IOException {
Thread thread = new Thread() {
public void run() {
i++;
System.out.println("Receiving packet..");
byte[] buffer2 = new byte[10];
try {
DatagramPacket packet = new DatagramPacket(buffer2, buffer2.length);
datagramSocket.receive(packet);
buffer2 = packet.getData();
if (buffer2 != null) {
System.out.println("UDP Packet " + i + ": " + bytArrayToHex(buffer2));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
// Generate data is een functie om een custom ID en een integer value om te zetten naar bytes. Heb je niet echt nodig maar hebben het in het project laten staan.
public static byte[] generateData(int id, int value) {
byte[] array1 = new byte[10];
array1[0] = (byte) id;
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.nativeOrder());
b.putInt(value);
for (int i = 0; i < 8; i++) {
array1[i + 2] = b.array()[7 - i];
}
return array1;
}
}
|
60918_10 | package cz.fidentis.featurepoints.texture;
import cz.fidentis.featurepoints.FacialPoint;
import cz.fidentis.featurepoints.FacialPointType;
import cz.fidentis.featurepoints.FpModel;
import cz.fidentis.model.Model;
import java.util.ArrayList;
import java.util.List;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3f;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
/**
*
* @author Galvanizze
*/
public class ImageAnalyzer {
private static final int EYE_WIDTH = 180;
private static final int EYE_HEIGHT = 60;
private static final int NOSE_WIDTH = 100;
private static final int NOSE_HEIGHT = 100;
private double resizeRatio;
private HaarCascade haarDetector;
private final Mat originalImage;
private Mat workingImage;
private Mat pupilaHoughCircles;
private final ImageViewer imageViewer;
private TextureMapper textureMapper;
private FpModel objFPmodel;
private List<TextureFP> textureFPs;
// Len pomocne premenne pre body, su aj v zozname listov
private TextureFP pupilaLFP;
private TextureFP pupilaRFP;
private Rect leftEye;
private Rect rightEye;
private Rect nose;
private Rect mouth;
private boolean doRotation;
public ImageAnalyzer(Model model) {
// zaujimava je len prva textura
this(model.getMatrials().getMatrials().get(0).getTextureFile());
this.textureMapper = new TextureMapper(model);
}
public ImageAnalyzer(String filePath) {
// this(Imgcodecs.imread(filePath, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE));
this(Imgcodecs.imread(filePath));
}
public ImageAnalyzer(Mat image) {
this.originalImage = image;
this.workingImage = new Mat();
this.originalImage.copyTo(workingImage);
this.imageViewer = new ImageViewer();
this.pupilaHoughCircles = new Mat();
this.textureFPs = new ArrayList<>();
this.doRotation = true;
}
public Mat analyze() throws NullPointerException {
// pokracovat iba ak je obrazok validny
if (!isValid()) {
return null;
}
// Zmensenie snimky na defaultnu velkost - pracujeme s kopiou
// original ostava nezmeneny
// Pre potreby prepoctu bodov na povodny obrazok si musime ponechat
// aj pomer zmeny velkosti obrazka
resizeRatio = OCVutils.resize(workingImage);
// Textury su otocene o 90° doprava, preto je potrebne otocit ich naspat
if (doRotation) {
OCVutils.rotate_90n(workingImage, -90);
}
// Detekcia bodov Pupila na oboch ociach
findHoughCircles();
// Vytvorenie Haar detectora
haarDetector = new HaarCascade(workingImage);
// Segmentacia regionov pomocou Haar detektorov
// leftEye = haarDetector.detectLeftEye();
// rightEye = haarDetector.detectRightEye();
// // haarDetector.detectEyes();
nose = haarDetector.detectNose();
mouth = haarDetector.detectMouth();
// Detekcia bodov
pointsDetection();
// Vykreslenie vsetkych objektov
drawObjects(workingImage);
return workingImage;
}
public void pointsDetection() {
// Vytvorenie kopie na spracovanie
Mat imageTmp = new Mat();
workingImage.copyTo(imageTmp);
// Uprava obrazka
Imgproc.cvtColor(imageTmp, imageTmp, Imgproc.COLOR_BGR2GRAY);
OCVutils.bilateralFilter(imageTmp);
OCVutils.laplacian(imageTmp, 5); // parameter - aperture
OCVutils.threshold(imageTmp, 220); // parameter - threshold
OCVutils.open(imageTmp, 1, Imgproc.CV_SHAPE_ELLIPSE);
// Spracovanie oci
// Body na ociach
// if (leftEye != null)
// Namiesto regiona detekovaneho Haar detektorom pouzivame region
// urceny podla stredu oka
Rect leftEyeRegion = new Rect((int) pupilaLFP.x - (EYE_WIDTH / 2), (int) pupilaLFP.y - (EYE_HEIGHT / 2), EYE_WIDTH, EYE_HEIGHT);
Point exL = getLeftPoint(imageTmp, leftEyeRegion);
Point enL = getRightPoint(imageTmp, leftEyeRegion);
textureFPs.add(new TextureFP(FacialPointType.EX_L, exL));
textureFPs.add(new TextureFP(FacialPointType.EN_L, enL));
// if (rightEye != null) {
Rect rightEyeRegion = new Rect((int) pupilaRFP.x - (EYE_WIDTH / 2), (int) pupilaRFP.y - (EYE_HEIGHT / 2), EYE_WIDTH, EYE_HEIGHT);
Point enR = getLeftPoint(imageTmp, rightEyeRegion);
Point exR = getRightPoint(imageTmp, rightEyeRegion);
textureFPs.add(new TextureFP(FacialPointType.EN_R, enR));
textureFPs.add(new TextureFP(FacialPointType.EX_R, exR));
// Region nosa
// Pouzitie modelu docasne zakomentovane
// Point pronasaleFP = getTextureFPfromModel(FacialPointType.PRN);
// if (pronasaleFP != null) {
// Rect noseRegion = new Rect((int) pronasaleFP.x - (NOSE_WIDTH / 2), (int) pronasaleFP.y - (NOSE_HEIGHT / 2), NOSE_WIDTH, NOSE_HEIGHT);
// Body na nose
nose = haarDetector.detectNose();
if (nose != null) {
Point alL = getLeftPoint(imageTmp, nose);
Point alR = getRightPoint(imageTmp, nose);
// textureFPs.add(new TextureFP(FacialPointType.AL_L, alL));
// textureFPs.add(new TextureFP(FacialPointType.AL_R, alR));
// Body musia byt symetricke, preto y suradnicu vypocitat ako priemer bodov
double y = (alL.y + alR.y) / 2;
textureFPs.add(new TextureFP(FacialPointType.AL_L, new Point(alL.x, y)));
textureFPs.add(new TextureFP(FacialPointType.AL_R, new Point(alR.x, y)));
}
// OCVutils.drawRectangle(workingImage, nose, OCVutils.BLUE);
// Kontrolone vykreslenie regionov
OCVutils.drawRectangle(workingImage, leftEyeRegion, OCVutils.GREEN);
OCVutils.drawRectangle(workingImage, rightEyeRegion, OCVutils.GREEN);
// // Pomocne zobrazenie upraveneho - binarneho! obrazku
// imageViewer.show(imageTmp, "Thresholded image");
}
private void findHoughCircles() {
Mat imageGray = new Mat();
Mat houghCircles = new Mat();
// Imgproc.Canny(originalImage, imageGray, 10, 50, aperture, false);
Imgproc.cvtColor(workingImage, imageGray, Imgproc.COLOR_BGR2GRAY);
Imgproc.blur(imageGray, imageGray, new Size(3, 3));
int lowThreshold = 20;
while (houghCircles.cols() < 3 && lowThreshold > 0) {
houghCircles = new Mat();
Imgproc.HoughCircles(imageGray, houghCircles, Imgproc.CV_HOUGH_GRADIENT, 1, imageGray.rows() / 8, 200, lowThreshold, 10, 50);
lowThreshold--;
}
// Body musia byt presne dva, ak nebudu, tak vybrat take, ktore su
// najviac v strede oka a ktore maju najmensi rozptyl od seba
// a zaroven sa nachadzaju v hornej casti tvare
double minDistance = Double.POSITIVE_INFINITY;
Point pupilaL = new Point();
Point pupilaR = new Point();
int p1index = -1;
int p2index = -1;
for (int i = 0; i < houghCircles.cols() - 1; i++) {
Point p1 = new Point(houghCircles.get(0, i)[0], houghCircles.get(0, i)[1]);
// if (pupila1.y > (workingImage.height() / 2)) {
for (int j = i + 1; j < houghCircles.cols(); j++) {
Point p2 = new Point(houghCircles.get(0, j)[0], houghCircles.get(0, j)[1]);
// if (pupila2.y > (workingImage.height() / 2)) {
double pupilasDistance = Math.abs(p1.y - p2.y);
if (pupilasDistance < minDistance) {
minDistance = pupilasDistance;
pupilaL = p1.x < p2.x ? p2 : p1;
pupilaR = p1.x < p2.x ? p1 : p2;
p1index = i;
p2index = j;
}
// }
// }
}
}
pupilaHoughCircles = new Mat(1, 2, CvType.CV_32FC3);
pupilaHoughCircles.put(0, 0, houghCircles.get(0, p1index));
pupilaHoughCircles.put(0, 1, houghCircles.get(0, p2index));
// // Ulozit este rozpoznane kruznice, len kvoli vizualizacii
// for (int i = 0; i < houghCircles.cols(); i++) {
// if (i != p1index && i != p2index) {
// Mat col = houghCircles.col(i);
// }
// }
// houghCircles.copyTo(pupilaHoughCircles);
// assert circles.cols() == 2;
// Point p1 = new Point(pupilaHoughCircles.get(0, 0)[0], pupilaHoughCircles.get(0, 0)[1]);
// Point p2 = new Point(pupilaHoughCircles.get(0, 1)[0], pupilaHoughCircles.get(0, 1)[1]);
// // Vytvorit andtropometricke body pupila, podla umiestnenia
// if (p1.x < p2.x) {
// pupilaRFP = new TextureFP(FacialPointType.P_R, p1);
// pupilaLFP = new TextureFP(FacialPointType.P_L, p2);
// } else {
// pupilaRFP = new TextureFP(FacialPointType.P_R, p2);
// pupilaLFP = new TextureFP(FacialPointType.P_L, p1);
// }
pupilaLFP = new TextureFP(FacialPointType.P_L, pupilaL);
textureFPs.add(pupilaLFP);
pupilaRFP = new TextureFP(FacialPointType.P_R, pupilaR);
textureFPs.add(pupilaRFP);
}
private boolean isValid() {
if (workingImage.dataAddr() == 0) {
System.out.println("Couldn't open image file.");
}
return workingImage.dataAddr() != 0;
}
private static Point getRightPoint(Mat image, Rect rect) {
for (int i = rect.x; i < rect.x + rect.width; i++) {
for (int j = rect.y; j < rect.y + rect.height; j++) {
double[] point = image.get(j, i);
// System.out.println("point " + i + ", " + j + " = " + point[0]);
if (point[0] == 255) {
// OCVutils.drawCircle(image, p, new Scalar(255, 255, 255));
return new Point(i, j);
}
}
}
return null;
}
private static Point getLeftPoint(Mat image, Rect rect) {
for (int i = rect.x + rect.width; i > rect.x; i--) {
for (int j = rect.y; j < rect.y + rect.height; j++) {
double[] point = image.get(j, i);
if (point[0] == 255) {
// OCVutils.drawCircle(image, new Point(i, j), new Scalar(255, 255, 255));
return new Point(i, j);
}
}
}
return null;
}
public void setObjFPmodel(FpModel fpModel) {
this.objFPmodel = fpModel;
}
private Point getTextureFPfromModel(FacialPointType type) {
if (objFPmodel == null) {
return null;
}
FacialPoint fp = objFPmodel.getFacialPoint(type);
Point imagePoint = textureMapper.getImagePoint(new Point3d(fp.getCoords()));
imagePoint.x *= originalImage.height();
imagePoint.y = imagePoint.y;
imagePoint.y *= originalImage.width();
imagePoint.x *= resizeRatio;
imagePoint.y *= resizeRatio;
Point rotatedPoint = rotatePoint(imagePoint, 90, workingImage);
OCVutils.drawPoint(workingImage, rotatedPoint, OCVutils.GREEN);
return imagePoint;
}
private void drawTextureFPs(Mat image) {
for (TextureFP fp : textureFPs) {
OCVutils.drawPoint(image, fp.getPoint(), OCVutils.RED);
}
}
private void drawHoughCircles(Mat image) {
for (int i = 0; i < pupilaHoughCircles.cols(); i++) {
Point center = new Point(pupilaHoughCircles.get(0, i)[0], pupilaHoughCircles.get(0, i)[1]);
int radius = (int) Math.round(pupilaHoughCircles.get(0, i)[2]);
OCVutils.drawCircle(image, center, OCVutils.BLUE, radius, 3);
}
}
public void drawObjects(Mat image) {
// drawTextureFPs(image);
// drawHoughCircles(image);
// OCVutils.drawRectangle(image, leftEye, OCVutils.GREEN);
// OCVutils.drawRectangle(image, rightEye, OCVutils.GREEN);
OCVutils.drawRectangle(image, nose, OCVutils.GREEN);
OCVutils.drawRectangle(image, mouth, OCVutils.GREEN);
}
public void showWorkingImage() {
showImage(workingImage);
}
public void showImage(Mat image) {
imageViewer.show(image, "Texture image");
}
public List<FacialPoint> get3DfacialPoints() {
assert textureMapper != null;
List<FacialPoint> facialPoints = new ArrayList<>();
rotateAndResizeFPs();
for (TextureFP textureFP : textureFPs) {
Vector3f modelVert = textureMapper.getModelVertFromTextureCoord(textureFP.getPoint(), originalImage);
facialPoints.add(new FacialPoint(textureFP.getType(), modelVert));
}
return facialPoints;
}
private void rotateAndResizeFPs() {
for (TextureFP textureFP : textureFPs) {
textureFP.x /= resizeRatio;
textureFP.y /= resizeRatio;
textureFP.setPoint(rotatePoint(textureFP.getPoint(), -90, originalImage));
}
}
public FpModel get3DfpModel() {
assert textureMapper != null;
FpModel fpModel = new FpModel();
fpModel.setFacialpoints(get3DfacialPoints());
return fpModel;
}
// public void setTextureMapper(TextureMapper textureMapper) {
// this.textureMapper = textureMapper;
// }
public boolean isDoRotation() {
return doRotation;
}
public void setDoRotation(boolean doRotation) {
this.doRotation = doRotation;
}
private Point rotatePoint(Point p, double angle, Mat image) {
double theta = Math.toRadians(angle);
Point o = new Point(image.height() / 2, image.width() / 2);
double x = Math.cos(theta) * (p.x - o.x) + Math.sin(theta) * (p.y - o.y) + o.y;
double y = Math.sin(theta) * -(p.x - o.x) + Math.cos(theta) * (p.y - o.y) + o.x;
return new Point(x, y);
}
}
| Fidentis/Analyst | FeaturePoints/src/cz/fidentis/featurepoints/texture/ImageAnalyzer.java | 4,922 | // Vytvorenie Haar detectora | line_comment | nl | package cz.fidentis.featurepoints.texture;
import cz.fidentis.featurepoints.FacialPoint;
import cz.fidentis.featurepoints.FacialPointType;
import cz.fidentis.featurepoints.FpModel;
import cz.fidentis.model.Model;
import java.util.ArrayList;
import java.util.List;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3f;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
/**
*
* @author Galvanizze
*/
public class ImageAnalyzer {
private static final int EYE_WIDTH = 180;
private static final int EYE_HEIGHT = 60;
private static final int NOSE_WIDTH = 100;
private static final int NOSE_HEIGHT = 100;
private double resizeRatio;
private HaarCascade haarDetector;
private final Mat originalImage;
private Mat workingImage;
private Mat pupilaHoughCircles;
private final ImageViewer imageViewer;
private TextureMapper textureMapper;
private FpModel objFPmodel;
private List<TextureFP> textureFPs;
// Len pomocne premenne pre body, su aj v zozname listov
private TextureFP pupilaLFP;
private TextureFP pupilaRFP;
private Rect leftEye;
private Rect rightEye;
private Rect nose;
private Rect mouth;
private boolean doRotation;
public ImageAnalyzer(Model model) {
// zaujimava je len prva textura
this(model.getMatrials().getMatrials().get(0).getTextureFile());
this.textureMapper = new TextureMapper(model);
}
public ImageAnalyzer(String filePath) {
// this(Imgcodecs.imread(filePath, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE));
this(Imgcodecs.imread(filePath));
}
public ImageAnalyzer(Mat image) {
this.originalImage = image;
this.workingImage = new Mat();
this.originalImage.copyTo(workingImage);
this.imageViewer = new ImageViewer();
this.pupilaHoughCircles = new Mat();
this.textureFPs = new ArrayList<>();
this.doRotation = true;
}
public Mat analyze() throws NullPointerException {
// pokracovat iba ak je obrazok validny
if (!isValid()) {
return null;
}
// Zmensenie snimky na defaultnu velkost - pracujeme s kopiou
// original ostava nezmeneny
// Pre potreby prepoctu bodov na povodny obrazok si musime ponechat
// aj pomer zmeny velkosti obrazka
resizeRatio = OCVutils.resize(workingImage);
// Textury su otocene o 90° doprava, preto je potrebne otocit ich naspat
if (doRotation) {
OCVutils.rotate_90n(workingImage, -90);
}
// Detekcia bodov Pupila na oboch ociach
findHoughCircles();
// Vytvorenie Haar<SUF>
haarDetector = new HaarCascade(workingImage);
// Segmentacia regionov pomocou Haar detektorov
// leftEye = haarDetector.detectLeftEye();
// rightEye = haarDetector.detectRightEye();
// // haarDetector.detectEyes();
nose = haarDetector.detectNose();
mouth = haarDetector.detectMouth();
// Detekcia bodov
pointsDetection();
// Vykreslenie vsetkych objektov
drawObjects(workingImage);
return workingImage;
}
public void pointsDetection() {
// Vytvorenie kopie na spracovanie
Mat imageTmp = new Mat();
workingImage.copyTo(imageTmp);
// Uprava obrazka
Imgproc.cvtColor(imageTmp, imageTmp, Imgproc.COLOR_BGR2GRAY);
OCVutils.bilateralFilter(imageTmp);
OCVutils.laplacian(imageTmp, 5); // parameter - aperture
OCVutils.threshold(imageTmp, 220); // parameter - threshold
OCVutils.open(imageTmp, 1, Imgproc.CV_SHAPE_ELLIPSE);
// Spracovanie oci
// Body na ociach
// if (leftEye != null)
// Namiesto regiona detekovaneho Haar detektorom pouzivame region
// urceny podla stredu oka
Rect leftEyeRegion = new Rect((int) pupilaLFP.x - (EYE_WIDTH / 2), (int) pupilaLFP.y - (EYE_HEIGHT / 2), EYE_WIDTH, EYE_HEIGHT);
Point exL = getLeftPoint(imageTmp, leftEyeRegion);
Point enL = getRightPoint(imageTmp, leftEyeRegion);
textureFPs.add(new TextureFP(FacialPointType.EX_L, exL));
textureFPs.add(new TextureFP(FacialPointType.EN_L, enL));
// if (rightEye != null) {
Rect rightEyeRegion = new Rect((int) pupilaRFP.x - (EYE_WIDTH / 2), (int) pupilaRFP.y - (EYE_HEIGHT / 2), EYE_WIDTH, EYE_HEIGHT);
Point enR = getLeftPoint(imageTmp, rightEyeRegion);
Point exR = getRightPoint(imageTmp, rightEyeRegion);
textureFPs.add(new TextureFP(FacialPointType.EN_R, enR));
textureFPs.add(new TextureFP(FacialPointType.EX_R, exR));
// Region nosa
// Pouzitie modelu docasne zakomentovane
// Point pronasaleFP = getTextureFPfromModel(FacialPointType.PRN);
// if (pronasaleFP != null) {
// Rect noseRegion = new Rect((int) pronasaleFP.x - (NOSE_WIDTH / 2), (int) pronasaleFP.y - (NOSE_HEIGHT / 2), NOSE_WIDTH, NOSE_HEIGHT);
// Body na nose
nose = haarDetector.detectNose();
if (nose != null) {
Point alL = getLeftPoint(imageTmp, nose);
Point alR = getRightPoint(imageTmp, nose);
// textureFPs.add(new TextureFP(FacialPointType.AL_L, alL));
// textureFPs.add(new TextureFP(FacialPointType.AL_R, alR));
// Body musia byt symetricke, preto y suradnicu vypocitat ako priemer bodov
double y = (alL.y + alR.y) / 2;
textureFPs.add(new TextureFP(FacialPointType.AL_L, new Point(alL.x, y)));
textureFPs.add(new TextureFP(FacialPointType.AL_R, new Point(alR.x, y)));
}
// OCVutils.drawRectangle(workingImage, nose, OCVutils.BLUE);
// Kontrolone vykreslenie regionov
OCVutils.drawRectangle(workingImage, leftEyeRegion, OCVutils.GREEN);
OCVutils.drawRectangle(workingImage, rightEyeRegion, OCVutils.GREEN);
// // Pomocne zobrazenie upraveneho - binarneho! obrazku
// imageViewer.show(imageTmp, "Thresholded image");
}
private void findHoughCircles() {
Mat imageGray = new Mat();
Mat houghCircles = new Mat();
// Imgproc.Canny(originalImage, imageGray, 10, 50, aperture, false);
Imgproc.cvtColor(workingImage, imageGray, Imgproc.COLOR_BGR2GRAY);
Imgproc.blur(imageGray, imageGray, new Size(3, 3));
int lowThreshold = 20;
while (houghCircles.cols() < 3 && lowThreshold > 0) {
houghCircles = new Mat();
Imgproc.HoughCircles(imageGray, houghCircles, Imgproc.CV_HOUGH_GRADIENT, 1, imageGray.rows() / 8, 200, lowThreshold, 10, 50);
lowThreshold--;
}
// Body musia byt presne dva, ak nebudu, tak vybrat take, ktore su
// najviac v strede oka a ktore maju najmensi rozptyl od seba
// a zaroven sa nachadzaju v hornej casti tvare
double minDistance = Double.POSITIVE_INFINITY;
Point pupilaL = new Point();
Point pupilaR = new Point();
int p1index = -1;
int p2index = -1;
for (int i = 0; i < houghCircles.cols() - 1; i++) {
Point p1 = new Point(houghCircles.get(0, i)[0], houghCircles.get(0, i)[1]);
// if (pupila1.y > (workingImage.height() / 2)) {
for (int j = i + 1; j < houghCircles.cols(); j++) {
Point p2 = new Point(houghCircles.get(0, j)[0], houghCircles.get(0, j)[1]);
// if (pupila2.y > (workingImage.height() / 2)) {
double pupilasDistance = Math.abs(p1.y - p2.y);
if (pupilasDistance < minDistance) {
minDistance = pupilasDistance;
pupilaL = p1.x < p2.x ? p2 : p1;
pupilaR = p1.x < p2.x ? p1 : p2;
p1index = i;
p2index = j;
}
// }
// }
}
}
pupilaHoughCircles = new Mat(1, 2, CvType.CV_32FC3);
pupilaHoughCircles.put(0, 0, houghCircles.get(0, p1index));
pupilaHoughCircles.put(0, 1, houghCircles.get(0, p2index));
// // Ulozit este rozpoznane kruznice, len kvoli vizualizacii
// for (int i = 0; i < houghCircles.cols(); i++) {
// if (i != p1index && i != p2index) {
// Mat col = houghCircles.col(i);
// }
// }
// houghCircles.copyTo(pupilaHoughCircles);
// assert circles.cols() == 2;
// Point p1 = new Point(pupilaHoughCircles.get(0, 0)[0], pupilaHoughCircles.get(0, 0)[1]);
// Point p2 = new Point(pupilaHoughCircles.get(0, 1)[0], pupilaHoughCircles.get(0, 1)[1]);
// // Vytvorit andtropometricke body pupila, podla umiestnenia
// if (p1.x < p2.x) {
// pupilaRFP = new TextureFP(FacialPointType.P_R, p1);
// pupilaLFP = new TextureFP(FacialPointType.P_L, p2);
// } else {
// pupilaRFP = new TextureFP(FacialPointType.P_R, p2);
// pupilaLFP = new TextureFP(FacialPointType.P_L, p1);
// }
pupilaLFP = new TextureFP(FacialPointType.P_L, pupilaL);
textureFPs.add(pupilaLFP);
pupilaRFP = new TextureFP(FacialPointType.P_R, pupilaR);
textureFPs.add(pupilaRFP);
}
private boolean isValid() {
if (workingImage.dataAddr() == 0) {
System.out.println("Couldn't open image file.");
}
return workingImage.dataAddr() != 0;
}
private static Point getRightPoint(Mat image, Rect rect) {
for (int i = rect.x; i < rect.x + rect.width; i++) {
for (int j = rect.y; j < rect.y + rect.height; j++) {
double[] point = image.get(j, i);
// System.out.println("point " + i + ", " + j + " = " + point[0]);
if (point[0] == 255) {
// OCVutils.drawCircle(image, p, new Scalar(255, 255, 255));
return new Point(i, j);
}
}
}
return null;
}
private static Point getLeftPoint(Mat image, Rect rect) {
for (int i = rect.x + rect.width; i > rect.x; i--) {
for (int j = rect.y; j < rect.y + rect.height; j++) {
double[] point = image.get(j, i);
if (point[0] == 255) {
// OCVutils.drawCircle(image, new Point(i, j), new Scalar(255, 255, 255));
return new Point(i, j);
}
}
}
return null;
}
public void setObjFPmodel(FpModel fpModel) {
this.objFPmodel = fpModel;
}
private Point getTextureFPfromModel(FacialPointType type) {
if (objFPmodel == null) {
return null;
}
FacialPoint fp = objFPmodel.getFacialPoint(type);
Point imagePoint = textureMapper.getImagePoint(new Point3d(fp.getCoords()));
imagePoint.x *= originalImage.height();
imagePoint.y = imagePoint.y;
imagePoint.y *= originalImage.width();
imagePoint.x *= resizeRatio;
imagePoint.y *= resizeRatio;
Point rotatedPoint = rotatePoint(imagePoint, 90, workingImage);
OCVutils.drawPoint(workingImage, rotatedPoint, OCVutils.GREEN);
return imagePoint;
}
private void drawTextureFPs(Mat image) {
for (TextureFP fp : textureFPs) {
OCVutils.drawPoint(image, fp.getPoint(), OCVutils.RED);
}
}
private void drawHoughCircles(Mat image) {
for (int i = 0; i < pupilaHoughCircles.cols(); i++) {
Point center = new Point(pupilaHoughCircles.get(0, i)[0], pupilaHoughCircles.get(0, i)[1]);
int radius = (int) Math.round(pupilaHoughCircles.get(0, i)[2]);
OCVutils.drawCircle(image, center, OCVutils.BLUE, radius, 3);
}
}
public void drawObjects(Mat image) {
// drawTextureFPs(image);
// drawHoughCircles(image);
// OCVutils.drawRectangle(image, leftEye, OCVutils.GREEN);
// OCVutils.drawRectangle(image, rightEye, OCVutils.GREEN);
OCVutils.drawRectangle(image, nose, OCVutils.GREEN);
OCVutils.drawRectangle(image, mouth, OCVutils.GREEN);
}
public void showWorkingImage() {
showImage(workingImage);
}
public void showImage(Mat image) {
imageViewer.show(image, "Texture image");
}
public List<FacialPoint> get3DfacialPoints() {
assert textureMapper != null;
List<FacialPoint> facialPoints = new ArrayList<>();
rotateAndResizeFPs();
for (TextureFP textureFP : textureFPs) {
Vector3f modelVert = textureMapper.getModelVertFromTextureCoord(textureFP.getPoint(), originalImage);
facialPoints.add(new FacialPoint(textureFP.getType(), modelVert));
}
return facialPoints;
}
private void rotateAndResizeFPs() {
for (TextureFP textureFP : textureFPs) {
textureFP.x /= resizeRatio;
textureFP.y /= resizeRatio;
textureFP.setPoint(rotatePoint(textureFP.getPoint(), -90, originalImage));
}
}
public FpModel get3DfpModel() {
assert textureMapper != null;
FpModel fpModel = new FpModel();
fpModel.setFacialpoints(get3DfacialPoints());
return fpModel;
}
// public void setTextureMapper(TextureMapper textureMapper) {
// this.textureMapper = textureMapper;
// }
public boolean isDoRotation() {
return doRotation;
}
public void setDoRotation(boolean doRotation) {
this.doRotation = doRotation;
}
private Point rotatePoint(Point p, double angle, Mat image) {
double theta = Math.toRadians(angle);
Point o = new Point(image.height() / 2, image.width() / 2);
double x = Math.cos(theta) * (p.x - o.x) + Math.sin(theta) * (p.y - o.y) + o.y;
double y = Math.sin(theta) * -(p.x - o.x) + Math.cos(theta) * (p.y - o.y) + o.x;
return new Point(x, y);
}
}
|
173925_2 | package com.vogella.android.multitouch;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
public class MultitouchView extends View {
private static final int SIZE = 60;
private SparseArray<PointF> mActivePointers;
private Paint mPaint;
private int[] colors = { Color.BLUE, Color.GREEN, Color.MAGENTA,
Color.BLACK, Color.CYAN, Color.GRAY, Color.RED, Color.DKGRAY,
Color.LTGRAY, Color.YELLOW };
private Paint textPaint;
public MultitouchView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private void initView() {
mActivePointers = new SparseArray<PointF>();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// set painter color to a color you like
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setTextSize(20);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID
int pointerId = event.getPointerId(pointerIndex);
// get masked (not specific to a pointer) action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
// We have a new pointer. Lets add it to the list of pointers
PointF f = new PointF();
f.x = event.getX(pointerIndex);
f.y = event.getY(pointerIndex);
mActivePointers.put(pointerId, f);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
for (int size = event.getPointerCount(), i = 0; i < size; i++) {
PointF point = mActivePointers.get(event.getPointerId(i));
if (point != null) {
point.x = event.getX(i);
point.y = event.getY(i);
}
}
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL: {
mActivePointers.remove(pointerId);
break;
}
}
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw all pointers
for (int size = mActivePointers.size(), i = 0; i < size; i++) {
PointF point = mActivePointers.valueAt(i);
if (point != null)
mPaint.setColor(colors[i % 9]);
canvas.drawCircle(point.x, point.y, SIZE, mPaint);
}
canvas.drawText("Total pointers: " + mActivePointers.size(), 10, 40 , textPaint);
}
}
| FinHead/codeexamples-android | com.vogella.android.multitouch/src/com/vogella/android/multitouch/MultitouchView.java | 953 | // get pointer ID | line_comment | nl | package com.vogella.android.multitouch;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
public class MultitouchView extends View {
private static final int SIZE = 60;
private SparseArray<PointF> mActivePointers;
private Paint mPaint;
private int[] colors = { Color.BLUE, Color.GREEN, Color.MAGENTA,
Color.BLACK, Color.CYAN, Color.GRAY, Color.RED, Color.DKGRAY,
Color.LTGRAY, Color.YELLOW };
private Paint textPaint;
public MultitouchView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private void initView() {
mActivePointers = new SparseArray<PointF>();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// set painter color to a color you like
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setTextSize(20);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer<SUF>
int pointerId = event.getPointerId(pointerIndex);
// get masked (not specific to a pointer) action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
// We have a new pointer. Lets add it to the list of pointers
PointF f = new PointF();
f.x = event.getX(pointerIndex);
f.y = event.getY(pointerIndex);
mActivePointers.put(pointerId, f);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
for (int size = event.getPointerCount(), i = 0; i < size; i++) {
PointF point = mActivePointers.get(event.getPointerId(i));
if (point != null) {
point.x = event.getX(i);
point.y = event.getY(i);
}
}
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL: {
mActivePointers.remove(pointerId);
break;
}
}
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw all pointers
for (int size = mActivePointers.size(), i = 0; i < size; i++) {
PointF point = mActivePointers.valueAt(i);
if (point != null)
mPaint.setColor(colors[i % 9]);
canvas.drawCircle(point.x, point.y, SIZE, mPaint);
}
canvas.drawText("Total pointers: " + mActivePointers.size(), 10, 40 , textPaint);
}
}
|
31953_3 | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RouteplannerImpl extends Network {
// Bekeken nodes in het berekenalgoritme
private Set<Node> settledNodes;
// Onbekeken nodes in het berekenalgoritme
private Set<Node> unSettledNodes;
// Deze variable slaat voor iedere node de voorlaatste node in het pad vanaf het beginpunt op
private Map<Node, Node> predecessors;
// Deze variable heeft van iedere node de afstand vanaf het opgegeven beginpunt
private Map<Node, Integer> distance;
public void execute(Node source) {
settledNodes = new HashSet<Node>();
unSettledNodes = new HashSet<Node>();
distance = new HashMap<Node, Integer>();
predecessors = new HashMap<Node, Node>();
distance.put(source, 0);
unSettledNodes.add(source);
while (unSettledNodes.size() > 0) {
Node node = getMinimum(unSettledNodes);
settledNodes.add(node);
unSettledNodes.remove(node);
findMinimalDistances(node);
}
}
private void findMinimalDistances(Node node) {
List<Node> adjacentNodes = getNeighbors(node);
for (Node target : adjacentNodes) {
//
// Implementeer algoritme. Vergeet niet afstanden in de distance-variable
// te zetten, en ook het predecessors-pad te vullen.
//
}
}
private int getDistanceBetweenNeighbors(Node node, Node target) {
for (Link link : getLinks()) {
//
// Bereken hier de afstand tussen 2 buren
//
}
throw new RuntimeException("Should not happen");
}
private List<Node> getNeighbors(Node node) {
List<Node> neighbors = new ArrayList<Node>();
for (Link link : getLinks()) {
//
// Haal hier de buren op die nog niet berekend zijn.
//
}
return neighbors;
}
private Node getMinimum(Set<Node> nodes) {
Node minimum = null;
for (Node node : nodes) {
if (minimum == null) {
minimum = node;
} else {
if (getShortestDistance(node) < getShortestDistance(minimum)) {
minimum = node;
}
}
}
return minimum;
}
private boolean isSettled(Node node) {
return settledNodes.contains(node);
}
public int getShortestDistance(Node destination) {
Integer d = distance.get(destination);
if (d == null) {
return Integer.MAX_VALUE;
} else {
return d;
}
}
/*
* Deze methode geeft het pad terug van het begin naar het opgegeven eindpunt (destination).
* Als er geen pad is geeft deze NULL terug.
*/
public LinkedList<Node> getPath(Node destination) {
LinkedList<Node> path = new LinkedList<Node>();
Node step = destination;
// check if a path exists
if (predecessors.get(step) == null) {
return null;
}
path.add(step);
while (predecessors.get(step) != null) {
step = predecessors.get(step);
path.add(step);
}
// We hebben nu het pad van het eindpunt naar het beginpunt. Dus nog even omdraaien
Collections.reverse(path);
return path;
}
}
| First8/mastersofjava | not converted/2014/NLJUG-Masters-of-Java/6_Routeplanner/RouteplannerCase/RouteplannerImpl.java | 1,001 | // Deze variable heeft van iedere node de afstand vanaf het opgegeven beginpunt | line_comment | nl | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RouteplannerImpl extends Network {
// Bekeken nodes in het berekenalgoritme
private Set<Node> settledNodes;
// Onbekeken nodes in het berekenalgoritme
private Set<Node> unSettledNodes;
// Deze variable slaat voor iedere node de voorlaatste node in het pad vanaf het beginpunt op
private Map<Node, Node> predecessors;
// Deze variable<SUF>
private Map<Node, Integer> distance;
public void execute(Node source) {
settledNodes = new HashSet<Node>();
unSettledNodes = new HashSet<Node>();
distance = new HashMap<Node, Integer>();
predecessors = new HashMap<Node, Node>();
distance.put(source, 0);
unSettledNodes.add(source);
while (unSettledNodes.size() > 0) {
Node node = getMinimum(unSettledNodes);
settledNodes.add(node);
unSettledNodes.remove(node);
findMinimalDistances(node);
}
}
private void findMinimalDistances(Node node) {
List<Node> adjacentNodes = getNeighbors(node);
for (Node target : adjacentNodes) {
//
// Implementeer algoritme. Vergeet niet afstanden in de distance-variable
// te zetten, en ook het predecessors-pad te vullen.
//
}
}
private int getDistanceBetweenNeighbors(Node node, Node target) {
for (Link link : getLinks()) {
//
// Bereken hier de afstand tussen 2 buren
//
}
throw new RuntimeException("Should not happen");
}
private List<Node> getNeighbors(Node node) {
List<Node> neighbors = new ArrayList<Node>();
for (Link link : getLinks()) {
//
// Haal hier de buren op die nog niet berekend zijn.
//
}
return neighbors;
}
private Node getMinimum(Set<Node> nodes) {
Node minimum = null;
for (Node node : nodes) {
if (minimum == null) {
minimum = node;
} else {
if (getShortestDistance(node) < getShortestDistance(minimum)) {
minimum = node;
}
}
}
return minimum;
}
private boolean isSettled(Node node) {
return settledNodes.contains(node);
}
public int getShortestDistance(Node destination) {
Integer d = distance.get(destination);
if (d == null) {
return Integer.MAX_VALUE;
} else {
return d;
}
}
/*
* Deze methode geeft het pad terug van het begin naar het opgegeven eindpunt (destination).
* Als er geen pad is geeft deze NULL terug.
*/
public LinkedList<Node> getPath(Node destination) {
LinkedList<Node> path = new LinkedList<Node>();
Node step = destination;
// check if a path exists
if (predecessors.get(step) == null) {
return null;
}
path.add(step);
while (predecessors.get(step) != null) {
step = predecessors.get(step);
path.add(step);
}
// We hebben nu het pad van het eindpunt naar het beginpunt. Dus nog even omdraaien
Collections.reverse(path);
return path;
}
}
|
82640_41 | /* ===========================================================
* GTNA : Graph-Theoretic Network Analyzer
* ===========================================================
*
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/
*
* GTNA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GTNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* ---------------------------------------
* SixTollis.java
* ---------------------------------------
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Original Author: Nico;
* Contributors: -;
*
* Changes since 2011-05-17
* ---------------------------------------
*
*/
package gtna.transformation.gd;
import gtna.drawing.GraphPlotter;
import gtna.graph.Edge;
import gtna.graph.Graph;
import gtna.graph.Node;
import gtna.graph.spanningTree.ParentChild;
import gtna.graph.spanningTree.SpanningTree;
import gtna.id.ring.RingIdentifier;
import gtna.id.ring.RingPartition;
import gtna.metrics.edges.EdgeCrossings;
import gtna.util.parameter.BooleanParameter;
import gtna.util.parameter.DoubleParameter;
import gtna.util.parameter.IntParameter;
import gtna.util.parameter.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
/**
* @author Nico
*
*/
public class SixTollis extends CircularAbstract {
private TreeSet<Node> waveCenterVertices, waveFrontVertices;
private List<Node> vertexList, removedVertices;
private HashMap<String, Edge> removedEdges;
private HashMap<String, Edge>[] additionalEdges;
private Edge[][] edges;
private ParentChild deepestVertex;
private Boolean useOriginalGraphWithoutRemovalList;
private Graph g;
public SixTollis(int realities, double modulus, boolean wrapAround,
GraphPlotter plotter) {
super("GDA_SIX_TOLLIS", new Parameter[] {
new IntParameter("REALITIES", realities),
new DoubleParameter("MODULUS", modulus),
new BooleanParameter("WRAPAROUND", wrapAround) });
this.realities = realities;
this.modulus = modulus;
this.wrapAround = wrapAround;
this.graphPlotter = plotter;
}
public GraphDrawingAbstract clone() {
return new SixTollis(realities, modulus, wrapAround, graphPlotter);
}
@Override
public Graph transform(Graph g) {
useOriginalGraphWithoutRemovalList = false;
initIDSpace(g);
if (graphPlotter != null)
graphPlotter.plotStartGraph(g, idSpace);
EdgeCrossings ec = new EdgeCrossings();
int countCrossings = -1;
// countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace,
// true);
// System.out.println("Crossings randomized: " + countCrossings);
this.g = g;
/*
* Phase 1
*/
edges = new Edge[g.getNodes().length][];
Node tempVertex = null;
Node currentVertex = null;
Node randDst1, randDst2;
Edge tempEdge;
String tempEdgeString;
ArrayList<Node> verticesToAdd;
removedEdges = new HashMap<String, Edge>(g.computeNumberOfEdges());
HashMap<String, Edge> pairEdges = null;
removedVertices = new ArrayList<Node>();
waveCenterVertices = new TreeSet<Node>();
waveFrontVertices = new TreeSet<Node>();
additionalEdges = new HashMap[g.getNodes().length];
for (int i = 0; i < g.getNodes().length; i++) {
additionalEdges[i] = new HashMap<String, Edge>();
}
vertexList = Arrays.asList(g.getNodes().clone());
System.out.println("Done with all init stuff, should run following loop from 1 to " + (vertexList.size() - 3));
for (int counter = 1; counter < (vertexList.size() - 3); counter++) {
currentVertex = getVertex();
if (counter % (vertexList.size() / 10) == 0) {
// System.out.println("Processing " + currentVertex + " with a degree of "
// + getEdges(currentVertex).size() + " (vertex " + counter + " of " + (vertexList.size() - 3)
// + ")");
}
pairEdges = getPairEdges(currentVertex);
for (Edge singleEdge : pairEdges.values()) {
removedEdges.put(getEdgeString(singleEdge), singleEdge);
}
HashMap<String, Edge> currentVertexConnections = getEdges(currentVertex);
int currentVertexDegree = currentVertexConnections.size();
int triangulationEdgesCount = (currentVertexDegree - 1)
- pairEdges.size();
int[] outgoingEdges = filterOutgoingEdges(currentVertex,
currentVertexConnections);
// System.out.print(currentVertex.getIndex() +
// " has a current degree of " + currentVertexDegree + ", "
// + pairEdges.size() + " pair edges and a need for " +
// triangulationEdgesCount
// + " triangulation edges - existing edges:");
// for (Edge sE : currentVertexConnections.values()) {
// System.out.print(" " + sE);
// }
// System.out.println();
int firstCounter = 0;
int secondCounter = 1;
while (triangulationEdgesCount > 0) {
randDst1 = g.getNode(outgoingEdges[firstCounter]);
randDst2 = g.getNode(outgoingEdges[secondCounter]);
if (!randDst1.equals(randDst2)
&& !removedVertices.contains(randDst1)
&& !removedVertices.contains(randDst2)) {
// System.out.println("rand1: " + randDst1.getIndex() +
// "; rand2: " + randDst2.getIndex());
// System.out.print("Outgoing edges for r1:");
// for (int i : filterOutgoingEdges(randDst1,
// getEdges(randDst1))) {
// System.out.print(" " + i);
// }
// System.out.println("");
if (!connected(randDst1, randDst2)) {
tempEdge = new Edge(Math.min(randDst1.getIndex(),
randDst2.getIndex()), Math.max(
randDst1.getIndex(), randDst2.getIndex()));
tempEdgeString = getEdgeString(tempEdge);
if (!additionalEdges[randDst1.getIndex()]
.containsKey(tempEdgeString)
&& !additionalEdges[randDst2.getIndex()]
.containsKey(tempEdgeString)) {
// System.out.println("Adding triangulation edge " +
// tempEdge);
additionalEdges[randDst1.getIndex()].put(
tempEdgeString, tempEdge);
additionalEdges[randDst2.getIndex()].put(
tempEdgeString, tempEdge);
triangulationEdgesCount--;
}
} else {
// System.out.println("Vertex " + randDst1.getIndex() +
// " is already connected to "
// + randDst2.getIndex());
}
}
secondCounter++;
if (secondCounter == currentVertexDegree) {
firstCounter++;
secondCounter = firstCounter + 1;
}
if (firstCounter == (currentVertexDegree - 1)
&& triangulationEdgesCount > 0)
throw new GDTransformationException(
"Could not find anymore pair edges for "
+ currentVertex.getIndex());
}
/*
* Keep track of wave front and wave center vertices!
*/
verticesToAdd = new ArrayList<Node>();
for (Edge i : getEdges(currentVertex).values()) {
int otherEnd;
if (i.getDst() == currentVertex.getIndex()) {
otherEnd = i.getSrc();
} else {
otherEnd = i.getDst();
}
tempVertex = g.getNode(otherEnd);
if (removedVertices.contains(tempVertex)) {
continue;
}
verticesToAdd.add(tempVertex);
}
Collections.shuffle(verticesToAdd);
waveFrontVertices = new TreeSet<Node>(verticesToAdd);
Collections.shuffle(verticesToAdd);
waveCenterVertices.addAll(verticesToAdd);
removedVertices.add(currentVertex);
// System.out.println("Adding " + currentVertex.getIndex() +
// " to removedVertices, now containing "
// + removedVertices.size() + " vertices");
}
LinkedList<Node> orderedVertices = orderVertices();
placeVertices(orderedVertices);
/*
* To avoid memory leaks: remove stuff that is not needed anymore
*/
waveCenterVertices = null;
waveFrontVertices = null;
removedEdges = null;
removedVertices = null;
// countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace,
// true);
// System.out.println("Crossings after phase 1: " + countCrossings);
if (graphPlotter != null)
graphPlotter.plot(g, idSpace, graphPlotter.getBasename()
+ "-afterPhase1");
// System.out.println("Done with phase 1 of S/T");
reduceCrossingsBySwapping(g);
writeIDSpace(g);
if (graphPlotter != null)
graphPlotter.plotFinalGraph(g, idSpace);
// countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace,
// true);
// System.out.println("Final crossings: " + countCrossings);
return g;
}
private void placeVertices(LinkedList<Node> orderedVertices) {
Node lastVertex = null;
double lastPos = 0;
double posDiff = modulus / partitions.length;
/*
* Create new RingIdentifiers in the order that was computed...
*/
RingIdentifier[] ids = new RingIdentifier[g.getNodes().length];
for (Node n : orderedVertices) {
ids[n.getIndex()] = new RingIdentifier(lastPos, idSpace);
// System.out.println("Place " + n.getIndex() + " at " + lastPos);
lastPos += posDiff;
}
/*
* ...and assign these ids to the partitions
*/
lastVertex = orderedVertices.getLast();
for (Node n : orderedVertices) {
partitions[n.getIndex()] = new RingPartition(
ids[lastVertex.getIndex()], ids[n.getIndex()]);
lastVertex = n;
}
}
private LinkedList<Node> orderVertices() {
/*
* Compute the longest path in a spanning tree created by DFS
*/
// System.out.println("Starting computation of longest path");
LinkedList<Node> longestPath = longestPath();
// System.out.println("Longest path contains " + longestPath.size() + " vertices, total number: "
// + vertexList.size());
// System.out.println("Characteristics for these vertices:");
// int counter = 0;
// int sum = 0;
// int[] degrees = new int[longestPath.size()];
//
// for ( Node n: longestPath) {
// degrees[counter++] = n.getOutDegree();
// sum += n.getOutDegree();
// }
// System.out.println("Avg degree: " + ( (double)sum / counter) + ", median degree: " + degrees[degrees.length/2]);
/*
* Check which vertices still need to be placed, as they do not lie on
* the longestPath
*/
ArrayList<Node> todoList = new ArrayList<Node>();
todoList.addAll(vertexList);
todoList.removeAll(longestPath);
Node neighbor, singleVertex;
int errors = 0;
int modCounter = 0;
while (!todoList.isEmpty()) {
int neighborPosition = -1;
/*
* We will walk through the todoList with a counter: there might be
* vertices that can not be placed yet, as they do have only
* connections to other not yet connected vertices
*/
singleVertex = todoList.get(modCounter % todoList.size());
int[] outgoingEdges = singleVertex.getOutgoingEdges();
if (outgoingEdges.length == 0) {
/*
* Current vertex is not connected, so place it anywhere
*/
neighborPosition = rand.nextInt(longestPath.size());
} else if (outgoingEdges.length == 1
&& todoList.contains(g.getNode(outgoingEdges[0]))) {
/*
* Current vertex has only one connection, and the vertex on the
* other end is also in todoList, so also place this one
* anywhere to ensure that all vertices get placed - phase 2
* will do the rest
*/
neighborPosition = rand.nextInt(longestPath.size());
} else {
/*
* Current vertex has more than one connection (or one
* connection to a connected vertex), so let's check them
*/
for (int singleNeighbor : outgoingEdges) {
neighbor = g.getNode(singleNeighbor);
neighborPosition = longestPath.indexOf(neighbor);
if (neighborPosition > -1) {
/*
* We found a neighbor that is contained in the list of
* connected vertices - stop searching
*/
break;
}
}
}
if (neighborPosition == -1) {
/*
* The current vertex does not yet have any connection to the
* longest path, so place it at a random position
*/
neighborPosition = rand.nextInt(longestPath.size());
}
/*
* As a possible position for this vertex is found: remove it from
* the todoList and place it in the longestPath. Following elements
* get shifted to the right
*/
todoList.remove(singleVertex);
longestPath.add(neighborPosition, singleVertex);
}
return longestPath;
}
private ArrayList<Edge> getAllEdges(Node n) {
ArrayList<Edge> vertexEdges = new ArrayList<Edge>();
if (edges[n.getIndex()] == null) {
edges[n.getIndex()] = n.generateAllEdges();
}
for (Edge e : edges[n.getIndex()])
vertexEdges.add(e);
if (!useOriginalGraphWithoutRemovalList) {
vertexEdges.addAll(additionalEdges[n.getIndex()].values());
}
return vertexEdges;
}
private HashMap<String, Edge> getEdges(Node n) {
HashMap<String, Edge> edges = new HashMap<String, Edge>(n.getDegree());
for (Edge i : getAllEdges(n)) {
if (!useOriginalGraphWithoutRemovalList
&& (removedVertices.contains(g.getNode(i.getDst())) || removedVertices
.contains(g.getNode(i.getSrc())))) {
continue;
}
edges.put(getEdgeString(i), i);
}
return edges;
}
private int[] filterOutgoingEdges(Node n, HashMap<String, Edge> edges) {
int[] result = new int[edges.size()];
int edgeCounter = 0;
for (Edge sE : edges.values()) {
int otherEnd;
if (sE.getDst() == n.getIndex()) {
otherEnd = sE.getSrc();
} else {
otherEnd = sE.getDst();
}
result[edgeCounter++] = otherEnd;
}
return result;
}
private Boolean connected(Node n, Node m) {
int[] edges = filterOutgoingEdges(n, getEdges(n));
for (int sE : edges) {
if (sE == m.getIndex())
return true;
}
return false;
}
private LinkedList<Integer> findLongestPath(SpanningTree tree, int source,
int comingFrom) {
LinkedList<Integer> connections = new LinkedList<Integer>();
for (int singleSrc : tree.getChildren(source)) {
if (singleSrc == source)
continue;
connections.add(singleSrc);
}
connections.add(tree.getParent(source));
connections.removeFirstOccurrence(source);
connections.removeFirstOccurrence(comingFrom);
if (connections.size() == 0) {
connections.add(source);
return connections;
}
LinkedList<Integer> longestPath, tempPath;
longestPath = new LinkedList<Integer>();
for (Integer singleConnection : connections) {
if (singleConnection == null) {
/*
* This is the roots parent!
*/
continue;
}
tempPath = findLongestPath(tree, singleConnection, source);
if (tempPath.size() > longestPath.size()) {
longestPath = tempPath;
}
}
longestPath.add(source);
return longestPath;
}
private LinkedList<Node> longestPath() {
LinkedList<Node> result = new LinkedList<Node>();
useOriginalGraphWithoutRemovalList = true;
int startIndex = 0;
Node start;
do {
start = removedVertices.get(startIndex++);
} while (start.getOutDegree() == 0);
deepestVertex = new ParentChild(-1, start.getIndex(), -1);
// System.out.println("Starting DFS at " + start);
HashMap<Integer, ParentChild> parentChildMap = new HashMap<Integer, ParentChild>(
vertexList.size());
dfs(start, deepestVertex, parentChildMap);
ArrayList<ParentChild> parentChildList = new ArrayList<ParentChild>();
parentChildList.addAll(parentChildMap.values());
SpanningTree tree = new SpanningTree(g, parentChildList);
LinkedList<Integer> resultInTree = findLongestPath(tree,
deepestVertex.getChild(), -1);
for (Integer tempVertex : resultInTree) {
result.add(g.getNode(tempVertex));
}
return result;
}
private void dfs(Node n, ParentChild root,
HashMap<Integer, ParentChild> visited) {
int otherEnd;
if (visited.containsKey(n.getIndex())) {
return;
}
ParentChild current = new ParentChild(root.getChild(), n.getIndex(),
root.getDepth() + 1);
visited.put(n.getIndex(), current);
if (current.getDepth() > deepestVertex.getDepth()) {
deepestVertex = current;
}
for (Edge mEdge : getEdges(n).values()) {
if (mEdge.getDst() == n.getIndex()) {
otherEnd = mEdge.getSrc();
} else {
otherEnd = mEdge.getDst();
}
Node mVertex = g.getNode(otherEnd);
dfs(mVertex, current, visited);
}
}
/**
* @return
*/
private Node getVertex() {
/*
* Retrieve any wave front vertex...
*/
int vDegree, tempVDegree;
Node result = null;
vDegree = Integer.MAX_VALUE;
if (waveFrontVertices != null) {
for (Node tempVertex : waveFrontVertices) {
if (!removedVertices.contains(tempVertex)) {
tempVDegree = getEdges(tempVertex).size();
if (tempVDegree < vDegree) {
result = tempVertex;
vDegree = tempVDegree;
}
}
}
if (result != null) {
waveFrontVertices.remove(result);
return result;
}
}
/*
* ...or a wave center vertex...
*/
vDegree = Integer.MAX_VALUE;
if (waveCenterVertices != null) {
for (Node tempVertex : waveCenterVertices) {
if (!removedVertices.contains(tempVertex)) {
tempVDegree = getEdges(tempVertex).size();
if (tempVDegree < vDegree) {
result = tempVertex;
vDegree = tempVDegree;
}
}
}
if (result != null) {
waveCenterVertices.remove(result);
return result;
}
}
/*
* ...or any lowest degree vertex
*/
resortVertexlist();
for (Node tempVertex : vertexList) {
if (!removedVertices.contains(tempVertex)) {
return tempVertex;
}
}
throw new GDTransformationException("No vertex left");
}
private void resortVertexlist() {
if (removedVertices.isEmpty() && removedEdges.isEmpty()) {
Collections.sort(vertexList);
return;
}
// System.out.println("Resorting vertexList as already " +
// removedVertices.size() + " vertices (of a total of "
// + vertexList.size() + ") and " + removedEdges.size() +
// " edges were removed");
/*
* We may not delete vertices from the vertex list, as orderVertices
* needs this later. So: as we are only interested in the vertices with
* low degree, set the (internal) degree of removed vertices to the
* total number of vertices
*/
int vDegree;
int highestDegree = vertexList.size();
ArrayList<Node>[] tempVertexList = new ArrayList[highestDegree + 1];
for (int i = 0; i <= highestDegree; i++) {
tempVertexList[i] = new ArrayList<Node>();
}
for (Node v : vertexList) {
if (removedVertices.contains(v)) {
vDegree = highestDegree;
} else {
vDegree = getEdges(v).size();
}
tempVertexList[vDegree].add(v);
}
List<Node> newVertexList = new ArrayList<Node>(vertexList.size());
for (int i = 0; i <= highestDegree; i++) {
Collections.shuffle(tempVertexList[i]);
newVertexList.addAll(tempVertexList[i]);
}
vertexList = newVertexList;
}
private HashMap<String, Edge> getPairEdges(Node n) {
HashMap<String, Edge> result = new HashMap<String, Edge>();
Node tempInnerVertex;
Edge tempEdge;
int otherOuterEnd, otherInnerEnd;
// System.out.println("\n\nCalling getPairEdges for vertex " +
// n.getIndex());
HashMap<String, Edge> allOuterEdges = getEdges(n);
for (Edge tempOuterEdge : allOuterEdges.values()) {
// System.out.println("\n");
if (tempOuterEdge.getDst() == n.getIndex()) {
otherOuterEnd = tempOuterEdge.getSrc();
} else {
otherOuterEnd = tempOuterEdge.getDst();
}
// System.out.println("For the edge " + tempOuterEdge + ", " +
// otherOuterEnd + " is the other vertex");
HashMap<String, Edge> allInnerEdges = getEdges(g
.getNode(otherOuterEnd));
for (Edge tempInnerEdge : allInnerEdges.values()) {
// System.out.println(tempInnerEdge + " is an edge for " +
// otherOuterEnd);
if (tempInnerEdge.getDst() == otherOuterEnd) {
otherInnerEnd = tempInnerEdge.getSrc();
} else {
otherInnerEnd = tempInnerEdge.getDst();
}
if (otherInnerEnd == n.getIndex()) {
continue;
}
tempInnerVertex = g.getNode(otherInnerEnd);
if (connected(n, tempInnerVertex)) {
tempEdge = new Edge(Math.min(otherInnerEnd, otherOuterEnd),
Math.max(otherInnerEnd, otherOuterEnd));
// System.out.println(getEdgeString(tempEdge) +
// " is a pair edge of " + otherOuterEnd + " and " +
// otherInnerEnd);
result.put(getEdgeString(tempEdge), tempEdge);
} else {
// System.out.println("No pair edge between " +
// otherOuterEnd + " and " + otherInnerEnd);
}
}
}
return result;
}
private String getEdgeString(Edge e) {
return Math.min(e.getSrc(), e.getDst()) + "->"
+ Math.max(e.getSrc(), e.getDst());
}
} | Flipp/GTNA | src/gtna/transformation/gd/SixTollis.java | 7,015 | // degrees[counter++] = n.getOutDegree(); | line_comment | nl | /* ===========================================================
* GTNA : Graph-Theoretic Network Analyzer
* ===========================================================
*
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/
*
* GTNA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GTNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* ---------------------------------------
* SixTollis.java
* ---------------------------------------
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Original Author: Nico;
* Contributors: -;
*
* Changes since 2011-05-17
* ---------------------------------------
*
*/
package gtna.transformation.gd;
import gtna.drawing.GraphPlotter;
import gtna.graph.Edge;
import gtna.graph.Graph;
import gtna.graph.Node;
import gtna.graph.spanningTree.ParentChild;
import gtna.graph.spanningTree.SpanningTree;
import gtna.id.ring.RingIdentifier;
import gtna.id.ring.RingPartition;
import gtna.metrics.edges.EdgeCrossings;
import gtna.util.parameter.BooleanParameter;
import gtna.util.parameter.DoubleParameter;
import gtna.util.parameter.IntParameter;
import gtna.util.parameter.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
/**
* @author Nico
*
*/
public class SixTollis extends CircularAbstract {
private TreeSet<Node> waveCenterVertices, waveFrontVertices;
private List<Node> vertexList, removedVertices;
private HashMap<String, Edge> removedEdges;
private HashMap<String, Edge>[] additionalEdges;
private Edge[][] edges;
private ParentChild deepestVertex;
private Boolean useOriginalGraphWithoutRemovalList;
private Graph g;
public SixTollis(int realities, double modulus, boolean wrapAround,
GraphPlotter plotter) {
super("GDA_SIX_TOLLIS", new Parameter[] {
new IntParameter("REALITIES", realities),
new DoubleParameter("MODULUS", modulus),
new BooleanParameter("WRAPAROUND", wrapAround) });
this.realities = realities;
this.modulus = modulus;
this.wrapAround = wrapAround;
this.graphPlotter = plotter;
}
public GraphDrawingAbstract clone() {
return new SixTollis(realities, modulus, wrapAround, graphPlotter);
}
@Override
public Graph transform(Graph g) {
useOriginalGraphWithoutRemovalList = false;
initIDSpace(g);
if (graphPlotter != null)
graphPlotter.plotStartGraph(g, idSpace);
EdgeCrossings ec = new EdgeCrossings();
int countCrossings = -1;
// countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace,
// true);
// System.out.println("Crossings randomized: " + countCrossings);
this.g = g;
/*
* Phase 1
*/
edges = new Edge[g.getNodes().length][];
Node tempVertex = null;
Node currentVertex = null;
Node randDst1, randDst2;
Edge tempEdge;
String tempEdgeString;
ArrayList<Node> verticesToAdd;
removedEdges = new HashMap<String, Edge>(g.computeNumberOfEdges());
HashMap<String, Edge> pairEdges = null;
removedVertices = new ArrayList<Node>();
waveCenterVertices = new TreeSet<Node>();
waveFrontVertices = new TreeSet<Node>();
additionalEdges = new HashMap[g.getNodes().length];
for (int i = 0; i < g.getNodes().length; i++) {
additionalEdges[i] = new HashMap<String, Edge>();
}
vertexList = Arrays.asList(g.getNodes().clone());
System.out.println("Done with all init stuff, should run following loop from 1 to " + (vertexList.size() - 3));
for (int counter = 1; counter < (vertexList.size() - 3); counter++) {
currentVertex = getVertex();
if (counter % (vertexList.size() / 10) == 0) {
// System.out.println("Processing " + currentVertex + " with a degree of "
// + getEdges(currentVertex).size() + " (vertex " + counter + " of " + (vertexList.size() - 3)
// + ")");
}
pairEdges = getPairEdges(currentVertex);
for (Edge singleEdge : pairEdges.values()) {
removedEdges.put(getEdgeString(singleEdge), singleEdge);
}
HashMap<String, Edge> currentVertexConnections = getEdges(currentVertex);
int currentVertexDegree = currentVertexConnections.size();
int triangulationEdgesCount = (currentVertexDegree - 1)
- pairEdges.size();
int[] outgoingEdges = filterOutgoingEdges(currentVertex,
currentVertexConnections);
// System.out.print(currentVertex.getIndex() +
// " has a current degree of " + currentVertexDegree + ", "
// + pairEdges.size() + " pair edges and a need for " +
// triangulationEdgesCount
// + " triangulation edges - existing edges:");
// for (Edge sE : currentVertexConnections.values()) {
// System.out.print(" " + sE);
// }
// System.out.println();
int firstCounter = 0;
int secondCounter = 1;
while (triangulationEdgesCount > 0) {
randDst1 = g.getNode(outgoingEdges[firstCounter]);
randDst2 = g.getNode(outgoingEdges[secondCounter]);
if (!randDst1.equals(randDst2)
&& !removedVertices.contains(randDst1)
&& !removedVertices.contains(randDst2)) {
// System.out.println("rand1: " + randDst1.getIndex() +
// "; rand2: " + randDst2.getIndex());
// System.out.print("Outgoing edges for r1:");
// for (int i : filterOutgoingEdges(randDst1,
// getEdges(randDst1))) {
// System.out.print(" " + i);
// }
// System.out.println("");
if (!connected(randDst1, randDst2)) {
tempEdge = new Edge(Math.min(randDst1.getIndex(),
randDst2.getIndex()), Math.max(
randDst1.getIndex(), randDst2.getIndex()));
tempEdgeString = getEdgeString(tempEdge);
if (!additionalEdges[randDst1.getIndex()]
.containsKey(tempEdgeString)
&& !additionalEdges[randDst2.getIndex()]
.containsKey(tempEdgeString)) {
// System.out.println("Adding triangulation edge " +
// tempEdge);
additionalEdges[randDst1.getIndex()].put(
tempEdgeString, tempEdge);
additionalEdges[randDst2.getIndex()].put(
tempEdgeString, tempEdge);
triangulationEdgesCount--;
}
} else {
// System.out.println("Vertex " + randDst1.getIndex() +
// " is already connected to "
// + randDst2.getIndex());
}
}
secondCounter++;
if (secondCounter == currentVertexDegree) {
firstCounter++;
secondCounter = firstCounter + 1;
}
if (firstCounter == (currentVertexDegree - 1)
&& triangulationEdgesCount > 0)
throw new GDTransformationException(
"Could not find anymore pair edges for "
+ currentVertex.getIndex());
}
/*
* Keep track of wave front and wave center vertices!
*/
verticesToAdd = new ArrayList<Node>();
for (Edge i : getEdges(currentVertex).values()) {
int otherEnd;
if (i.getDst() == currentVertex.getIndex()) {
otherEnd = i.getSrc();
} else {
otherEnd = i.getDst();
}
tempVertex = g.getNode(otherEnd);
if (removedVertices.contains(tempVertex)) {
continue;
}
verticesToAdd.add(tempVertex);
}
Collections.shuffle(verticesToAdd);
waveFrontVertices = new TreeSet<Node>(verticesToAdd);
Collections.shuffle(verticesToAdd);
waveCenterVertices.addAll(verticesToAdd);
removedVertices.add(currentVertex);
// System.out.println("Adding " + currentVertex.getIndex() +
// " to removedVertices, now containing "
// + removedVertices.size() + " vertices");
}
LinkedList<Node> orderedVertices = orderVertices();
placeVertices(orderedVertices);
/*
* To avoid memory leaks: remove stuff that is not needed anymore
*/
waveCenterVertices = null;
waveFrontVertices = null;
removedEdges = null;
removedVertices = null;
// countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace,
// true);
// System.out.println("Crossings after phase 1: " + countCrossings);
if (graphPlotter != null)
graphPlotter.plot(g, idSpace, graphPlotter.getBasename()
+ "-afterPhase1");
// System.out.println("Done with phase 1 of S/T");
reduceCrossingsBySwapping(g);
writeIDSpace(g);
if (graphPlotter != null)
graphPlotter.plotFinalGraph(g, idSpace);
// countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace,
// true);
// System.out.println("Final crossings: " + countCrossings);
return g;
}
private void placeVertices(LinkedList<Node> orderedVertices) {
Node lastVertex = null;
double lastPos = 0;
double posDiff = modulus / partitions.length;
/*
* Create new RingIdentifiers in the order that was computed...
*/
RingIdentifier[] ids = new RingIdentifier[g.getNodes().length];
for (Node n : orderedVertices) {
ids[n.getIndex()] = new RingIdentifier(lastPos, idSpace);
// System.out.println("Place " + n.getIndex() + " at " + lastPos);
lastPos += posDiff;
}
/*
* ...and assign these ids to the partitions
*/
lastVertex = orderedVertices.getLast();
for (Node n : orderedVertices) {
partitions[n.getIndex()] = new RingPartition(
ids[lastVertex.getIndex()], ids[n.getIndex()]);
lastVertex = n;
}
}
private LinkedList<Node> orderVertices() {
/*
* Compute the longest path in a spanning tree created by DFS
*/
// System.out.println("Starting computation of longest path");
LinkedList<Node> longestPath = longestPath();
// System.out.println("Longest path contains " + longestPath.size() + " vertices, total number: "
// + vertexList.size());
// System.out.println("Characteristics for these vertices:");
// int counter = 0;
// int sum = 0;
// int[] degrees = new int[longestPath.size()];
//
// for ( Node n: longestPath) {
// degrees[counter++] =<SUF>
// sum += n.getOutDegree();
// }
// System.out.println("Avg degree: " + ( (double)sum / counter) + ", median degree: " + degrees[degrees.length/2]);
/*
* Check which vertices still need to be placed, as they do not lie on
* the longestPath
*/
ArrayList<Node> todoList = new ArrayList<Node>();
todoList.addAll(vertexList);
todoList.removeAll(longestPath);
Node neighbor, singleVertex;
int errors = 0;
int modCounter = 0;
while (!todoList.isEmpty()) {
int neighborPosition = -1;
/*
* We will walk through the todoList with a counter: there might be
* vertices that can not be placed yet, as they do have only
* connections to other not yet connected vertices
*/
singleVertex = todoList.get(modCounter % todoList.size());
int[] outgoingEdges = singleVertex.getOutgoingEdges();
if (outgoingEdges.length == 0) {
/*
* Current vertex is not connected, so place it anywhere
*/
neighborPosition = rand.nextInt(longestPath.size());
} else if (outgoingEdges.length == 1
&& todoList.contains(g.getNode(outgoingEdges[0]))) {
/*
* Current vertex has only one connection, and the vertex on the
* other end is also in todoList, so also place this one
* anywhere to ensure that all vertices get placed - phase 2
* will do the rest
*/
neighborPosition = rand.nextInt(longestPath.size());
} else {
/*
* Current vertex has more than one connection (or one
* connection to a connected vertex), so let's check them
*/
for (int singleNeighbor : outgoingEdges) {
neighbor = g.getNode(singleNeighbor);
neighborPosition = longestPath.indexOf(neighbor);
if (neighborPosition > -1) {
/*
* We found a neighbor that is contained in the list of
* connected vertices - stop searching
*/
break;
}
}
}
if (neighborPosition == -1) {
/*
* The current vertex does not yet have any connection to the
* longest path, so place it at a random position
*/
neighborPosition = rand.nextInt(longestPath.size());
}
/*
* As a possible position for this vertex is found: remove it from
* the todoList and place it in the longestPath. Following elements
* get shifted to the right
*/
todoList.remove(singleVertex);
longestPath.add(neighborPosition, singleVertex);
}
return longestPath;
}
private ArrayList<Edge> getAllEdges(Node n) {
ArrayList<Edge> vertexEdges = new ArrayList<Edge>();
if (edges[n.getIndex()] == null) {
edges[n.getIndex()] = n.generateAllEdges();
}
for (Edge e : edges[n.getIndex()])
vertexEdges.add(e);
if (!useOriginalGraphWithoutRemovalList) {
vertexEdges.addAll(additionalEdges[n.getIndex()].values());
}
return vertexEdges;
}
private HashMap<String, Edge> getEdges(Node n) {
HashMap<String, Edge> edges = new HashMap<String, Edge>(n.getDegree());
for (Edge i : getAllEdges(n)) {
if (!useOriginalGraphWithoutRemovalList
&& (removedVertices.contains(g.getNode(i.getDst())) || removedVertices
.contains(g.getNode(i.getSrc())))) {
continue;
}
edges.put(getEdgeString(i), i);
}
return edges;
}
private int[] filterOutgoingEdges(Node n, HashMap<String, Edge> edges) {
int[] result = new int[edges.size()];
int edgeCounter = 0;
for (Edge sE : edges.values()) {
int otherEnd;
if (sE.getDst() == n.getIndex()) {
otherEnd = sE.getSrc();
} else {
otherEnd = sE.getDst();
}
result[edgeCounter++] = otherEnd;
}
return result;
}
private Boolean connected(Node n, Node m) {
int[] edges = filterOutgoingEdges(n, getEdges(n));
for (int sE : edges) {
if (sE == m.getIndex())
return true;
}
return false;
}
private LinkedList<Integer> findLongestPath(SpanningTree tree, int source,
int comingFrom) {
LinkedList<Integer> connections = new LinkedList<Integer>();
for (int singleSrc : tree.getChildren(source)) {
if (singleSrc == source)
continue;
connections.add(singleSrc);
}
connections.add(tree.getParent(source));
connections.removeFirstOccurrence(source);
connections.removeFirstOccurrence(comingFrom);
if (connections.size() == 0) {
connections.add(source);
return connections;
}
LinkedList<Integer> longestPath, tempPath;
longestPath = new LinkedList<Integer>();
for (Integer singleConnection : connections) {
if (singleConnection == null) {
/*
* This is the roots parent!
*/
continue;
}
tempPath = findLongestPath(tree, singleConnection, source);
if (tempPath.size() > longestPath.size()) {
longestPath = tempPath;
}
}
longestPath.add(source);
return longestPath;
}
private LinkedList<Node> longestPath() {
LinkedList<Node> result = new LinkedList<Node>();
useOriginalGraphWithoutRemovalList = true;
int startIndex = 0;
Node start;
do {
start = removedVertices.get(startIndex++);
} while (start.getOutDegree() == 0);
deepestVertex = new ParentChild(-1, start.getIndex(), -1);
// System.out.println("Starting DFS at " + start);
HashMap<Integer, ParentChild> parentChildMap = new HashMap<Integer, ParentChild>(
vertexList.size());
dfs(start, deepestVertex, parentChildMap);
ArrayList<ParentChild> parentChildList = new ArrayList<ParentChild>();
parentChildList.addAll(parentChildMap.values());
SpanningTree tree = new SpanningTree(g, parentChildList);
LinkedList<Integer> resultInTree = findLongestPath(tree,
deepestVertex.getChild(), -1);
for (Integer tempVertex : resultInTree) {
result.add(g.getNode(tempVertex));
}
return result;
}
private void dfs(Node n, ParentChild root,
HashMap<Integer, ParentChild> visited) {
int otherEnd;
if (visited.containsKey(n.getIndex())) {
return;
}
ParentChild current = new ParentChild(root.getChild(), n.getIndex(),
root.getDepth() + 1);
visited.put(n.getIndex(), current);
if (current.getDepth() > deepestVertex.getDepth()) {
deepestVertex = current;
}
for (Edge mEdge : getEdges(n).values()) {
if (mEdge.getDst() == n.getIndex()) {
otherEnd = mEdge.getSrc();
} else {
otherEnd = mEdge.getDst();
}
Node mVertex = g.getNode(otherEnd);
dfs(mVertex, current, visited);
}
}
/**
* @return
*/
private Node getVertex() {
/*
* Retrieve any wave front vertex...
*/
int vDegree, tempVDegree;
Node result = null;
vDegree = Integer.MAX_VALUE;
if (waveFrontVertices != null) {
for (Node tempVertex : waveFrontVertices) {
if (!removedVertices.contains(tempVertex)) {
tempVDegree = getEdges(tempVertex).size();
if (tempVDegree < vDegree) {
result = tempVertex;
vDegree = tempVDegree;
}
}
}
if (result != null) {
waveFrontVertices.remove(result);
return result;
}
}
/*
* ...or a wave center vertex...
*/
vDegree = Integer.MAX_VALUE;
if (waveCenterVertices != null) {
for (Node tempVertex : waveCenterVertices) {
if (!removedVertices.contains(tempVertex)) {
tempVDegree = getEdges(tempVertex).size();
if (tempVDegree < vDegree) {
result = tempVertex;
vDegree = tempVDegree;
}
}
}
if (result != null) {
waveCenterVertices.remove(result);
return result;
}
}
/*
* ...or any lowest degree vertex
*/
resortVertexlist();
for (Node tempVertex : vertexList) {
if (!removedVertices.contains(tempVertex)) {
return tempVertex;
}
}
throw new GDTransformationException("No vertex left");
}
private void resortVertexlist() {
if (removedVertices.isEmpty() && removedEdges.isEmpty()) {
Collections.sort(vertexList);
return;
}
// System.out.println("Resorting vertexList as already " +
// removedVertices.size() + " vertices (of a total of "
// + vertexList.size() + ") and " + removedEdges.size() +
// " edges were removed");
/*
* We may not delete vertices from the vertex list, as orderVertices
* needs this later. So: as we are only interested in the vertices with
* low degree, set the (internal) degree of removed vertices to the
* total number of vertices
*/
int vDegree;
int highestDegree = vertexList.size();
ArrayList<Node>[] tempVertexList = new ArrayList[highestDegree + 1];
for (int i = 0; i <= highestDegree; i++) {
tempVertexList[i] = new ArrayList<Node>();
}
for (Node v : vertexList) {
if (removedVertices.contains(v)) {
vDegree = highestDegree;
} else {
vDegree = getEdges(v).size();
}
tempVertexList[vDegree].add(v);
}
List<Node> newVertexList = new ArrayList<Node>(vertexList.size());
for (int i = 0; i <= highestDegree; i++) {
Collections.shuffle(tempVertexList[i]);
newVertexList.addAll(tempVertexList[i]);
}
vertexList = newVertexList;
}
private HashMap<String, Edge> getPairEdges(Node n) {
HashMap<String, Edge> result = new HashMap<String, Edge>();
Node tempInnerVertex;
Edge tempEdge;
int otherOuterEnd, otherInnerEnd;
// System.out.println("\n\nCalling getPairEdges for vertex " +
// n.getIndex());
HashMap<String, Edge> allOuterEdges = getEdges(n);
for (Edge tempOuterEdge : allOuterEdges.values()) {
// System.out.println("\n");
if (tempOuterEdge.getDst() == n.getIndex()) {
otherOuterEnd = tempOuterEdge.getSrc();
} else {
otherOuterEnd = tempOuterEdge.getDst();
}
// System.out.println("For the edge " + tempOuterEdge + ", " +
// otherOuterEnd + " is the other vertex");
HashMap<String, Edge> allInnerEdges = getEdges(g
.getNode(otherOuterEnd));
for (Edge tempInnerEdge : allInnerEdges.values()) {
// System.out.println(tempInnerEdge + " is an edge for " +
// otherOuterEnd);
if (tempInnerEdge.getDst() == otherOuterEnd) {
otherInnerEnd = tempInnerEdge.getSrc();
} else {
otherInnerEnd = tempInnerEdge.getDst();
}
if (otherInnerEnd == n.getIndex()) {
continue;
}
tempInnerVertex = g.getNode(otherInnerEnd);
if (connected(n, tempInnerVertex)) {
tempEdge = new Edge(Math.min(otherInnerEnd, otherOuterEnd),
Math.max(otherInnerEnd, otherOuterEnd));
// System.out.println(getEdgeString(tempEdge) +
// " is a pair edge of " + otherOuterEnd + " and " +
// otherInnerEnd);
result.put(getEdgeString(tempEdge), tempEdge);
} else {
// System.out.println("No pair edge between " +
// otherOuterEnd + " and " + otherInnerEnd);
}
}
}
return result;
}
private String getEdgeString(Edge e) {
return Math.min(e.getSrc(), e.getDst()) + "->"
+ Math.max(e.getSrc(), e.getDst());
}
} |
169611_0 | public class Duplicator {
public static void main(String[] args) {
System.out.println( duplicateCounter(20));
}
/**
* TEST DIRECTORY en TEST CLASS
*
* 1. Maak een test directory aan.
* 2. Maak van deze directory een Test Resource Folder wordt
*
* 3. Maak een test class aan.
*
*/
/**
*
* 1. Maak een SUT aan in je test class.
*
* 2. Maak een test method aan waarbij je de onderstaande
* functie duplicateCounter() test
*
* 3. Run de test en bekijk het resultaat
*
* 4. Maak de functie duplicateCounter() af zodat de test wel werkt.
*
*/
public static int duplicateCounter(int numberDuplicate) {
int newNumber = numberDuplicate*2;
return newNumber;
}
}
| FloortjeTjeertes/RedGreenRefactor | src/Duplicator.java | 248 | /**
* TEST DIRECTORY en TEST CLASS
*
* 1. Maak een test directory aan.
* 2. Maak van deze directory een Test Resource Folder wordt
*
* 3. Maak een test class aan.
*
*/ | block_comment | nl | public class Duplicator {
public static void main(String[] args) {
System.out.println( duplicateCounter(20));
}
/**
* TEST DIRECTORY en<SUF>*/
/**
*
* 1. Maak een SUT aan in je test class.
*
* 2. Maak een test method aan waarbij je de onderstaande
* functie duplicateCounter() test
*
* 3. Run de test en bekijk het resultaat
*
* 4. Maak de functie duplicateCounter() af zodat de test wel werkt.
*
*/
public static int duplicateCounter(int numberDuplicate) {
int newNumber = numberDuplicate*2;
return newNumber;
}
}
|
14954_3 |
public class Opdracht3WEEE
{
public static void main(String[] args)
{
// MAAK ALLE ONDERDELEN AF OM DE OPDRACHT TE VOLTOOIEN!
OnderdeelEen();
OnderdeelTwee();
OnderdeelDrie();
}
public static void OnderdeelEen()
{
// ONDERSTAANDE VARIABELE NAMEN EN WAARDEN MAG JE NIET AANPASSEN!
boolean waarOfNiet = false;
String stukjeTekst = "TEKST";
int getalA = 3;
int getalB = 5;
int getalC = 7;
int getalD = (int)Math.ceil( Math.random() * 10 ); // Willekeurige waarde van 1 t/m 10.
/*
* OPDRACHT OMSCHRIJVING:
*
* VERTAAL HET ONDERSTAANDE COMMENTAAR BINNEN DE BLOKHAKEN [] NAAR WERKENDE CODE DOOR if-statements
* MET DE CORRECTE voorwaarden TOE TE PASSEN.
*
*/
// [ALS waarOfNiet NIET GELIJK STAAT AAN true EN getalB GROTER OF GELIJK IS AAN getalA]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
// [ALS stukjeTekst GELIJK STAAT AAN "TEKST"]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
// [ALS getalD KLEINER OF GELIJK STAAT AAN getalA OF ALS getalD GROTER OF GELIJK STAAT AAN getalC]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
System.out.println("ONDERDEEL EEN: Uitkomst 1 = " + getalD + " ###############");
}
// [ZO NIET, ALS getalD NIET GELIJK STAAT AAN getalB]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
System.out.println("ONDERDEEL EEN: Uitkomst 2 = " + getalD + " !!!!!!!!!");
}
// [ZO NIET, DOE DAN HET VOLGENDE]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
System.out.println("ONDERDEEL EEN: Uitkomst 3 = " + getalD + " $$$");
}
}
}
}
public static void OnderdeelTwee()
{
// ONDERSTAANDE VARIABELE NAMEN EN WAARDEN MAG JE NIET AANPASSEN!
int testWaardeA = (int)Math.ceil( Math.random() * 5 ); // Willekeurige waarde van 1 t/m 5.
/*
* OPDRACHT OMSCHRIJVING:
*
* MAAK EEN SWITCH-STATEMENT WAARIN JE GEBRUIK MAAKT VAN testWaardeA. DE VARIABELE testWaardeA KAN EEN WAARDE HEBBEN VAN 1 t/m 5.
* VOOR ELKE UITKOMST VAN testWaardeA MOET JE EEN ANDER RESULTAAT PRINTEN DOOR System.out.println("") TE GEBRUIKEN.
* (Dus in totaal 5 verschillende uitkomsten!)
*
*/
// ### MAAK HIER JE SWITCH STATEMENT ###
}
public static void OnderdeelDrie()
{
// ONDERSTAANDE VARIABELE NAMEN EN WAARDEN MAG JE NIET AANPASSEN!
int testWaarde1 = (int)Math.ceil( Math.random() * 5 ); // Willekeurige waarde van 1 t/m 5.
int testWaarde2 = testWaarde1;
boolean testWaarde3 = true;
boolean testWaarde4 = false;
/*
* OPDRACHT OMSCHRIJVING:
*
* VUL ALLEEN DE CORRECTE OPERATOREN IN OM DE ONDERSTAANDE IF-STATEMENT TE LATEN KLOPPEN.
* (De uitkomst van de if-statement moet dus JA, GA DOOR zijn.)
* (Je moet het resultaat "GOED ZO! DE IF-STATEMENT IS GELUKT!" dus te zien krijgen!)
*
* HAAL DE COMMENTS VAN DE IF-STATEMENT WEG OM HET TE TESTEN.
*
*/
//if
//(
// (testWaarde1 /*OPERATOR*/ testWaarde2 /*OPERATOR*/ testWaarde2 /*OPERATOR*/ 6) == false /*OPERATOR*/
// (testWaarde3 /*OPERATOR*/ testWaarde4)
//)
{
System.out.println("GOED ZO! DE IF-STATEMENT IS GELUKT!");
}
else
{
System.out.println("JAMMER... DE IF-STATEMENT KLOPT NOG STEEDS NIET.");
}
}
}
| FloortjeTjeertes/TPR | Periode 1/Les 3/Opdracht3WEEE.java | 1,590 | /*
* OPDRACHT OMSCHRIJVING:
*
* VERTAAL HET ONDERSTAANDE COMMENTAAR BINNEN DE BLOKHAKEN [] NAAR WERKENDE CODE DOOR if-statements
* MET DE CORRECTE voorwaarden TOE TE PASSEN.
*
*/ | block_comment | nl |
public class Opdracht3WEEE
{
public static void main(String[] args)
{
// MAAK ALLE ONDERDELEN AF OM DE OPDRACHT TE VOLTOOIEN!
OnderdeelEen();
OnderdeelTwee();
OnderdeelDrie();
}
public static void OnderdeelEen()
{
// ONDERSTAANDE VARIABELE NAMEN EN WAARDEN MAG JE NIET AANPASSEN!
boolean waarOfNiet = false;
String stukjeTekst = "TEKST";
int getalA = 3;
int getalB = 5;
int getalC = 7;
int getalD = (int)Math.ceil( Math.random() * 10 ); // Willekeurige waarde van 1 t/m 10.
/*
* OPDRACHT OMSCHRIJVING:
<SUF>*/
// [ALS waarOfNiet NIET GELIJK STAAT AAN true EN getalB GROTER OF GELIJK IS AAN getalA]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
// [ALS stukjeTekst GELIJK STAAT AAN "TEKST"]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
// [ALS getalD KLEINER OF GELIJK STAAT AAN getalA OF ALS getalD GROTER OF GELIJK STAAT AAN getalC]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
System.out.println("ONDERDEEL EEN: Uitkomst 1 = " + getalD + " ###############");
}
// [ZO NIET, ALS getalD NIET GELIJK STAAT AAN getalB]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
System.out.println("ONDERDEEL EEN: Uitkomst 2 = " + getalD + " !!!!!!!!!");
}
// [ZO NIET, DOE DAN HET VOLGENDE]
// ### VERVANG DEZE REGEL MET JOUW IF-STATEMENT CODE! ###
{
System.out.println("ONDERDEEL EEN: Uitkomst 3 = " + getalD + " $$$");
}
}
}
}
public static void OnderdeelTwee()
{
// ONDERSTAANDE VARIABELE NAMEN EN WAARDEN MAG JE NIET AANPASSEN!
int testWaardeA = (int)Math.ceil( Math.random() * 5 ); // Willekeurige waarde van 1 t/m 5.
/*
* OPDRACHT OMSCHRIJVING:
*
* MAAK EEN SWITCH-STATEMENT WAARIN JE GEBRUIK MAAKT VAN testWaardeA. DE VARIABELE testWaardeA KAN EEN WAARDE HEBBEN VAN 1 t/m 5.
* VOOR ELKE UITKOMST VAN testWaardeA MOET JE EEN ANDER RESULTAAT PRINTEN DOOR System.out.println("") TE GEBRUIKEN.
* (Dus in totaal 5 verschillende uitkomsten!)
*
*/
// ### MAAK HIER JE SWITCH STATEMENT ###
}
public static void OnderdeelDrie()
{
// ONDERSTAANDE VARIABELE NAMEN EN WAARDEN MAG JE NIET AANPASSEN!
int testWaarde1 = (int)Math.ceil( Math.random() * 5 ); // Willekeurige waarde van 1 t/m 5.
int testWaarde2 = testWaarde1;
boolean testWaarde3 = true;
boolean testWaarde4 = false;
/*
* OPDRACHT OMSCHRIJVING:
*
* VUL ALLEEN DE CORRECTE OPERATOREN IN OM DE ONDERSTAANDE IF-STATEMENT TE LATEN KLOPPEN.
* (De uitkomst van de if-statement moet dus JA, GA DOOR zijn.)
* (Je moet het resultaat "GOED ZO! DE IF-STATEMENT IS GELUKT!" dus te zien krijgen!)
*
* HAAL DE COMMENTS VAN DE IF-STATEMENT WEG OM HET TE TESTEN.
*
*/
//if
//(
// (testWaarde1 /*OPERATOR*/ testWaarde2 /*OPERATOR*/ testWaarde2 /*OPERATOR*/ 6) == false /*OPERATOR*/
// (testWaarde3 /*OPERATOR*/ testWaarde4)
//)
{
System.out.println("GOED ZO! DE IF-STATEMENT IS GELUKT!");
}
else
{
System.out.println("JAMMER... DE IF-STATEMENT KLOPT NOG STEEDS NIET.");
}
}
}
|
85244_5 | import java.util.*;
public class Main {
static public void guess(String word, int life){
char[] filler= new char[word.length()];
int i =0;
while (i<word.length() ){
filler[i]='-';
if(word.charAt(i)==' '){
filler[i]=' ';
}
i++;
}
System.out.print(filler);
System.out.println(" Life remaining=" + life);
ArrayList<Character> l = new ArrayList<Character>();
Scanner s=new Scanner(System.in); // leest de characters
while(life>0){
char x=s.next().charAt(0); // character input door gebruiker
if(l.contains(x)){
System.out.println("al gebruikt");
continue; //terwile loop bezig is
}
l.add(x);
if(word.contains(x+"")){
for(int y=0;y<word.length();y++) { //deze loop checkt voor indexes van de letter
if(word.charAt(y)==x){ // en zal een '-' er voor in de plaats doen
filler[y]=x; //het character
}
}
}
else{
life--; //life decreses als het ingevoerde character niet klopt
}
if(word.equals(String.valueOf(filler))) { //controleert of de filler heztzelfde is als als word
System.out.print(filler);
System.out.println(" you won!!!");
break;
}
System.out.print(filler);
System.out.println(" Life remaining=" + life);
}
if(life==0){
System.out.println("you loose");
}
}
public static void main (String[] args) {
System.out.println("dit is galgje\n in dit leuke spelletje ga jij een woord raden\n maar je heb maar een bepaald aantal levens succses");
//String[] mannetje= {"nog niet dood" , "| \n|\n|\n|\n|\n|\n|\n|\n|\n|" , " 1|--------------- \n|/ \n| \n| \n| \n| \n| \n| \n| \n|" , "2|--------------- \n|/ |\n| | \n| (*_*)\n| \n| \n| \n| \n| \n|" , "3|--------------- \n|/ |\n| | \n| (*_*)\n| \\ | / \n| \\ | /\n| | \n| \n| \n|" , "4|--------------- \n|/ | \n| \\ | / \n| \\ (*_*) / \n| \\ | /\n| |\n| |\n| / \\ \n| / \\ \n| " , " __________ \n / \\ \n| you dead |"};
//System.out.println(mannetje[]);
String word ="florian tjeertes"; // het woord die geraade word
int life=5;
guess(word,life);
}
}
| FloortjeTjeertes/hangman | src/Main.java | 884 | //life decreses als het ingevoerde character niet klopt | line_comment | nl | import java.util.*;
public class Main {
static public void guess(String word, int life){
char[] filler= new char[word.length()];
int i =0;
while (i<word.length() ){
filler[i]='-';
if(word.charAt(i)==' '){
filler[i]=' ';
}
i++;
}
System.out.print(filler);
System.out.println(" Life remaining=" + life);
ArrayList<Character> l = new ArrayList<Character>();
Scanner s=new Scanner(System.in); // leest de characters
while(life>0){
char x=s.next().charAt(0); // character input door gebruiker
if(l.contains(x)){
System.out.println("al gebruikt");
continue; //terwile loop bezig is
}
l.add(x);
if(word.contains(x+"")){
for(int y=0;y<word.length();y++) { //deze loop checkt voor indexes van de letter
if(word.charAt(y)==x){ // en zal een '-' er voor in de plaats doen
filler[y]=x; //het character
}
}
}
else{
life--; //life decreses<SUF>
}
if(word.equals(String.valueOf(filler))) { //controleert of de filler heztzelfde is als als word
System.out.print(filler);
System.out.println(" you won!!!");
break;
}
System.out.print(filler);
System.out.println(" Life remaining=" + life);
}
if(life==0){
System.out.println("you loose");
}
}
public static void main (String[] args) {
System.out.println("dit is galgje\n in dit leuke spelletje ga jij een woord raden\n maar je heb maar een bepaald aantal levens succses");
//String[] mannetje= {"nog niet dood" , "| \n|\n|\n|\n|\n|\n|\n|\n|\n|" , " 1|--------------- \n|/ \n| \n| \n| \n| \n| \n| \n| \n|" , "2|--------------- \n|/ |\n| | \n| (*_*)\n| \n| \n| \n| \n| \n|" , "3|--------------- \n|/ |\n| | \n| (*_*)\n| \\ | / \n| \\ | /\n| | \n| \n| \n|" , "4|--------------- \n|/ | \n| \\ | / \n| \\ (*_*) / \n| \\ | /\n| |\n| |\n| / \\ \n| / \\ \n| " , " __________ \n / \\ \n| you dead |"};
//System.out.println(mannetje[]);
String word ="florian tjeertes"; // het woord die geraade word
int life=5;
guess(word,life);
}
}
|
39056_2 | package be.one16.barka.klant.adapter.out.order;
import be.one16.barka.domain.exceptions.EntityNotFoundException;
import be.one16.barka.klant.adapter.mapper.order.OrderJpaEntityMapper;
import be.one16.barka.klant.adapter.out.repository.OrderRepository;
import be.one16.barka.klant.common.OrderType;
import be.one16.barka.klant.domain.Order;
import be.one16.barka.klant.ports.out.order.CreateOrderPort;
import be.one16.barka.klant.ports.out.order.DeleteOrderPort;
import be.one16.barka.klant.ports.out.order.LoadOrdersPort;
import be.one16.barka.klant.ports.out.order.UpdateOrderPort;
import org.springframework.core.Ordered;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.UUID;
@Component
@org.springframework.core.annotation.Order(Ordered.HIGHEST_PRECEDENCE)
public class OrderDBAdapter implements LoadOrdersPort, CreateOrderPort, UpdateOrderPort, DeleteOrderPort {
private final OrderRepository orderRepository;
private final OrderJpaEntityMapper orderJpaEntityMapper;
public OrderDBAdapter(OrderRepository orderRepository, OrderJpaEntityMapper orderJpaEntityMapper) {
this.orderRepository = orderRepository;
this.orderJpaEntityMapper = orderJpaEntityMapper;
}
@Override
public Order retrieveOrderById(UUID id) {
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id);
return orderJpaEntityMapper.mapJpaEntityToOrder(orderJpaEntity);
}
@Override
public Page<Order> retrieveOrdersByFilterAndSort(String naam, Pageable pageable) {
Specification<OrderJpaEntity> specification = Specification.where(naam == null ? null : (Specification<OrderJpaEntity>) ((root, query, builder) -> builder.like(root.get("naam"), "%" + naam + "%")));
return orderRepository.findAll(specification, PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort()))
.map(orderJpaEntityMapper::mapJpaEntityToOrder);
}
@Override
public void createOrder(Order order) {
int year = order.getDatum().getYear();
OrderJpaEntity orderJpaEntity = new OrderJpaEntity();
orderJpaEntity.setUuid(order.getOrderId());
orderJpaEntity.setOrderType(order.getOrderType());
orderJpaEntity.setNaam(order.getNaam());
orderJpaEntity.setOpmerkingen(order.getOpmerkingen());
orderJpaEntity.setDatum(order.getDatum());
orderJpaEntity.setJaar(year);
orderJpaEntity.setKlantId(order.getKlantId());
orderJpaEntity.setReparatieNummer(order.getReparatieNummer());
orderJpaEntity.setOrderNummer(order.getOrderNummer());
orderJpaEntity.setSequence(decideOnSequence(order));
orderRepository.save(orderJpaEntity);
}
@Override
public void updateOrder(Order order) {
int year = order.getDatum().getYear();
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId());
orderJpaEntity.setOrderType(order.getOrderType());
orderJpaEntity.setNaam(order.getNaam());
orderJpaEntity.setOpmerkingen(order.getOpmerkingen());
orderJpaEntity.setDatum(order.getDatum());
orderJpaEntity.setJaar(year);
orderJpaEntity.setKlantId(order.getKlantId());
orderJpaEntity.setReparatieNummer(order.getReparatieNummer());
orderJpaEntity.setOrderNummer(order.getOrderNummer());
orderJpaEntity.setSequence(decideOnSequence(order));
orderRepository.save(orderJpaEntity);
}
@Override
public void deleteOrder(UUID id) {
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id);
orderRepository.delete(orderJpaEntity);
}
private OrderJpaEntity getOrderJpaEntityById(UUID id) {
return orderRepository.findByUuid(id).orElseThrow(() -> new EntityNotFoundException(String.format("Order with uuid %s doesn't exist", id)));
}
private int decideOnSequence(Order order){
int year = order.getDatum().getYear();
int sequence = 0;
OrderType orderType = order.getOrderType();
//Enkel voor facturen, anders 0
if(orderType==OrderType.FACTUUR){
//Enkel wanneer er nog geen orderNummer bestaat, maken we een nieuwe sequence aan
if(order.getOrderNummer()!=null) {
Optional<OrderJpaEntity> factuur = orderRepository.findTopByJaarOrderBySequenceDesc(year);
int sequenceLastFactuur = 0;
if (!factuur.isEmpty()) {
sequenceLastFactuur = factuur.get().getSequence();
sequence = sequenceLastFactuur + 1;
}else{
//Wanneer er geen factuur gevonden wordt, is dit de eerste factuur
sequence = 1;
}
}else{
//Anders blijft de sequence dezelfde
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId());
sequence = orderJpaEntity.getSequence();
}
}
return sequence;
}
}
| Floovera/fietsenbogaerts | klant/src/main/java/be/one16/barka/klant/adapter/out/order/OrderDBAdapter.java | 1,545 | //Wanneer er geen factuur gevonden wordt, is dit de eerste factuur | line_comment | nl | package be.one16.barka.klant.adapter.out.order;
import be.one16.barka.domain.exceptions.EntityNotFoundException;
import be.one16.barka.klant.adapter.mapper.order.OrderJpaEntityMapper;
import be.one16.barka.klant.adapter.out.repository.OrderRepository;
import be.one16.barka.klant.common.OrderType;
import be.one16.barka.klant.domain.Order;
import be.one16.barka.klant.ports.out.order.CreateOrderPort;
import be.one16.barka.klant.ports.out.order.DeleteOrderPort;
import be.one16.barka.klant.ports.out.order.LoadOrdersPort;
import be.one16.barka.klant.ports.out.order.UpdateOrderPort;
import org.springframework.core.Ordered;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.UUID;
@Component
@org.springframework.core.annotation.Order(Ordered.HIGHEST_PRECEDENCE)
public class OrderDBAdapter implements LoadOrdersPort, CreateOrderPort, UpdateOrderPort, DeleteOrderPort {
private final OrderRepository orderRepository;
private final OrderJpaEntityMapper orderJpaEntityMapper;
public OrderDBAdapter(OrderRepository orderRepository, OrderJpaEntityMapper orderJpaEntityMapper) {
this.orderRepository = orderRepository;
this.orderJpaEntityMapper = orderJpaEntityMapper;
}
@Override
public Order retrieveOrderById(UUID id) {
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id);
return orderJpaEntityMapper.mapJpaEntityToOrder(orderJpaEntity);
}
@Override
public Page<Order> retrieveOrdersByFilterAndSort(String naam, Pageable pageable) {
Specification<OrderJpaEntity> specification = Specification.where(naam == null ? null : (Specification<OrderJpaEntity>) ((root, query, builder) -> builder.like(root.get("naam"), "%" + naam + "%")));
return orderRepository.findAll(specification, PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort()))
.map(orderJpaEntityMapper::mapJpaEntityToOrder);
}
@Override
public void createOrder(Order order) {
int year = order.getDatum().getYear();
OrderJpaEntity orderJpaEntity = new OrderJpaEntity();
orderJpaEntity.setUuid(order.getOrderId());
orderJpaEntity.setOrderType(order.getOrderType());
orderJpaEntity.setNaam(order.getNaam());
orderJpaEntity.setOpmerkingen(order.getOpmerkingen());
orderJpaEntity.setDatum(order.getDatum());
orderJpaEntity.setJaar(year);
orderJpaEntity.setKlantId(order.getKlantId());
orderJpaEntity.setReparatieNummer(order.getReparatieNummer());
orderJpaEntity.setOrderNummer(order.getOrderNummer());
orderJpaEntity.setSequence(decideOnSequence(order));
orderRepository.save(orderJpaEntity);
}
@Override
public void updateOrder(Order order) {
int year = order.getDatum().getYear();
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId());
orderJpaEntity.setOrderType(order.getOrderType());
orderJpaEntity.setNaam(order.getNaam());
orderJpaEntity.setOpmerkingen(order.getOpmerkingen());
orderJpaEntity.setDatum(order.getDatum());
orderJpaEntity.setJaar(year);
orderJpaEntity.setKlantId(order.getKlantId());
orderJpaEntity.setReparatieNummer(order.getReparatieNummer());
orderJpaEntity.setOrderNummer(order.getOrderNummer());
orderJpaEntity.setSequence(decideOnSequence(order));
orderRepository.save(orderJpaEntity);
}
@Override
public void deleteOrder(UUID id) {
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id);
orderRepository.delete(orderJpaEntity);
}
private OrderJpaEntity getOrderJpaEntityById(UUID id) {
return orderRepository.findByUuid(id).orElseThrow(() -> new EntityNotFoundException(String.format("Order with uuid %s doesn't exist", id)));
}
private int decideOnSequence(Order order){
int year = order.getDatum().getYear();
int sequence = 0;
OrderType orderType = order.getOrderType();
//Enkel voor facturen, anders 0
if(orderType==OrderType.FACTUUR){
//Enkel wanneer er nog geen orderNummer bestaat, maken we een nieuwe sequence aan
if(order.getOrderNummer()!=null) {
Optional<OrderJpaEntity> factuur = orderRepository.findTopByJaarOrderBySequenceDesc(year);
int sequenceLastFactuur = 0;
if (!factuur.isEmpty()) {
sequenceLastFactuur = factuur.get().getSequence();
sequence = sequenceLastFactuur + 1;
}else{
//Wanneer er<SUF>
sequence = 1;
}
}else{
//Anders blijft de sequence dezelfde
OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId());
sequence = orderJpaEntity.getSequence();
}
}
return sequence;
}
}
|
200231_39 | /**
* Copyright (c) 2010-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
// in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
// in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
// in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
// in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperature";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperature";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung Betriebsart
TYPE_COOLING_OPERATION_MODE {
{
command = "cooling_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung AT-Freigabe
TYPE_COOLING_RELEASE_TEMPERATURE {
{
command = "cooling_release_temperature";
itemClass = NumberItem.class;
}
},
// in german Solltemp MK1
TYPE_COOLING_INLET_TEMP {
{
command = "cooling_inlet_temperature";
itemClass = NumberItem.class;
}
},
// in german AT-Überschreitung
TYPE_COOLING_START_AFTER_HOURS {
{
command = "cooling_start_hours";
itemClass = NumberItem.class;
}
},
// in german AT-Unterschreitung
TYPE_COOLING_STOP_AFTER_HOURS {
{
command = "cooling_stop_hours";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'");
}
} | FlorianSW/openhab | bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java | 3,172 | // in german Solltemp MK1 | line_comment | nl | /**
* Copyright (c) 2010-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
// in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
// in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
// in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
// in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperature";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperature";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung Betriebsart
TYPE_COOLING_OPERATION_MODE {
{
command = "cooling_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung AT-Freigabe
TYPE_COOLING_RELEASE_TEMPERATURE {
{
command = "cooling_release_temperature";
itemClass = NumberItem.class;
}
},
// in german<SUF>
TYPE_COOLING_INLET_TEMP {
{
command = "cooling_inlet_temperature";
itemClass = NumberItem.class;
}
},
// in german AT-Überschreitung
TYPE_COOLING_START_AFTER_HOURS {
{
command = "cooling_start_hours";
itemClass = NumberItem.class;
}
},
// in german AT-Unterschreitung
TYPE_COOLING_STOP_AFTER_HOURS {
{
command = "cooling_stop_hours";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'");
}
} |
176061_55 | /*
* Class to manage and to get Airport Information
*/
package parser;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class to manage and to get Airport Information
*
* @author yoann
*/
public class Aeroport {
/**
* ICAO Code
*/
private String icaoCode;
/**
* Airport ICAO Identifier
*/
private String identifiant;
/**
* ATA/IATA Designator
*/
private String ataIata;
/**
* Speed Limit Altitude
*/
private String speedLimitAltitude;
/**
* Longest Runway
*/
private String longestRwy;
/**
* IFR Capability
*/
private String ifr;
/**
* Longway Surface Code
*/
private String longRwy;
/**
* Airport Reference Pt Latitude
*/
private String latitude;
/**
* Airport Reference Pt Longitude
*/
private String longitude;
/**
* Magnetic Variation
*/
private String magneticVariation;
/**
* Airport Elevation
*/
private String elevation;
/**
* Speed Limit
*/
private String speedLimit;
/**
* Recommended Navaid
*/
private Balises receiverVhf;
/**
* Transitions Altitude
*/
private String transAltitude;
/**
* Transition Level
*/
private String transLevel;
/**
* Public Military Indicator
*/
private String publicMilitaire;
/**
* Time Zone
*/
private String timeZone;
/**
* DayLight Indicator
*/
private String dayTime;
/**
* Magnetic/True Indicator
*/
private String MTInd;
/**
* Datum Code
*/
private String datum;
/**
* Airport Name
*/
private String airportName;
/**
* FIR Identifier
*/
private String firIdentifier;
/**
* UIR Identifier
*/
private String uirIdentifier;
/**
* Start/End Indicator
*/
private String sEIndicator;
/**
* Start/End Date
*/
private String sEDate;
/**
* Controlled A/S Indicator
*/
private String asInd;
/**
* Controlled A/S Arpt Ident
*/
private String asArptIdent;
/**
* Controlled A/S Arpt ICAO
*/
private String asIcaoCode;
/**
* Constructor Airport
*
* @param icaoCode Icao Code
* @param identifiant Airport ICAO Identifier
* @param ataIata ATA/IATA Designator
* @param speedLimitAltitude Speed Limit Altitude
* @param longestRwy Longest Runway
* @param ifr IFR Capability
* @param longRwy Longest Runway Surface Code
* @param latitude Airport Reference Pt Latitude
* @param longitude Aiport Reference Pt Longitude
* @param magneticVariation Magnetic Variation
* @param elevation Airport Elevation
* @param speedLimit Speed Limit
* @param receiverVhf Recommend Navaid
* @param transAltitude Transition Altitude
* @param transLevel Transition Level
* @param publicMilitaire Public/Military Indicator
* @param timeZone Time Zone
* @param dayTime Daylight Indicator
* @param MTInd Magnetic/True Indicator
* @param datum Datum Code
* @param airportName Airport Name
* @param firIdentifier FIR Identifier
* @param uirIdentifier UIR Identifier
* @param sEIndicator Start/End Indicator
* @param sEDate Start/End Date
* @param asInd Controlled A/S Indicator
* @param asArptIdent Controlled A/S Arpt Ident
* @param asIcaoCode Controlled A/S Arpt ICAO
*/
public Aeroport(String icaoCode, String identifiant, String ataIata, String speedLimitAltitude, String longestRwy, String ifr,
String longRwy, String latitude, String longitude, String magneticVariation, String elevation, String speedLimit,
Balises receiverVhf, String transAltitude, String transLevel, String publicMilitaire, String timeZone, String dayTime,
String MTInd, String datum, String airportName, String firIdentifier, String uirIdentifier, String sEIndicator,
String sEDate, String asInd, String asArptIdent, String asIcaoCode) {
this.icaoCode = icaoCode;
this.identifiant = identifiant;
this.ataIata = ataIata;
this.speedLimitAltitude = speedLimitAltitude;
this.longestRwy = longestRwy;
this.ifr = ifr;
this.longRwy = longRwy;
this.latitude = latitude;
this.longitude = longitude;
this.magneticVariation = magneticVariation;
this.elevation = elevation;
this.speedLimit = speedLimit;
this.receiverVhf = receiverVhf;
this.transAltitude = transAltitude;
this.transLevel = transLevel;
this.publicMilitaire = publicMilitaire;
this.timeZone = timeZone;
this.dayTime = dayTime;
this.MTInd = MTInd;
this.datum = datum;
this.airportName = airportName;
this.firIdentifier = firIdentifier;
this.uirIdentifier = uirIdentifier;
this.sEIndicator = sEIndicator;
this.sEDate = sEDate;
this.asInd = asInd;
this.asArptIdent = asArptIdent;
this.asIcaoCode = asIcaoCode;
}
/**
* Constructor of airport
*
* @param identifiant Airport ICAO Identifier
*/
public Aeroport(String identifiant) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = ParserGlobal.createSql();
pst = con.prepareStatement("SELECT * from aeroport where identifiant like ?");
pst.setString(1, identifiant);
rs = pst.executeQuery();
if (rs.next()) { // il y a un resultat
this.icaoCode = rs.getString("icaoCode");
this.identifiant = rs.getString("identifiant");
this.ataIata = rs.getString("ataIata");
this.speedLimitAltitude = rs.getString("speedLimitAltitude");
this.longestRwy = rs.getString("longestRwy");
this.ifr = rs.getString("ifr");
this.longRwy = rs.getString("longRwy");
this.latitude = rs.getString("latitude");
this.longitude = rs.getString("longitude");
this.magneticVariation = rs.getString("magneticVariation");
this.elevation = rs.getString("elevation");
this.speedLimit = rs.getString("speedLimit");
this.receiverVhf = new Balises(rs.getString("recVhf"), rs.getString("icaoCodeVhf"));
this.transAltitude = rs.getString("transAltitude");
this.transLevel = rs.getString("transLevel");
this.publicMilitaire = rs.getString("publicMilitaire");
this.timeZone = rs.getString("timeZone");
this.dayTime = rs.getString("dayTime");
this.MTInd = rs.getString("MTInd");
this.datum = rs.getString("datum");
this.airportName = rs.getString("airportName");
this.firIdentifier = rs.getString("firIdentifier");
this.uirIdentifier = rs.getString("uirIdentifier");
this.sEIndicator = rs.getString("sEIndicator");
this.sEDate = rs.getString("sEDate");
this.asInd = rs.getString("asInd");
this.asArptIdent = rs.getString("asArptIdent");
this.asIcaoCode = rs.getString("asIcaoCode");
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Get Magnetic/True Indicator
*
* @return L'indicateur
*/
public String getMTind() {
return this.MTInd;
}
/**
* Get Airport Name
*
* @return The Airport Name
*/
public String getAirportName() {
return this.airportName;
}
/**
* Get Controlled A/S Identifier
*
* @return Controlled A/S Identifier
*/
public String getAsAirportIdent() {
return this.asArptIdent;
}
/**
* Get Controlled A/S Arpt ICAO
*
* @return Controlled A/S Arpt ICAO
*/
public String getAsIcaoCode() {
return this.asIcaoCode;
}
/**
* Get Controlled A/S Indicator
*
* @return Controlled A/S Indicator
*/
public String getAsInd() {
return this.asInd;
}
/**
* Get ATA/IATA designator
*
* @return ATA/IATA designator
*/
public String getAtaIata() {
return this.ataIata;
}
/**
* Get Datum code
*
* @return Datum Code
*/
public String getDatum() {
return this.datum;
}
/**
* Get DayLight indicator
*
* @return DayLight Indicator
*/
public String getDayTime() {
return this.datum;
}
/**
* Get Airport Elevation
*
* @return Altitude
*/
public String getElevation() {
return this.elevation;
}
/**
* Get FIR Identifier
*
* @return FIR Identifier
*/
public String getFirIdentifier() {
return this.firIdentifier;
}
/**
* Get Icao Code Airport
*
* @return Icao Code
*/
public String getIcaoCode() {
return this.icaoCode;
}
/**
* Get Airport ICAO Identifier
*
* @return Aiport ICAO Identifier
*/
public String getIdentifiant() {
return this.identifiant;
}
/**
* Get IFR Capability
*
* @return IFR Capability
*/
public String getIfr() {
return this.ifr;
}
/**
* Get Airport Reference Pt Latitude
*
* @return Latitude
*/
public String getLatitude() {
return this.latitude;
}
/**
* Get the Longest Runway Surface Code
*
* @return the runway number
*/
public String getLongRwy() {
return this.longRwy;
}
/**
* Get the Longest Runway
*
* @return runway Number
*/
public String getLongestRwy() {
return this.longestRwy;
}
/**
* Get Airport Reference Pt Longitude
*
* @return Longitude
*/
public String getLongitude() {
return this.longitude;
}
/**
* Get Magnetic Variation
*
* @return magnetic Variation
*/
public String getMagneticVariation() {
return this.magneticVariation;
}
/**
* Get Public/Military Indicator
*
* @return Indicator
*/
public String getPublicMilitaire() {
return this.publicMilitaire;
}
/**
* Get Recommended navaid
*
* @return Name of the recommended Navaid
*/
public Balises getReceiverVhf() {
return this.receiverVhf;
}
/**
* Get Start/End Date
*
* @return Start/End Date
*/
public String getSEDate() {
return this.sEDate;
}
/**
* Get Start/End Indicator
*
* @return Start/End Indicator
*/
public String getSEIndicator() {
return this.sEIndicator;
}
/**
* Get Speed Limit
*
* @return Speed Limit
*/
public String getSpeedLimit() {
return this.speedLimit;
}
/**
* Get Speed Limit Altitude
*
* @return Speed Limit Altitude
*/
public String getSpeedLimitAltitude() {
return this.speedLimitAltitude;
}
/**
* Get Time Zone
*
* @return Time Zone
*/
public String getTimeZone() {
return this.timeZone;
}
/**
* Get Transition Altitude
*
* @return Transition Altitude
*/
public String getTransAltitude() {
return this.transAltitude;
}
/**
* Get Transition Level
*
* @return Transition Level
*/
public String getTransLevel() {
return this.transLevel;
}
/**
* Get UIR Identifier
*
* @return UIR Identifier
*/
public String getUirIdentifier() {
return this.uirIdentifier;
}
/**
* Display Airport informations in a text file
*
* @param fw
* @throws IOException
*/
public void afficherAeroport(OutputStreamWriter fw) throws IOException {
fw.write("Airport ICAO Identifier : " + this.identifiant + "\n");
fw.write("Airport Name : " + this.airportName + "\n");
fw.write("ATA/IATA Designator : " + this.ataIata + "\n");
fw.write("Datum Code : " + this.datum + "\n");
fw.write("Time Zone : " + this.timeZone + "\n");
fw.write("DayLight Indicator : " + this.dayTime + "\n");
fw.write("Airport Elevation : " + this.elevation + "\n");
fw.write("FIR Identifier : " + this.firIdentifier + "\n");
fw.write("IFR Capability : " + this.ifr + "\n");
fw.write("Airport Reference Pt. Latitude : " + this.latitude + "\n");
fw.write("Longest Runway Surface Code : " + this.longRwy + "\n");
fw.write("Longest Runway : " + this.longestRwy + "\n");
fw.write("Airport Reference Pt. Longitude : " + this.longitude + "\n");
fw.write("Magnetic/True Indicator : " + this.MTInd + "\n");
fw.write("Magnetic Variations : " + this.magneticVariation + "\n");
fw.write("Public/Military Indicator : " + this.publicMilitaire + "\n");
fw.write("Start/End Date : " + this.sEDate + "\n");
fw.write("Start/End Indicator : " + this.sEIndicator + "\n");
fw.write("Speed Limit : " + this.speedLimit + "\n");
fw.write("Speed Limit Altitude : " + this.speedLimitAltitude + "\n");
fw.write("Time Zone : " + this.timeZone + "\n");
fw.write("Transitions Altitude : " + this.transAltitude + "\n");
fw.write("Transition Level : " + this.transLevel + "\n");
fw.write("UIR Identifier : " + this.uirIdentifier + "\n");
}
/**
* Add a new record in the SQL Airport Table
*
* @param con DataBase Connection
* @param icaoCode Icao Code of the Airport
* @param identifiant Airport ICAO Identifier
* @param ataIata ATA/IATA Designator
* @param speedLimitAltitude Speed Limit Altitude
* @param longestRwy Longest Runway
* @param ifr IFR Capability
* @param longRwy Longest Runway Surface Code
* @param latitude Airport Reference Pt Latitude
* @param longitude Airport Reference Pt Longitude
* @param magneticVariation Magnetic Variations
* @param elevation Airport Elevation
* @param speedLimit Speed Limit
* @param recVhf Recommended Navaid
* @param icaoCodeVhf Icao Code of Recommended Navaid
* @param transAltitude Transition Altitude
* @param transLevel Transition Level
* @param publicMilitaire Public/Military Indicator
* @param timeZone Time Zone
* @param dayTime DayLight Indicator
* @param MTInd Magnetic/True Indicator
* @param datum Datum Code
* @param airportName Airport Name
*/
protected static void addSql(Connection con, String icaoCode, String identifiant, String ataIata, String speedLimitAltitude, String longestRwy, String ifr,
String longRwy, String latitude, String longitude, String magneticVariation, String elevation, String speedLimit, String recVhf,
String icaoCodeVhf, String transAltitude, String transLevel, String publicMilitaire, String timeZone, String dayTime, String MTInd,
String datum, String airportName) {
PreparedStatement pst = null;
try {
String stm = "INSERT INTO aeroport (icaoCode, identifiant, ataIata, speedLimitAltitude, longestRwy, ifr, longRwy, latitude, longitude,magneticVariation,elevation,speedLimit,recVhf,icaoCodeVhf,transAltitude,transLevel,publicMilitaire,timeZone,dayTime,MTInd,datum, airportName) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pst = con.prepareStatement(stm);
pst.setString(1, icaoCode);
pst.setString(2, identifiant);
pst.setString(3, ataIata);
pst.setString(4, speedLimitAltitude);
pst.setString(5, longestRwy);
pst.setString(6, ifr);
pst.setString(7, longRwy);
pst.setString(8, latitude);
pst.setString(9, longitude);
pst.setString(10, magneticVariation);
pst.setString(11, elevation);
pst.setString(12, speedLimit);
pst.setString(13, recVhf);
pst.setString(14, icaoCodeVhf);
pst.setString(15, transAltitude);
pst.setString(16, transLevel);
pst.setString(17, publicMilitaire);
pst.setString(18, timeZone);
pst.setString(19, dayTime);
pst.setString(20, MTInd);
pst.setString(21, datum);
pst.setString(22, airportName);
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Update the airport record by adding Continuation informations
*
* @param con DataBase Connection
* @param firIdentifier FIR Identifier
* @param uirIdentifier UIR Identifier
* @param sEIndicator Start/End Indicator
* @param sEdate Start/End Date
* @param asInd Controlled A/S Indicator
* @param asArptIdent Controlled A/S Airport Indentifier
* @param asIcaoCode Controlled A/S ICAO Code
* @param id Id of the airport record
*/
protected static void addSqlContinuation(Connection con, String firIdentifier, String uirIdentifier, String sEIndicator, String sEdate,
String asInd, String asArptIdent, String asIcaoCode, int id) {
PreparedStatement pst = null;
try {
String stm = "UPDATE aeroport set firIdentifier= ?, uirIdentifier= ?, sEIndicator= ?, sEdate= ?, asInd= ?, asArptIdent= ?, asIcaoCode= ? WHERE id=?";
pst = con.prepareStatement(stm);
pst.setString(1, firIdentifier);
pst.setString(2, uirIdentifier);
pst.setString(3, sEIndicator);
pst.setString(4, sEdate);
pst.setString(5, asInd);
pst.setString(6, asArptIdent);
pst.setString(7, asIcaoCode);
pst.setInt(8, id);
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Ckeck if the airport exists in the SQL database
*
* @param aeroport Airport ICAO Identifier
* @return True or False
*/
public static boolean isPresent(String aeroport) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
boolean result = false;
try {
con = ParserGlobal.createSql();
pst = con.prepareStatement("SELECT count(*) from aeroport where identifiant=?");
pst.setString(1, aeroport);
rs = pst.executeQuery();
if (rs != null && rs.next()) {
result = (rs.getInt(1) >= 1);
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
return result;
}
/**
* Return the ICAO Code of an Airport
*
* @param aeroport ICAO Airport Identifier
* @return An ArrayList of ICAO Code
*/
public static ArrayList<String> listAirport(String aeroport) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
ArrayList<String> a = new ArrayList<>();
try {
con = ParserGlobal.createSql();
pst = con.prepareStatement("SELECT icaoCode from aeroport where identifiant=?");
pst.setString(1, aeroport);
rs = pst.executeQuery();
while (rs.next()) {
a.add(rs.getString(1));
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
return a;
}
/**
* Return the id of the last airport record in the database
*
* @param con DataBase Connection
* @return The id of the last airport record in the database
*/
protected static int lastRecord(Connection con) {
PreparedStatement pst = null;
ResultSet rs = null;
int result = 0;
try {
pst = con.prepareStatement("SELECT max(id) from aeroport");
rs = pst.executeQuery();
if (rs != null && rs.next()) {
result = rs.getInt(1);
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
return result;
}
}
| FlorianSan/FMS | NavDB/InitDatabase/src/parser/Aeroport.java | 7,451 | /**
* Get Speed Limit
*
* @return Speed Limit
*/ | block_comment | nl | /*
* Class to manage and to get Airport Information
*/
package parser;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class to manage and to get Airport Information
*
* @author yoann
*/
public class Aeroport {
/**
* ICAO Code
*/
private String icaoCode;
/**
* Airport ICAO Identifier
*/
private String identifiant;
/**
* ATA/IATA Designator
*/
private String ataIata;
/**
* Speed Limit Altitude
*/
private String speedLimitAltitude;
/**
* Longest Runway
*/
private String longestRwy;
/**
* IFR Capability
*/
private String ifr;
/**
* Longway Surface Code
*/
private String longRwy;
/**
* Airport Reference Pt Latitude
*/
private String latitude;
/**
* Airport Reference Pt Longitude
*/
private String longitude;
/**
* Magnetic Variation
*/
private String magneticVariation;
/**
* Airport Elevation
*/
private String elevation;
/**
* Speed Limit
*/
private String speedLimit;
/**
* Recommended Navaid
*/
private Balises receiverVhf;
/**
* Transitions Altitude
*/
private String transAltitude;
/**
* Transition Level
*/
private String transLevel;
/**
* Public Military Indicator
*/
private String publicMilitaire;
/**
* Time Zone
*/
private String timeZone;
/**
* DayLight Indicator
*/
private String dayTime;
/**
* Magnetic/True Indicator
*/
private String MTInd;
/**
* Datum Code
*/
private String datum;
/**
* Airport Name
*/
private String airportName;
/**
* FIR Identifier
*/
private String firIdentifier;
/**
* UIR Identifier
*/
private String uirIdentifier;
/**
* Start/End Indicator
*/
private String sEIndicator;
/**
* Start/End Date
*/
private String sEDate;
/**
* Controlled A/S Indicator
*/
private String asInd;
/**
* Controlled A/S Arpt Ident
*/
private String asArptIdent;
/**
* Controlled A/S Arpt ICAO
*/
private String asIcaoCode;
/**
* Constructor Airport
*
* @param icaoCode Icao Code
* @param identifiant Airport ICAO Identifier
* @param ataIata ATA/IATA Designator
* @param speedLimitAltitude Speed Limit Altitude
* @param longestRwy Longest Runway
* @param ifr IFR Capability
* @param longRwy Longest Runway Surface Code
* @param latitude Airport Reference Pt Latitude
* @param longitude Aiport Reference Pt Longitude
* @param magneticVariation Magnetic Variation
* @param elevation Airport Elevation
* @param speedLimit Speed Limit
* @param receiverVhf Recommend Navaid
* @param transAltitude Transition Altitude
* @param transLevel Transition Level
* @param publicMilitaire Public/Military Indicator
* @param timeZone Time Zone
* @param dayTime Daylight Indicator
* @param MTInd Magnetic/True Indicator
* @param datum Datum Code
* @param airportName Airport Name
* @param firIdentifier FIR Identifier
* @param uirIdentifier UIR Identifier
* @param sEIndicator Start/End Indicator
* @param sEDate Start/End Date
* @param asInd Controlled A/S Indicator
* @param asArptIdent Controlled A/S Arpt Ident
* @param asIcaoCode Controlled A/S Arpt ICAO
*/
public Aeroport(String icaoCode, String identifiant, String ataIata, String speedLimitAltitude, String longestRwy, String ifr,
String longRwy, String latitude, String longitude, String magneticVariation, String elevation, String speedLimit,
Balises receiverVhf, String transAltitude, String transLevel, String publicMilitaire, String timeZone, String dayTime,
String MTInd, String datum, String airportName, String firIdentifier, String uirIdentifier, String sEIndicator,
String sEDate, String asInd, String asArptIdent, String asIcaoCode) {
this.icaoCode = icaoCode;
this.identifiant = identifiant;
this.ataIata = ataIata;
this.speedLimitAltitude = speedLimitAltitude;
this.longestRwy = longestRwy;
this.ifr = ifr;
this.longRwy = longRwy;
this.latitude = latitude;
this.longitude = longitude;
this.magneticVariation = magneticVariation;
this.elevation = elevation;
this.speedLimit = speedLimit;
this.receiverVhf = receiverVhf;
this.transAltitude = transAltitude;
this.transLevel = transLevel;
this.publicMilitaire = publicMilitaire;
this.timeZone = timeZone;
this.dayTime = dayTime;
this.MTInd = MTInd;
this.datum = datum;
this.airportName = airportName;
this.firIdentifier = firIdentifier;
this.uirIdentifier = uirIdentifier;
this.sEIndicator = sEIndicator;
this.sEDate = sEDate;
this.asInd = asInd;
this.asArptIdent = asArptIdent;
this.asIcaoCode = asIcaoCode;
}
/**
* Constructor of airport
*
* @param identifiant Airport ICAO Identifier
*/
public Aeroport(String identifiant) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = ParserGlobal.createSql();
pst = con.prepareStatement("SELECT * from aeroport where identifiant like ?");
pst.setString(1, identifiant);
rs = pst.executeQuery();
if (rs.next()) { // il y a un resultat
this.icaoCode = rs.getString("icaoCode");
this.identifiant = rs.getString("identifiant");
this.ataIata = rs.getString("ataIata");
this.speedLimitAltitude = rs.getString("speedLimitAltitude");
this.longestRwy = rs.getString("longestRwy");
this.ifr = rs.getString("ifr");
this.longRwy = rs.getString("longRwy");
this.latitude = rs.getString("latitude");
this.longitude = rs.getString("longitude");
this.magneticVariation = rs.getString("magneticVariation");
this.elevation = rs.getString("elevation");
this.speedLimit = rs.getString("speedLimit");
this.receiverVhf = new Balises(rs.getString("recVhf"), rs.getString("icaoCodeVhf"));
this.transAltitude = rs.getString("transAltitude");
this.transLevel = rs.getString("transLevel");
this.publicMilitaire = rs.getString("publicMilitaire");
this.timeZone = rs.getString("timeZone");
this.dayTime = rs.getString("dayTime");
this.MTInd = rs.getString("MTInd");
this.datum = rs.getString("datum");
this.airportName = rs.getString("airportName");
this.firIdentifier = rs.getString("firIdentifier");
this.uirIdentifier = rs.getString("uirIdentifier");
this.sEIndicator = rs.getString("sEIndicator");
this.sEDate = rs.getString("sEDate");
this.asInd = rs.getString("asInd");
this.asArptIdent = rs.getString("asArptIdent");
this.asIcaoCode = rs.getString("asIcaoCode");
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Get Magnetic/True Indicator
*
* @return L'indicateur
*/
public String getMTind() {
return this.MTInd;
}
/**
* Get Airport Name
*
* @return The Airport Name
*/
public String getAirportName() {
return this.airportName;
}
/**
* Get Controlled A/S Identifier
*
* @return Controlled A/S Identifier
*/
public String getAsAirportIdent() {
return this.asArptIdent;
}
/**
* Get Controlled A/S Arpt ICAO
*
* @return Controlled A/S Arpt ICAO
*/
public String getAsIcaoCode() {
return this.asIcaoCode;
}
/**
* Get Controlled A/S Indicator
*
* @return Controlled A/S Indicator
*/
public String getAsInd() {
return this.asInd;
}
/**
* Get ATA/IATA designator
*
* @return ATA/IATA designator
*/
public String getAtaIata() {
return this.ataIata;
}
/**
* Get Datum code
*
* @return Datum Code
*/
public String getDatum() {
return this.datum;
}
/**
* Get DayLight indicator
*
* @return DayLight Indicator
*/
public String getDayTime() {
return this.datum;
}
/**
* Get Airport Elevation
*
* @return Altitude
*/
public String getElevation() {
return this.elevation;
}
/**
* Get FIR Identifier
*
* @return FIR Identifier
*/
public String getFirIdentifier() {
return this.firIdentifier;
}
/**
* Get Icao Code Airport
*
* @return Icao Code
*/
public String getIcaoCode() {
return this.icaoCode;
}
/**
* Get Airport ICAO Identifier
*
* @return Aiport ICAO Identifier
*/
public String getIdentifiant() {
return this.identifiant;
}
/**
* Get IFR Capability
*
* @return IFR Capability
*/
public String getIfr() {
return this.ifr;
}
/**
* Get Airport Reference Pt Latitude
*
* @return Latitude
*/
public String getLatitude() {
return this.latitude;
}
/**
* Get the Longest Runway Surface Code
*
* @return the runway number
*/
public String getLongRwy() {
return this.longRwy;
}
/**
* Get the Longest Runway
*
* @return runway Number
*/
public String getLongestRwy() {
return this.longestRwy;
}
/**
* Get Airport Reference Pt Longitude
*
* @return Longitude
*/
public String getLongitude() {
return this.longitude;
}
/**
* Get Magnetic Variation
*
* @return magnetic Variation
*/
public String getMagneticVariation() {
return this.magneticVariation;
}
/**
* Get Public/Military Indicator
*
* @return Indicator
*/
public String getPublicMilitaire() {
return this.publicMilitaire;
}
/**
* Get Recommended navaid
*
* @return Name of the recommended Navaid
*/
public Balises getReceiverVhf() {
return this.receiverVhf;
}
/**
* Get Start/End Date
*
* @return Start/End Date
*/
public String getSEDate() {
return this.sEDate;
}
/**
* Get Start/End Indicator
*
* @return Start/End Indicator
*/
public String getSEIndicator() {
return this.sEIndicator;
}
/**
* Get Speed Limit<SUF>*/
public String getSpeedLimit() {
return this.speedLimit;
}
/**
* Get Speed Limit Altitude
*
* @return Speed Limit Altitude
*/
public String getSpeedLimitAltitude() {
return this.speedLimitAltitude;
}
/**
* Get Time Zone
*
* @return Time Zone
*/
public String getTimeZone() {
return this.timeZone;
}
/**
* Get Transition Altitude
*
* @return Transition Altitude
*/
public String getTransAltitude() {
return this.transAltitude;
}
/**
* Get Transition Level
*
* @return Transition Level
*/
public String getTransLevel() {
return this.transLevel;
}
/**
* Get UIR Identifier
*
* @return UIR Identifier
*/
public String getUirIdentifier() {
return this.uirIdentifier;
}
/**
* Display Airport informations in a text file
*
* @param fw
* @throws IOException
*/
public void afficherAeroport(OutputStreamWriter fw) throws IOException {
fw.write("Airport ICAO Identifier : " + this.identifiant + "\n");
fw.write("Airport Name : " + this.airportName + "\n");
fw.write("ATA/IATA Designator : " + this.ataIata + "\n");
fw.write("Datum Code : " + this.datum + "\n");
fw.write("Time Zone : " + this.timeZone + "\n");
fw.write("DayLight Indicator : " + this.dayTime + "\n");
fw.write("Airport Elevation : " + this.elevation + "\n");
fw.write("FIR Identifier : " + this.firIdentifier + "\n");
fw.write("IFR Capability : " + this.ifr + "\n");
fw.write("Airport Reference Pt. Latitude : " + this.latitude + "\n");
fw.write("Longest Runway Surface Code : " + this.longRwy + "\n");
fw.write("Longest Runway : " + this.longestRwy + "\n");
fw.write("Airport Reference Pt. Longitude : " + this.longitude + "\n");
fw.write("Magnetic/True Indicator : " + this.MTInd + "\n");
fw.write("Magnetic Variations : " + this.magneticVariation + "\n");
fw.write("Public/Military Indicator : " + this.publicMilitaire + "\n");
fw.write("Start/End Date : " + this.sEDate + "\n");
fw.write("Start/End Indicator : " + this.sEIndicator + "\n");
fw.write("Speed Limit : " + this.speedLimit + "\n");
fw.write("Speed Limit Altitude : " + this.speedLimitAltitude + "\n");
fw.write("Time Zone : " + this.timeZone + "\n");
fw.write("Transitions Altitude : " + this.transAltitude + "\n");
fw.write("Transition Level : " + this.transLevel + "\n");
fw.write("UIR Identifier : " + this.uirIdentifier + "\n");
}
/**
* Add a new record in the SQL Airport Table
*
* @param con DataBase Connection
* @param icaoCode Icao Code of the Airport
* @param identifiant Airport ICAO Identifier
* @param ataIata ATA/IATA Designator
* @param speedLimitAltitude Speed Limit Altitude
* @param longestRwy Longest Runway
* @param ifr IFR Capability
* @param longRwy Longest Runway Surface Code
* @param latitude Airport Reference Pt Latitude
* @param longitude Airport Reference Pt Longitude
* @param magneticVariation Magnetic Variations
* @param elevation Airport Elevation
* @param speedLimit Speed Limit
* @param recVhf Recommended Navaid
* @param icaoCodeVhf Icao Code of Recommended Navaid
* @param transAltitude Transition Altitude
* @param transLevel Transition Level
* @param publicMilitaire Public/Military Indicator
* @param timeZone Time Zone
* @param dayTime DayLight Indicator
* @param MTInd Magnetic/True Indicator
* @param datum Datum Code
* @param airportName Airport Name
*/
protected static void addSql(Connection con, String icaoCode, String identifiant, String ataIata, String speedLimitAltitude, String longestRwy, String ifr,
String longRwy, String latitude, String longitude, String magneticVariation, String elevation, String speedLimit, String recVhf,
String icaoCodeVhf, String transAltitude, String transLevel, String publicMilitaire, String timeZone, String dayTime, String MTInd,
String datum, String airportName) {
PreparedStatement pst = null;
try {
String stm = "INSERT INTO aeroport (icaoCode, identifiant, ataIata, speedLimitAltitude, longestRwy, ifr, longRwy, latitude, longitude,magneticVariation,elevation,speedLimit,recVhf,icaoCodeVhf,transAltitude,transLevel,publicMilitaire,timeZone,dayTime,MTInd,datum, airportName) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pst = con.prepareStatement(stm);
pst.setString(1, icaoCode);
pst.setString(2, identifiant);
pst.setString(3, ataIata);
pst.setString(4, speedLimitAltitude);
pst.setString(5, longestRwy);
pst.setString(6, ifr);
pst.setString(7, longRwy);
pst.setString(8, latitude);
pst.setString(9, longitude);
pst.setString(10, magneticVariation);
pst.setString(11, elevation);
pst.setString(12, speedLimit);
pst.setString(13, recVhf);
pst.setString(14, icaoCodeVhf);
pst.setString(15, transAltitude);
pst.setString(16, transLevel);
pst.setString(17, publicMilitaire);
pst.setString(18, timeZone);
pst.setString(19, dayTime);
pst.setString(20, MTInd);
pst.setString(21, datum);
pst.setString(22, airportName);
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Update the airport record by adding Continuation informations
*
* @param con DataBase Connection
* @param firIdentifier FIR Identifier
* @param uirIdentifier UIR Identifier
* @param sEIndicator Start/End Indicator
* @param sEdate Start/End Date
* @param asInd Controlled A/S Indicator
* @param asArptIdent Controlled A/S Airport Indentifier
* @param asIcaoCode Controlled A/S ICAO Code
* @param id Id of the airport record
*/
protected static void addSqlContinuation(Connection con, String firIdentifier, String uirIdentifier, String sEIndicator, String sEdate,
String asInd, String asArptIdent, String asIcaoCode, int id) {
PreparedStatement pst = null;
try {
String stm = "UPDATE aeroport set firIdentifier= ?, uirIdentifier= ?, sEIndicator= ?, sEdate= ?, asInd= ?, asArptIdent= ?, asIcaoCode= ? WHERE id=?";
pst = con.prepareStatement(stm);
pst.setString(1, firIdentifier);
pst.setString(2, uirIdentifier);
pst.setString(3, sEIndicator);
pst.setString(4, sEdate);
pst.setString(5, asInd);
pst.setString(6, asArptIdent);
pst.setString(7, asIcaoCode);
pst.setInt(8, id);
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Ckeck if the airport exists in the SQL database
*
* @param aeroport Airport ICAO Identifier
* @return True or False
*/
public static boolean isPresent(String aeroport) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
boolean result = false;
try {
con = ParserGlobal.createSql();
pst = con.prepareStatement("SELECT count(*) from aeroport where identifiant=?");
pst.setString(1, aeroport);
rs = pst.executeQuery();
if (rs != null && rs.next()) {
result = (rs.getInt(1) >= 1);
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
return result;
}
/**
* Return the ICAO Code of an Airport
*
* @param aeroport ICAO Airport Identifier
* @return An ArrayList of ICAO Code
*/
public static ArrayList<String> listAirport(String aeroport) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
ArrayList<String> a = new ArrayList<>();
try {
con = ParserGlobal.createSql();
pst = con.prepareStatement("SELECT icaoCode from aeroport where identifiant=?");
pst.setString(1, aeroport);
rs = pst.executeQuery();
while (rs.next()) {
a.add(rs.getString(1));
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
return a;
}
/**
* Return the id of the last airport record in the database
*
* @param con DataBase Connection
* @return The id of the last airport record in the database
*/
protected static int lastRecord(Connection con) {
PreparedStatement pst = null;
ResultSet rs = null;
int result = 0;
try {
pst = con.prepareStatement("SELECT max(id) from aeroport");
rs = pst.executeQuery();
if (rs != null && rs.next()) {
result = rs.getInt(1);
}
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException ex) {
Logger.getLogger(Aeroport.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
return result;
}
}
|
33452_6 | /*
* Copyright 2018 flow.ci
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flowci.core.job.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.flowci.common.helper.StringHelper;
import com.flowci.core.agent.domain.Agent;
import com.flowci.core.agent.domain.AgentProfile;
import com.flowci.core.common.domain.Mongoable;
import com.flowci.common.domain.StringVars;
import com.flowci.common.domain.Vars;
import com.flowci.store.Pathable;
import com.google.common.collect.ImmutableSet;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* @author yang
*/
@Document(collection = "job")
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@CompoundIndex(
name = "index_job_flowid_and_buildnum",
def = "{'flowId': 1, 'buildNumber': 1}",
unique = true
)
public class Job extends Mongoable implements Pathable {
public enum Trigger {
/**
* Scheduler trigger
*/
SCHEDULER,
/**
* Api trigger
*/
API,
/**
* Manual trigger
*/
MANUAL,
/**
* Git push event
*/
PUSH,
/**
* Git PR opened event
*/
PR_OPENED,
/**
* Git PR merged event
*/
PR_MERGED,
/**
* Git tag event
*/
TAG,
/**
* Git patchset trigger
*/
PATCHSET
}
public enum Status {
/**
* Initial job state
*/
PENDING(0),
/**
* Job created with yaml and steps
*/
CREATED(1),
/**
* Loading the yaml from git repo
*/
LOADING(2),
/**
* Been put to job queue
*/
QUEUED(3),
/**
* Agent take over the job, and been start to execute
*/
RUNNING(4),
/**
* Job will be cancelled, but waiting for response from agent
*/
CANCELLING(5),
/**
* Job been executed
*/
SUCCESS(10),
/**
* Job been executed but failure
*/
FAILURE(10),
/**
* Job been cancelled by user
*/
CANCELLED(10),
/**
* Job execution time been over the expiredAt
*/
TIMEOUT(10);
@Getter
private int order;
Status(int order) {
this.order = order;
}
}
/**
* Agent snapshot
*/
@Getter
@Setter
public static class AgentSnapshot {
private String name;
private String os;
private int cpuNum;
private double cpuUsage;
private int totalMemory;
private int freeMemory;
private int totalDisk;
private int freeDisk;
}
public static Pathable path(Long buildNumber) {
Job job = new Job();
job.setBuildNumber(buildNumber);
return job;
}
public static final Set<Status> FINISH_STATUS = ImmutableSet.<Status>builder()
.add(Status.TIMEOUT)
.add(Status.CANCELLED)
.add(Status.FAILURE)
.add(Status.SUCCESS)
.build();
private static final SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public static final Integer MinPriority = 1;
public static final Integer MaxPriority = 255;
/**
* Job key is generated from {flow id}-{build number}
*/
@Indexed(name = "index_job_key", unique = true)
private String key;
@Indexed(name = "index_job_flow_id", partialFilter = "{ flowId: {$exists: true} }")
private String flowId;
private String flowName;
private Long buildNumber;
private Trigger trigger;
private Status status = Status.PENDING;
private boolean onPostSteps = false;
// agent id : info
private Map<String, AgentSnapshot> snapshots = new HashMap<>();
// current running steps
private Set<String> currentPath = new HashSet<>();
private Vars<String> context = new StringVars();
private String message;
private Integer priority = MinPriority;
private boolean isYamlFromRepo;
private String yamlRepoBranch;
/**
* Step timeout in seconds
*/
private int timeout = 1800;
/**
* Timeout while job queuing
*/
private int expire = 1800;
/**
* Date that job will be expired at
*/
private Date expireAt;
/**
* Real execution start at
*/
private Date startAt;
/**
* Real execution finish at
*/
private Date finishAt;
private int numOfArtifact = 0;
public void setExpire(int expire) {
this.expire = expire;
Instant expireAt = Instant.now().plus(expire, ChronoUnit.SECONDS);
this.expireAt = (Date.from(expireAt));
}
@JsonIgnore
public boolean isRunning() {
return status == Status.RUNNING;
}
@JsonIgnore
public boolean isCancelling() {
return status == Status.CANCELLING;
}
@JsonIgnore
public boolean isDone() {
return FINISH_STATUS.contains(status);
}
@JsonIgnore
public boolean isFailure() {
return status == Status.FAILURE;
}
@JsonIgnore
public String getQueueName() {
return "flow.q." + flowId + ".job";
}
@JsonIgnore
@Override
public String pathName() {
return getBuildNumber().toString();
}
@JsonIgnore
public String startAtInStr() {
if (Objects.isNull(this.startAt)) {
return StringHelper.EMPTY;
}
return DateFormat.format(this.startAt);
}
@JsonIgnore
public String finishAtInStr() {
if (Objects.isNull(this.finishAt)) {
return StringHelper.EMPTY;
}
return DateFormat.format(this.finishAt);
}
@JsonIgnore
public Long getDurationInSeconds() {
if (this.startAt == null || this.finishAt == null) {
return 0L;
}
return Duration.between(this.startAt.toInstant(), this.finishAt.toInstant()).getSeconds();
}
public boolean isExpired() {
Instant expireAt = getExpireAt().toInstant();
return Instant.now().compareTo(expireAt) > 0;
}
public void addAgentSnapshot(Agent agent, AgentProfile profile) {
AgentSnapshot s = new AgentSnapshot();
s.name = agent.getName();
s.os = agent.getOs().name();
s.cpuNum = profile.getCpuNum();
s.cpuUsage = profile.getCpuUsage();
s.totalMemory = profile.getTotalMemory();
s.freeMemory = profile.getFreeMemory();
s.totalDisk = profile.getTotalDisk();
s.freeDisk = profile.getFreeDisk();
this.snapshots.put(agent.getId(), s);
}
public Job resetCurrentPath() {
this.currentPath.clear();
return this;
}
public void addToCurrentPath(Step step) {
this.currentPath.add(step.getNodePath());
}
public void removeFromCurrentPath(Step step) {
this.currentPath.remove(step.getNodePath());
}
}
| FlowCI/flow-core-x | core/src/main/java/com/flowci/core/job/domain/Job.java | 2,326 | /**
* Git PR opened event
*/ | block_comment | nl | /*
* Copyright 2018 flow.ci
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flowci.core.job.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.flowci.common.helper.StringHelper;
import com.flowci.core.agent.domain.Agent;
import com.flowci.core.agent.domain.AgentProfile;
import com.flowci.core.common.domain.Mongoable;
import com.flowci.common.domain.StringVars;
import com.flowci.common.domain.Vars;
import com.flowci.store.Pathable;
import com.google.common.collect.ImmutableSet;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* @author yang
*/
@Document(collection = "job")
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@CompoundIndex(
name = "index_job_flowid_and_buildnum",
def = "{'flowId': 1, 'buildNumber': 1}",
unique = true
)
public class Job extends Mongoable implements Pathable {
public enum Trigger {
/**
* Scheduler trigger
*/
SCHEDULER,
/**
* Api trigger
*/
API,
/**
* Manual trigger
*/
MANUAL,
/**
* Git push event
*/
PUSH,
/**
* Git PR opened<SUF>*/
PR_OPENED,
/**
* Git PR merged event
*/
PR_MERGED,
/**
* Git tag event
*/
TAG,
/**
* Git patchset trigger
*/
PATCHSET
}
public enum Status {
/**
* Initial job state
*/
PENDING(0),
/**
* Job created with yaml and steps
*/
CREATED(1),
/**
* Loading the yaml from git repo
*/
LOADING(2),
/**
* Been put to job queue
*/
QUEUED(3),
/**
* Agent take over the job, and been start to execute
*/
RUNNING(4),
/**
* Job will be cancelled, but waiting for response from agent
*/
CANCELLING(5),
/**
* Job been executed
*/
SUCCESS(10),
/**
* Job been executed but failure
*/
FAILURE(10),
/**
* Job been cancelled by user
*/
CANCELLED(10),
/**
* Job execution time been over the expiredAt
*/
TIMEOUT(10);
@Getter
private int order;
Status(int order) {
this.order = order;
}
}
/**
* Agent snapshot
*/
@Getter
@Setter
public static class AgentSnapshot {
private String name;
private String os;
private int cpuNum;
private double cpuUsage;
private int totalMemory;
private int freeMemory;
private int totalDisk;
private int freeDisk;
}
public static Pathable path(Long buildNumber) {
Job job = new Job();
job.setBuildNumber(buildNumber);
return job;
}
public static final Set<Status> FINISH_STATUS = ImmutableSet.<Status>builder()
.add(Status.TIMEOUT)
.add(Status.CANCELLED)
.add(Status.FAILURE)
.add(Status.SUCCESS)
.build();
private static final SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public static final Integer MinPriority = 1;
public static final Integer MaxPriority = 255;
/**
* Job key is generated from {flow id}-{build number}
*/
@Indexed(name = "index_job_key", unique = true)
private String key;
@Indexed(name = "index_job_flow_id", partialFilter = "{ flowId: {$exists: true} }")
private String flowId;
private String flowName;
private Long buildNumber;
private Trigger trigger;
private Status status = Status.PENDING;
private boolean onPostSteps = false;
// agent id : info
private Map<String, AgentSnapshot> snapshots = new HashMap<>();
// current running steps
private Set<String> currentPath = new HashSet<>();
private Vars<String> context = new StringVars();
private String message;
private Integer priority = MinPriority;
private boolean isYamlFromRepo;
private String yamlRepoBranch;
/**
* Step timeout in seconds
*/
private int timeout = 1800;
/**
* Timeout while job queuing
*/
private int expire = 1800;
/**
* Date that job will be expired at
*/
private Date expireAt;
/**
* Real execution start at
*/
private Date startAt;
/**
* Real execution finish at
*/
private Date finishAt;
private int numOfArtifact = 0;
public void setExpire(int expire) {
this.expire = expire;
Instant expireAt = Instant.now().plus(expire, ChronoUnit.SECONDS);
this.expireAt = (Date.from(expireAt));
}
@JsonIgnore
public boolean isRunning() {
return status == Status.RUNNING;
}
@JsonIgnore
public boolean isCancelling() {
return status == Status.CANCELLING;
}
@JsonIgnore
public boolean isDone() {
return FINISH_STATUS.contains(status);
}
@JsonIgnore
public boolean isFailure() {
return status == Status.FAILURE;
}
@JsonIgnore
public String getQueueName() {
return "flow.q." + flowId + ".job";
}
@JsonIgnore
@Override
public String pathName() {
return getBuildNumber().toString();
}
@JsonIgnore
public String startAtInStr() {
if (Objects.isNull(this.startAt)) {
return StringHelper.EMPTY;
}
return DateFormat.format(this.startAt);
}
@JsonIgnore
public String finishAtInStr() {
if (Objects.isNull(this.finishAt)) {
return StringHelper.EMPTY;
}
return DateFormat.format(this.finishAt);
}
@JsonIgnore
public Long getDurationInSeconds() {
if (this.startAt == null || this.finishAt == null) {
return 0L;
}
return Duration.between(this.startAt.toInstant(), this.finishAt.toInstant()).getSeconds();
}
public boolean isExpired() {
Instant expireAt = getExpireAt().toInstant();
return Instant.now().compareTo(expireAt) > 0;
}
public void addAgentSnapshot(Agent agent, AgentProfile profile) {
AgentSnapshot s = new AgentSnapshot();
s.name = agent.getName();
s.os = agent.getOs().name();
s.cpuNum = profile.getCpuNum();
s.cpuUsage = profile.getCpuUsage();
s.totalMemory = profile.getTotalMemory();
s.freeMemory = profile.getFreeMemory();
s.totalDisk = profile.getTotalDisk();
s.freeDisk = profile.getFreeDisk();
this.snapshots.put(agent.getId(), s);
}
public Job resetCurrentPath() {
this.currentPath.clear();
return this;
}
public void addToCurrentPath(Step step) {
this.currentPath.add(step.getNodePath());
}
public void removeFromCurrentPath(Step step) {
this.currentPath.remove(step.getNodePath());
}
}
|
143227_48 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.Localizer;
import org.apache.jasper.compiler.TagPluginManager;
import org.apache.jasper.compiler.TldCache;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* A class to hold all init parameters specific to the JSP engine.
*
* @author Anil K. Vijendran
* @author Hans Bergsten
* @author Pierre Delisle
*/
public final class EmbeddedServletOptions implements Options {
// Logger
private final Log log = LogFactory.getLog(EmbeddedServletOptions.class);
private Properties settings = new Properties();
/**
* Is Jasper being used in development mode?
*/
private boolean development = true;
/**
* Should Ant fork its java compiles of JSP pages.
*/
public boolean fork = true;
/**
* Do you want to keep the generated Java files around?
*/
private boolean keepGenerated = true;
/**
* Should template text that consists entirely of whitespace be removed?
*/
private boolean trimSpaces = false;
/**
* Determines whether tag handler pooling is enabled.
*/
private boolean isPoolingEnabled = true;
/**
* Do you want support for "mapped" files? This will generate
* servlet that has a print statement per line of the JSP file.
* This seems like a really nice feature to have for debugging.
*/
private boolean mappedFile = true;
/**
* Do we want to include debugging information in the class file?
*/
private boolean classDebugInfo = true;
/**
* Background compile thread check interval in seconds.
*/
private int checkInterval = 0;
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
private boolean isSmapSuppressed = false;
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
private boolean isSmapDumped = false;
/**
* Are Text strings to be generated as char arrays?
*/
private boolean genStringAsCharArray = false;
private boolean errorOnUseBeanInvalidClassAttribute = true;
/**
* I want to see my generated servlets. Which directory are they
* in?
*/
private File scratchDir;
/**
* Need to have this as is for versions 4 and 5 of IE. Can be set from
* the initParams so if it changes in the future all that is needed is
* to have a jsp initParam of type ieClassId="<value>"
*/
private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
/**
* What classpath should I use while compiling generated servlets?
*/
private String classpath = null;
/**
* Compiler to use.
*/
private String compiler = null;
/**
* Compiler target VM.
*/
private String compilerTargetVM = "1.7";
/**
* The compiler source VM.
*/
private String compilerSourceVM = "1.7";
/**
* The compiler class name.
*/
private String compilerClassName = null;
/**
* Cache for the TLD URIs, resource paths and parsed files.
*/
private TldCache tldCache = null;
/**
* Jsp config information
*/
private JspConfig jspConfig = null;
/**
* TagPluginManager
*/
private TagPluginManager tagPluginManager = null;
/**
* Java platform encoding to generate the JSP
* page servlet.
*/
private String javaEncoding = "UTF8";
/**
* Modification test interval.
*/
private int modificationTestInterval = 4;
/**
* Is re-compilation attempted immediately after a failure?
*/
private boolean recompileOnFail = false;
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
private boolean xpoweredBy;
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
private boolean displaySourceFragment = true;
/**
* The maximum number of loaded jsps per web-application. If there are more
* jsps loaded, they will be unloaded.
*/
private int maxLoadedJsps = -1;
/**
* The idle time in seconds after which a JSP is unloaded.
* If unset or less or equal than 0, no jsps are unloaded.
*/
private int jspIdleTimeout = -1;
/**
* Should JSP.1.6 be applied strictly to attributes defined using scriptlet
* expressions?
*/
private boolean strictQuoteEscaping = true;
/**
* When EL is used in JSP attribute values, should the rules for quoting of
* attributes described in JSP.1.6 be applied to the expression?
*/
private boolean quoteAttributeEL = true;
public String getProperty(String name ) {
return settings.getProperty( name );
}
public void setProperty(String name, String value ) {
if (name != null && value != null){
settings.setProperty( name, value );
}
}
public void setQuoteAttributeEL(boolean b) {
this.quoteAttributeEL = b;
}
@Override
public boolean getQuoteAttributeEL() {
return quoteAttributeEL;
}
/**
* Are we keeping generated code around?
*/
@Override
public boolean getKeepGenerated() {
return keepGenerated;
}
/**
* Should template text that consists entirely of whitespace be removed?
*/
@Override
public boolean getTrimSpaces() {
return trimSpaces;
}
@Override
public boolean isPoolingEnabled() {
return isPoolingEnabled;
}
/**
* Are we supporting HTML mapped servlets?
*/
@Override
public boolean getMappedFile() {
return mappedFile;
}
/**
* Should class files be compiled with debug information?
*/
@Override
public boolean getClassDebugInfo() {
return classDebugInfo;
}
/**
* Background JSP compile thread check interval
*/
@Override
public int getCheckInterval() {
return checkInterval;
}
/**
* Modification test interval.
*/
@Override
public int getModificationTestInterval() {
return modificationTestInterval;
}
/**
* Re-compile on failure.
*/
@Override
public boolean getRecompileOnFail() {
return recompileOnFail;
}
/**
* Is Jasper being used in development mode?
*/
@Override
public boolean getDevelopment() {
return development;
}
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
@Override
public boolean isSmapSuppressed() {
return isSmapSuppressed;
}
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
@Override
public boolean isSmapDumped() {
return isSmapDumped;
}
/**
* Are Text strings to be generated as char arrays?
*/
@Override
public boolean genStringAsCharArray() {
return this.genStringAsCharArray;
}
/**
* Class ID for use in the plugin tag when the browser is IE.
*/
@Override
public String getIeClassId() {
return ieClassId;
}
/**
* What is my scratch dir?
*/
@Override
public File getScratchDir() {
return scratchDir;
}
/**
* What classpath should I use while compiling the servlets
* generated from JSP files?
*/
@Override
public String getClassPath() {
return classpath;
}
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
@Override
public boolean isXpoweredBy() {
return xpoweredBy;
}
/**
* Compiler to use.
*/
@Override
public String getCompiler() {
return compiler;
}
/**
* @see Options#getCompilerTargetVM
*/
@Override
public String getCompilerTargetVM() {
return compilerTargetVM;
}
/**
* @see Options#getCompilerSourceVM
*/
@Override
public String getCompilerSourceVM() {
return compilerSourceVM;
}
/**
* Java compiler class to use.
*/
@Override
public String getCompilerClassName() {
return compilerClassName;
}
@Override
public boolean getErrorOnUseBeanInvalidClassAttribute() {
return errorOnUseBeanInvalidClassAttribute;
}
public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
errorOnUseBeanInvalidClassAttribute = b;
}
@Override
public TldCache getTldCache() {
return tldCache;
}
public void setTldCache(TldCache tldCache) {
this.tldCache = tldCache;
}
@Override
public String getJavaEncoding() {
return javaEncoding;
}
@Override
public boolean getFork() {
return fork;
}
@Override
public JspConfig getJspConfig() {
return jspConfig;
}
@Override
public TagPluginManager getTagPluginManager() {
return tagPluginManager;
}
@Override
public boolean isCaching() {
return false;
}
@Override
public Map<String, TagLibraryInfo> getCache() {
return null;
}
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
@Override
public boolean getDisplaySourceFragment() {
return displaySourceFragment;
}
/**
* Should jsps be unloaded if to many are loaded?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getMaxLoadedJsps() {
return maxLoadedJsps;
}
/**
* Should any jsps be unloaded when being idle for this time in seconds?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getJspIdleTimeout() {
return jspIdleTimeout;
}
@Override
public boolean getStrictQuoteEscaping() {
return strictQuoteEscaping;
}
/**
* Create an EmbeddedServletOptions object using data available from
* ServletConfig and ServletContext.
* @param config The Servlet config
* @param context The Servlet context
*/
public EmbeddedServletOptions(ServletConfig config,
ServletContext context) {
Enumeration<String> enumeration=config.getInitParameterNames();
while( enumeration.hasMoreElements() ) {
String k=enumeration.nextElement();
String v=config.getInitParameter( k );
setProperty( k, v);
}
String keepgen = config.getInitParameter("keepgenerated");
if (keepgen != null) {
if (keepgen.equalsIgnoreCase("true")) {
this.keepGenerated = true;
} else if (keepgen.equalsIgnoreCase("false")) {
this.keepGenerated = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.keepgen"));
}
}
}
String trimsp = config.getInitParameter("trimSpaces");
if (trimsp != null) {
if (trimsp.equalsIgnoreCase("true")) {
trimSpaces = true;
} else if (trimsp.equalsIgnoreCase("false")) {
trimSpaces = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.trimspaces"));
}
}
}
this.isPoolingEnabled = true;
String poolingEnabledParam
= config.getInitParameter("enablePooling");
if (poolingEnabledParam != null
&& !poolingEnabledParam.equalsIgnoreCase("true")) {
if (poolingEnabledParam.equalsIgnoreCase("false")) {
this.isPoolingEnabled = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.enablePooling"));
}
}
}
String mapFile = config.getInitParameter("mappedfile");
if (mapFile != null) {
if (mapFile.equalsIgnoreCase("true")) {
this.mappedFile = true;
} else if (mapFile.equalsIgnoreCase("false")) {
this.mappedFile = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.mappedFile"));
}
}
}
String debugInfo = config.getInitParameter("classdebuginfo");
if (debugInfo != null) {
if (debugInfo.equalsIgnoreCase("true")) {
this.classDebugInfo = true;
} else if (debugInfo.equalsIgnoreCase("false")) {
this.classDebugInfo = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.classDebugInfo"));
}
}
}
String checkInterval = config.getInitParameter("checkInterval");
if (checkInterval != null) {
try {
this.checkInterval = Integer.parseInt(checkInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.checkInterval"));
}
}
}
String modificationTestInterval = config.getInitParameter("modificationTestInterval");
if (modificationTestInterval != null) {
try {
this.modificationTestInterval = Integer.parseInt(modificationTestInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval"));
}
}
}
String recompileOnFail = config.getInitParameter("recompileOnFail");
if (recompileOnFail != null) {
if (recompileOnFail.equalsIgnoreCase("true")) {
this.recompileOnFail = true;
} else if (recompileOnFail.equalsIgnoreCase("false")) {
this.recompileOnFail = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.recompileOnFail"));
}
}
}
String development = config.getInitParameter("development");
if (development != null) {
if (development.equalsIgnoreCase("true")) {
this.development = true;
} else if (development.equalsIgnoreCase("false")) {
this.development = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.development"));
}
}
}
String suppressSmap = config.getInitParameter("suppressSmap");
if (suppressSmap != null) {
if (suppressSmap.equalsIgnoreCase("true")) {
isSmapSuppressed = true;
} else if (suppressSmap.equalsIgnoreCase("false")) {
isSmapSuppressed = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.suppressSmap"));
}
}
}
String dumpSmap = config.getInitParameter("dumpSmap");
if (dumpSmap != null) {
if (dumpSmap.equalsIgnoreCase("true")) {
isSmapDumped = true;
} else if (dumpSmap.equalsIgnoreCase("false")) {
isSmapDumped = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.dumpSmap"));
}
}
}
String genCharArray = config.getInitParameter("genStringAsCharArray");
if (genCharArray != null) {
if (genCharArray.equalsIgnoreCase("true")) {
genStringAsCharArray = true;
} else if (genCharArray.equalsIgnoreCase("false")) {
genStringAsCharArray = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.genchararray"));
}
}
}
String errBeanClass =
config.getInitParameter("errorOnUseBeanInvalidClassAttribute");
if (errBeanClass != null) {
if (errBeanClass.equalsIgnoreCase("true")) {
errorOnUseBeanInvalidClassAttribute = true;
} else if (errBeanClass.equalsIgnoreCase("false")) {
errorOnUseBeanInvalidClassAttribute = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.errBean"));
}
}
}
String ieClassId = config.getInitParameter("ieClassId");
if (ieClassId != null)
this.ieClassId = ieClassId;
String classpath = config.getInitParameter("classpath");
if (classpath != null)
this.classpath = classpath;
/*
* scratchdir
*/
String dir = config.getInitParameter("scratchdir");
if (dir != null && Constants.IS_SECURITY_ENABLED) {
log.info(Localizer.getMessage("jsp.info.ignoreSetting", "scratchdir", dir));
dir = null;
}
if (dir != null) {
scratchDir = new File(dir);
} else {
// First try the Servlet 2.2 javax.servlet.context.tempdir property
scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR);
if (scratchDir == null) {
// Not running in a Servlet 2.2 container.
// Try to get the JDK 1.2 java.io.tmpdir property
dir = System.getProperty("java.io.tmpdir");
if (dir != null)
scratchDir = new File(dir);
}
}
if (this.scratchDir == null) {
log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir"));
return;
}
if (!(scratchDir.exists() && scratchDir.canRead() &&
scratchDir.canWrite() && scratchDir.isDirectory()))
log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir",
scratchDir.getAbsolutePath()));
this.compiler = config.getInitParameter("compiler");
String compilerTargetVM = config.getInitParameter("compilerTargetVM");
if(compilerTargetVM != null) {
this.compilerTargetVM = compilerTargetVM;
}
String compilerSourceVM = config.getInitParameter("compilerSourceVM");
if(compilerSourceVM != null) {
this.compilerSourceVM = compilerSourceVM;
}
String javaEncoding = config.getInitParameter("javaEncoding");
if (javaEncoding != null) {
this.javaEncoding = javaEncoding;
}
String compilerClassName = config.getInitParameter("compilerClassName");
if (compilerClassName != null) {
this.compilerClassName = compilerClassName;
}
String fork = config.getInitParameter("fork");
if (fork != null) {
if (fork.equalsIgnoreCase("true")) {
this.fork = true;
} else if (fork.equalsIgnoreCase("false")) {
this.fork = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.fork"));
}
}
}
String xpoweredBy = config.getInitParameter("xpoweredBy");
if (xpoweredBy != null) {
if (xpoweredBy.equalsIgnoreCase("true")) {
this.xpoweredBy = true;
} else if (xpoweredBy.equalsIgnoreCase("false")) {
this.xpoweredBy = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.xpoweredBy"));
}
}
}
String displaySourceFragment = config.getInitParameter("displaySourceFragment");
if (displaySourceFragment != null) {
if (displaySourceFragment.equalsIgnoreCase("true")) {
this.displaySourceFragment = true;
} else if (displaySourceFragment.equalsIgnoreCase("false")) {
this.displaySourceFragment = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment"));
}
}
}
String maxLoadedJsps = config.getInitParameter("maxLoadedJsps");
if (maxLoadedJsps != null) {
try {
this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps));
}
}
}
String jspIdleTimeout = config.getInitParameter("jspIdleTimeout");
if (jspIdleTimeout != null) {
try {
this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout));
}
}
}
String strictQuoteEscaping = config.getInitParameter("strictQuoteEscaping");
if (strictQuoteEscaping != null) {
if (strictQuoteEscaping.equalsIgnoreCase("true")) {
this.strictQuoteEscaping = true;
} else if (strictQuoteEscaping.equalsIgnoreCase("false")) {
this.strictQuoteEscaping = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.strictQuoteEscaping"));
}
}
}
String quoteAttributeEL = config.getInitParameter("quoteAttributeEL");
if (quoteAttributeEL != null) {
if (quoteAttributeEL.equalsIgnoreCase("true")) {
this.quoteAttributeEL = true;
} else if (quoteAttributeEL.equalsIgnoreCase("false")) {
this.quoteAttributeEL = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL"));
}
}
}
// Setup the global Tag Libraries location cache for this
// web-application.
tldCache = TldCache.getInstance(context);
// Setup the jsp config info for this web app.
jspConfig = new JspConfig(context);
// Create a Tag plugin instance
tagPluginManager = new TagPluginManager(context);
}
}
| FlowerL/tomcat8.5-src-dev | java/org/apache/jasper/EmbeddedServletOptions.java | 6,555 | /**
* @see Options#getCompilerTargetVM
*/ | block_comment | nl | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.Localizer;
import org.apache.jasper.compiler.TagPluginManager;
import org.apache.jasper.compiler.TldCache;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* A class to hold all init parameters specific to the JSP engine.
*
* @author Anil K. Vijendran
* @author Hans Bergsten
* @author Pierre Delisle
*/
public final class EmbeddedServletOptions implements Options {
// Logger
private final Log log = LogFactory.getLog(EmbeddedServletOptions.class);
private Properties settings = new Properties();
/**
* Is Jasper being used in development mode?
*/
private boolean development = true;
/**
* Should Ant fork its java compiles of JSP pages.
*/
public boolean fork = true;
/**
* Do you want to keep the generated Java files around?
*/
private boolean keepGenerated = true;
/**
* Should template text that consists entirely of whitespace be removed?
*/
private boolean trimSpaces = false;
/**
* Determines whether tag handler pooling is enabled.
*/
private boolean isPoolingEnabled = true;
/**
* Do you want support for "mapped" files? This will generate
* servlet that has a print statement per line of the JSP file.
* This seems like a really nice feature to have for debugging.
*/
private boolean mappedFile = true;
/**
* Do we want to include debugging information in the class file?
*/
private boolean classDebugInfo = true;
/**
* Background compile thread check interval in seconds.
*/
private int checkInterval = 0;
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
private boolean isSmapSuppressed = false;
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
private boolean isSmapDumped = false;
/**
* Are Text strings to be generated as char arrays?
*/
private boolean genStringAsCharArray = false;
private boolean errorOnUseBeanInvalidClassAttribute = true;
/**
* I want to see my generated servlets. Which directory are they
* in?
*/
private File scratchDir;
/**
* Need to have this as is for versions 4 and 5 of IE. Can be set from
* the initParams so if it changes in the future all that is needed is
* to have a jsp initParam of type ieClassId="<value>"
*/
private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
/**
* What classpath should I use while compiling generated servlets?
*/
private String classpath = null;
/**
* Compiler to use.
*/
private String compiler = null;
/**
* Compiler target VM.
*/
private String compilerTargetVM = "1.7";
/**
* The compiler source VM.
*/
private String compilerSourceVM = "1.7";
/**
* The compiler class name.
*/
private String compilerClassName = null;
/**
* Cache for the TLD URIs, resource paths and parsed files.
*/
private TldCache tldCache = null;
/**
* Jsp config information
*/
private JspConfig jspConfig = null;
/**
* TagPluginManager
*/
private TagPluginManager tagPluginManager = null;
/**
* Java platform encoding to generate the JSP
* page servlet.
*/
private String javaEncoding = "UTF8";
/**
* Modification test interval.
*/
private int modificationTestInterval = 4;
/**
* Is re-compilation attempted immediately after a failure?
*/
private boolean recompileOnFail = false;
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
private boolean xpoweredBy;
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
private boolean displaySourceFragment = true;
/**
* The maximum number of loaded jsps per web-application. If there are more
* jsps loaded, they will be unloaded.
*/
private int maxLoadedJsps = -1;
/**
* The idle time in seconds after which a JSP is unloaded.
* If unset or less or equal than 0, no jsps are unloaded.
*/
private int jspIdleTimeout = -1;
/**
* Should JSP.1.6 be applied strictly to attributes defined using scriptlet
* expressions?
*/
private boolean strictQuoteEscaping = true;
/**
* When EL is used in JSP attribute values, should the rules for quoting of
* attributes described in JSP.1.6 be applied to the expression?
*/
private boolean quoteAttributeEL = true;
public String getProperty(String name ) {
return settings.getProperty( name );
}
public void setProperty(String name, String value ) {
if (name != null && value != null){
settings.setProperty( name, value );
}
}
public void setQuoteAttributeEL(boolean b) {
this.quoteAttributeEL = b;
}
@Override
public boolean getQuoteAttributeEL() {
return quoteAttributeEL;
}
/**
* Are we keeping generated code around?
*/
@Override
public boolean getKeepGenerated() {
return keepGenerated;
}
/**
* Should template text that consists entirely of whitespace be removed?
*/
@Override
public boolean getTrimSpaces() {
return trimSpaces;
}
@Override
public boolean isPoolingEnabled() {
return isPoolingEnabled;
}
/**
* Are we supporting HTML mapped servlets?
*/
@Override
public boolean getMappedFile() {
return mappedFile;
}
/**
* Should class files be compiled with debug information?
*/
@Override
public boolean getClassDebugInfo() {
return classDebugInfo;
}
/**
* Background JSP compile thread check interval
*/
@Override
public int getCheckInterval() {
return checkInterval;
}
/**
* Modification test interval.
*/
@Override
public int getModificationTestInterval() {
return modificationTestInterval;
}
/**
* Re-compile on failure.
*/
@Override
public boolean getRecompileOnFail() {
return recompileOnFail;
}
/**
* Is Jasper being used in development mode?
*/
@Override
public boolean getDevelopment() {
return development;
}
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
@Override
public boolean isSmapSuppressed() {
return isSmapSuppressed;
}
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
@Override
public boolean isSmapDumped() {
return isSmapDumped;
}
/**
* Are Text strings to be generated as char arrays?
*/
@Override
public boolean genStringAsCharArray() {
return this.genStringAsCharArray;
}
/**
* Class ID for use in the plugin tag when the browser is IE.
*/
@Override
public String getIeClassId() {
return ieClassId;
}
/**
* What is my scratch dir?
*/
@Override
public File getScratchDir() {
return scratchDir;
}
/**
* What classpath should I use while compiling the servlets
* generated from JSP files?
*/
@Override
public String getClassPath() {
return classpath;
}
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
@Override
public boolean isXpoweredBy() {
return xpoweredBy;
}
/**
* Compiler to use.
*/
@Override
public String getCompiler() {
return compiler;
}
/**
* @see Options#getCompilerTargetVM
<SUF>*/
@Override
public String getCompilerTargetVM() {
return compilerTargetVM;
}
/**
* @see Options#getCompilerSourceVM
*/
@Override
public String getCompilerSourceVM() {
return compilerSourceVM;
}
/**
* Java compiler class to use.
*/
@Override
public String getCompilerClassName() {
return compilerClassName;
}
@Override
public boolean getErrorOnUseBeanInvalidClassAttribute() {
return errorOnUseBeanInvalidClassAttribute;
}
public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
errorOnUseBeanInvalidClassAttribute = b;
}
@Override
public TldCache getTldCache() {
return tldCache;
}
public void setTldCache(TldCache tldCache) {
this.tldCache = tldCache;
}
@Override
public String getJavaEncoding() {
return javaEncoding;
}
@Override
public boolean getFork() {
return fork;
}
@Override
public JspConfig getJspConfig() {
return jspConfig;
}
@Override
public TagPluginManager getTagPluginManager() {
return tagPluginManager;
}
@Override
public boolean isCaching() {
return false;
}
@Override
public Map<String, TagLibraryInfo> getCache() {
return null;
}
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
@Override
public boolean getDisplaySourceFragment() {
return displaySourceFragment;
}
/**
* Should jsps be unloaded if to many are loaded?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getMaxLoadedJsps() {
return maxLoadedJsps;
}
/**
* Should any jsps be unloaded when being idle for this time in seconds?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getJspIdleTimeout() {
return jspIdleTimeout;
}
@Override
public boolean getStrictQuoteEscaping() {
return strictQuoteEscaping;
}
/**
* Create an EmbeddedServletOptions object using data available from
* ServletConfig and ServletContext.
* @param config The Servlet config
* @param context The Servlet context
*/
public EmbeddedServletOptions(ServletConfig config,
ServletContext context) {
Enumeration<String> enumeration=config.getInitParameterNames();
while( enumeration.hasMoreElements() ) {
String k=enumeration.nextElement();
String v=config.getInitParameter( k );
setProperty( k, v);
}
String keepgen = config.getInitParameter("keepgenerated");
if (keepgen != null) {
if (keepgen.equalsIgnoreCase("true")) {
this.keepGenerated = true;
} else if (keepgen.equalsIgnoreCase("false")) {
this.keepGenerated = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.keepgen"));
}
}
}
String trimsp = config.getInitParameter("trimSpaces");
if (trimsp != null) {
if (trimsp.equalsIgnoreCase("true")) {
trimSpaces = true;
} else if (trimsp.equalsIgnoreCase("false")) {
trimSpaces = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.trimspaces"));
}
}
}
this.isPoolingEnabled = true;
String poolingEnabledParam
= config.getInitParameter("enablePooling");
if (poolingEnabledParam != null
&& !poolingEnabledParam.equalsIgnoreCase("true")) {
if (poolingEnabledParam.equalsIgnoreCase("false")) {
this.isPoolingEnabled = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.enablePooling"));
}
}
}
String mapFile = config.getInitParameter("mappedfile");
if (mapFile != null) {
if (mapFile.equalsIgnoreCase("true")) {
this.mappedFile = true;
} else if (mapFile.equalsIgnoreCase("false")) {
this.mappedFile = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.mappedFile"));
}
}
}
String debugInfo = config.getInitParameter("classdebuginfo");
if (debugInfo != null) {
if (debugInfo.equalsIgnoreCase("true")) {
this.classDebugInfo = true;
} else if (debugInfo.equalsIgnoreCase("false")) {
this.classDebugInfo = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.classDebugInfo"));
}
}
}
String checkInterval = config.getInitParameter("checkInterval");
if (checkInterval != null) {
try {
this.checkInterval = Integer.parseInt(checkInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.checkInterval"));
}
}
}
String modificationTestInterval = config.getInitParameter("modificationTestInterval");
if (modificationTestInterval != null) {
try {
this.modificationTestInterval = Integer.parseInt(modificationTestInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval"));
}
}
}
String recompileOnFail = config.getInitParameter("recompileOnFail");
if (recompileOnFail != null) {
if (recompileOnFail.equalsIgnoreCase("true")) {
this.recompileOnFail = true;
} else if (recompileOnFail.equalsIgnoreCase("false")) {
this.recompileOnFail = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.recompileOnFail"));
}
}
}
String development = config.getInitParameter("development");
if (development != null) {
if (development.equalsIgnoreCase("true")) {
this.development = true;
} else if (development.equalsIgnoreCase("false")) {
this.development = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.development"));
}
}
}
String suppressSmap = config.getInitParameter("suppressSmap");
if (suppressSmap != null) {
if (suppressSmap.equalsIgnoreCase("true")) {
isSmapSuppressed = true;
} else if (suppressSmap.equalsIgnoreCase("false")) {
isSmapSuppressed = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.suppressSmap"));
}
}
}
String dumpSmap = config.getInitParameter("dumpSmap");
if (dumpSmap != null) {
if (dumpSmap.equalsIgnoreCase("true")) {
isSmapDumped = true;
} else if (dumpSmap.equalsIgnoreCase("false")) {
isSmapDumped = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.dumpSmap"));
}
}
}
String genCharArray = config.getInitParameter("genStringAsCharArray");
if (genCharArray != null) {
if (genCharArray.equalsIgnoreCase("true")) {
genStringAsCharArray = true;
} else if (genCharArray.equalsIgnoreCase("false")) {
genStringAsCharArray = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.genchararray"));
}
}
}
String errBeanClass =
config.getInitParameter("errorOnUseBeanInvalidClassAttribute");
if (errBeanClass != null) {
if (errBeanClass.equalsIgnoreCase("true")) {
errorOnUseBeanInvalidClassAttribute = true;
} else if (errBeanClass.equalsIgnoreCase("false")) {
errorOnUseBeanInvalidClassAttribute = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.errBean"));
}
}
}
String ieClassId = config.getInitParameter("ieClassId");
if (ieClassId != null)
this.ieClassId = ieClassId;
String classpath = config.getInitParameter("classpath");
if (classpath != null)
this.classpath = classpath;
/*
* scratchdir
*/
String dir = config.getInitParameter("scratchdir");
if (dir != null && Constants.IS_SECURITY_ENABLED) {
log.info(Localizer.getMessage("jsp.info.ignoreSetting", "scratchdir", dir));
dir = null;
}
if (dir != null) {
scratchDir = new File(dir);
} else {
// First try the Servlet 2.2 javax.servlet.context.tempdir property
scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR);
if (scratchDir == null) {
// Not running in a Servlet 2.2 container.
// Try to get the JDK 1.2 java.io.tmpdir property
dir = System.getProperty("java.io.tmpdir");
if (dir != null)
scratchDir = new File(dir);
}
}
if (this.scratchDir == null) {
log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir"));
return;
}
if (!(scratchDir.exists() && scratchDir.canRead() &&
scratchDir.canWrite() && scratchDir.isDirectory()))
log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir",
scratchDir.getAbsolutePath()));
this.compiler = config.getInitParameter("compiler");
String compilerTargetVM = config.getInitParameter("compilerTargetVM");
if(compilerTargetVM != null) {
this.compilerTargetVM = compilerTargetVM;
}
String compilerSourceVM = config.getInitParameter("compilerSourceVM");
if(compilerSourceVM != null) {
this.compilerSourceVM = compilerSourceVM;
}
String javaEncoding = config.getInitParameter("javaEncoding");
if (javaEncoding != null) {
this.javaEncoding = javaEncoding;
}
String compilerClassName = config.getInitParameter("compilerClassName");
if (compilerClassName != null) {
this.compilerClassName = compilerClassName;
}
String fork = config.getInitParameter("fork");
if (fork != null) {
if (fork.equalsIgnoreCase("true")) {
this.fork = true;
} else if (fork.equalsIgnoreCase("false")) {
this.fork = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.fork"));
}
}
}
String xpoweredBy = config.getInitParameter("xpoweredBy");
if (xpoweredBy != null) {
if (xpoweredBy.equalsIgnoreCase("true")) {
this.xpoweredBy = true;
} else if (xpoweredBy.equalsIgnoreCase("false")) {
this.xpoweredBy = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.xpoweredBy"));
}
}
}
String displaySourceFragment = config.getInitParameter("displaySourceFragment");
if (displaySourceFragment != null) {
if (displaySourceFragment.equalsIgnoreCase("true")) {
this.displaySourceFragment = true;
} else if (displaySourceFragment.equalsIgnoreCase("false")) {
this.displaySourceFragment = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment"));
}
}
}
String maxLoadedJsps = config.getInitParameter("maxLoadedJsps");
if (maxLoadedJsps != null) {
try {
this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps));
}
}
}
String jspIdleTimeout = config.getInitParameter("jspIdleTimeout");
if (jspIdleTimeout != null) {
try {
this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout));
}
}
}
String strictQuoteEscaping = config.getInitParameter("strictQuoteEscaping");
if (strictQuoteEscaping != null) {
if (strictQuoteEscaping.equalsIgnoreCase("true")) {
this.strictQuoteEscaping = true;
} else if (strictQuoteEscaping.equalsIgnoreCase("false")) {
this.strictQuoteEscaping = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.strictQuoteEscaping"));
}
}
}
String quoteAttributeEL = config.getInitParameter("quoteAttributeEL");
if (quoteAttributeEL != null) {
if (quoteAttributeEL.equalsIgnoreCase("true")) {
this.quoteAttributeEL = true;
} else if (quoteAttributeEL.equalsIgnoreCase("false")) {
this.quoteAttributeEL = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL"));
}
}
}
// Setup the global Tag Libraries location cache for this
// web-application.
tldCache = TldCache.getInstance(context);
// Setup the jsp config info for this web app.
jspConfig = new JspConfig(context);
// Create a Tag plugin instance
tagPluginManager = new TagPluginManager(context);
}
}
|
78671_0 | package app.qienuren.controller;
import app.qienuren.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import app.qienuren.Interface.TraineeService;
import app.qienuren.Interface.FormulierService;
import app.qienuren.Interface.TraineeRepository;
import app.qienuren.Interface.EmailService;
@Configuration
@EnableScheduling
@Service
@Transactional
public class MedewerkerService {
@Autowired
private TraineeService ts;
@Autowired
private InterneMedewerkerService ims;
@Autowired
private FormulierService fs;
@Autowired
private TraineeRepository traineeRepository;
@Autowired
private MedewerkerRepository medewerkerRepository;
@Autowired
private EmailService emailService;
private List<Medewerker> medewerkers;
private List<Trainee> trainees;
private List<InterneMedewerker> interneMedewerkers;
public ArrayList<Medewerker> voegTraineesEnInterneMedewerkersSamen(){
medewerkers = new ArrayList<>();
trainees = (List) ts.getAllTrainees();
interneMedewerkers = (List) ims.getAllInterneMedewerkers();
for (Trainee t : trainees) {
medewerkers.add(t);
}
for (InterneMedewerker i : interneMedewerkers) {
if (!(i.getType() == MedewerkerType.Admin)) {
medewerkers.add(i);
}
}
return (ArrayList<Medewerker>) medewerkers;
}
public void genereerLeegFormulierVoorAlleMedewerkers(){
ArrayList<Medewerker> deMedewerkers = voegTraineesEnInterneMedewerkersSamen();
for (Medewerker m : deMedewerkers) {
m.voegFormulierToe(fs.addNieuwFormulier(new Formulier(LocalDate.now().getMonthValue(), LocalDate.now().getYear())));
// Send email
// Arguments: Medewerker, Subject, Message(templated?)
// Medewerker fields nodig: Name, ?
emailService.sendWithFormulierStaatKlaarTemplate(m);
}
}
public Medewerker getMedewerkerById(long id){
System.out.println("Medewerker opgehaald - test Maandag");
return medewerkerRepository.findById(id).get();
}
} | FranciscoFreitas45/MicroRefact | app/Results/mauricedibbets1986__qienurenappgroep2/2/src/main/java/app/qienuren/controller/MedewerkerService.java | 754 | // Arguments: Medewerker, Subject, Message(templated?) | line_comment | nl | package app.qienuren.controller;
import app.qienuren.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import app.qienuren.Interface.TraineeService;
import app.qienuren.Interface.FormulierService;
import app.qienuren.Interface.TraineeRepository;
import app.qienuren.Interface.EmailService;
@Configuration
@EnableScheduling
@Service
@Transactional
public class MedewerkerService {
@Autowired
private TraineeService ts;
@Autowired
private InterneMedewerkerService ims;
@Autowired
private FormulierService fs;
@Autowired
private TraineeRepository traineeRepository;
@Autowired
private MedewerkerRepository medewerkerRepository;
@Autowired
private EmailService emailService;
private List<Medewerker> medewerkers;
private List<Trainee> trainees;
private List<InterneMedewerker> interneMedewerkers;
public ArrayList<Medewerker> voegTraineesEnInterneMedewerkersSamen(){
medewerkers = new ArrayList<>();
trainees = (List) ts.getAllTrainees();
interneMedewerkers = (List) ims.getAllInterneMedewerkers();
for (Trainee t : trainees) {
medewerkers.add(t);
}
for (InterneMedewerker i : interneMedewerkers) {
if (!(i.getType() == MedewerkerType.Admin)) {
medewerkers.add(i);
}
}
return (ArrayList<Medewerker>) medewerkers;
}
public void genereerLeegFormulierVoorAlleMedewerkers(){
ArrayList<Medewerker> deMedewerkers = voegTraineesEnInterneMedewerkersSamen();
for (Medewerker m : deMedewerkers) {
m.voegFormulierToe(fs.addNieuwFormulier(new Formulier(LocalDate.now().getMonthValue(), LocalDate.now().getYear())));
// Send email
// Arguments: Medewerker,<SUF>
// Medewerker fields nodig: Name, ?
emailService.sendWithFormulierStaatKlaarTemplate(m);
}
}
public Medewerker getMedewerkerById(long id){
System.out.println("Medewerker opgehaald - test Maandag");
return medewerkerRepository.findById(id).get();
}
} |
76925_0 | package com.example.hangman;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
//words lezen van xml
//words stoppen in sql lite
//design pattern, design doc aanpassen
//features saven
public class Game extends Activity {
private Button RestartButton;
private Button ExitButton;
private Button highscoreButton;
private Button settings;
private Gameplay gameLogic;
private Settings gameSettings;
private Exit gameExit;
private Highscores gameHighscores;
private SaveData defaultSetting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
defaultSetting = new SaveData(this);
defaultSetting.saveSettings("7", "10");
gameLogic = new Gameplay(this);
RestartButton = (Button) findViewById(R.id.button2);
RestartButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//gameRestart = new Restart(Game.this);
final Dialog dialog = new Dialog(Game.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Restart");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.textDialog);
text.setText("Are you sure you want to restart? You will loose your current progress.");
ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
image.setImageResource(R.drawable.restart);
dialog.show();
Button acceptButton = (Button) dialog.findViewById(R.id.AcceptButton);
// if button is clicked, close the custom dialog
acceptButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
gameLogic.Restart();
dialog.dismiss();
}
});
Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
// if button is clicked, close the custom dialog
declineButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
ExitButton = (Button) findViewById(R.id.button1);
ExitButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
gameExit = new Exit(Game.this);
}
});
highscoreButton = (Button) findViewById(R.id.highscores);
highscoreButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
gameHighscores = new Highscores(Game.this);
}
});
settings = (Button) findViewById(R.id.settings);
settings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// custom dialog
gameSettings = new Settings(Game.this);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
}
| FreddyG/Hangman2 | Hangman/src/com/example/hangman/Game.java | 1,026 | //words lezen van xml | line_comment | nl | package com.example.hangman;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
//words lezen<SUF>
//words stoppen in sql lite
//design pattern, design doc aanpassen
//features saven
public class Game extends Activity {
private Button RestartButton;
private Button ExitButton;
private Button highscoreButton;
private Button settings;
private Gameplay gameLogic;
private Settings gameSettings;
private Exit gameExit;
private Highscores gameHighscores;
private SaveData defaultSetting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
defaultSetting = new SaveData(this);
defaultSetting.saveSettings("7", "10");
gameLogic = new Gameplay(this);
RestartButton = (Button) findViewById(R.id.button2);
RestartButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//gameRestart = new Restart(Game.this);
final Dialog dialog = new Dialog(Game.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Restart");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.textDialog);
text.setText("Are you sure you want to restart? You will loose your current progress.");
ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
image.setImageResource(R.drawable.restart);
dialog.show();
Button acceptButton = (Button) dialog.findViewById(R.id.AcceptButton);
// if button is clicked, close the custom dialog
acceptButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
gameLogic.Restart();
dialog.dismiss();
}
});
Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
// if button is clicked, close the custom dialog
declineButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
ExitButton = (Button) findViewById(R.id.button1);
ExitButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
gameExit = new Exit(Game.this);
}
});
highscoreButton = (Button) findViewById(R.id.highscores);
highscoreButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
gameHighscores = new Highscores(Game.this);
}
});
settings = (Button) findViewById(R.id.settings);
settings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// custom dialog
gameSettings = new Settings(Game.this);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
}
|
211590_0 | /** -----------------------------------------------------------------------
*
* ie.ucd.srg.koa.constants.SystemState.java
*
* -----------------------------------------------------------------------
*
* (c) 2003 Ministerie van Binnenlandse Zaken en Koninkrijkrelaties
*
* Project : Kiezen Op Afstand (KOA)
* Project Number : ECF-2651
*
* History:
* Version Date Name Reason
* ---------------------------------------------------------
* 0.1 11-04-2003 MKu First implementation
* -----------------------------------------------------------------------
*/
package ie.ucd.srg.koa.constants;
import java.io.IOException;
import java.util.Vector;
import ie.ucd.srg.koa.exception.*;
import ie.ucd.srg.logica.eplatform.error.ErrorMessageFactory;
import ie.ucd.srg.koa.constants.ErrorConstants;
import ie.ucd.srg.koa.utils.KOALogHelper;
/**
* All possible states the KOA system could
* have are bundled in this class.
* Every state has a constant value.
*
* @author KuijerM
*
*/
public class SystemState
{
/**
* Private constructor to prevent
* creating an instance of this class
*
*/
private SystemState()
{
}
/**
* The system state is not known
*
*/
public final static String UNKNOWN = "UNKNOWN";
/**
* The system will be prepared for the elections
*
*/
public final static String PREPARE = "PREPARE";
/**
* The system is initialized and ready to be opened
*
*/
public final static String INITIALIZED = "INITIALIZED";
/**
* The system is open. In this state votes can be
* posted to the system.
*
*/
public final static String OPEN = "OPEN";
/**
* The system is blocked. If the system indicates that
* there are inconsistenties, it automatically will
* block.
*
*/
public final static String BLOCKED = "BLOCKED";
/**
* The system is suspended. During elections and there
* can not be voted.
*
*/
public final static String SUSPENDED = "SUSPENDED";
/**
* The system is closed. There can not be voted anymore.
*
*/
public final static String CLOSED = "CLOSED";
/**
* The system is re-initialized. It is ready to be
* opened.
*
*/
public final static String RE_INITIALIZED = "RE_INITIALIZED";
/**
* The system is closed and the system is ready to
* count the votes.
*
*/
public final static String READY_TO_COUNT = "READY_TO_COUNT";
/**
* The system has counted the votes. This is the final
* state.
*
*/
public final static String VOTES_COUNTED = "VOTES_COUNTED";
/**
* Get the system state mapped to an Integer
*
*/
//@ requires sState != null;
//@ ensures \result >= -1 && \result <= 6;
public static int getStateAsInt(String sState)
{
if (sState.equals(UNKNOWN))
return -1;
if (sState.equals(PREPARE))
return 0;
if (sState.equals(INITIALIZED))
return 1;
if (sState.equals(RE_INITIALIZED))
return 2;
if (sState.equals(OPEN))
return 3;
if (sState.equals(SUSPENDED))
return 4;
if (sState.equals(BLOCKED))
return 5;
if (sState.equals(READY_TO_COUNT)
|| sState.equals(VOTES_COUNTED)
|| sState.equals(CLOSED))
return 6;
return -1;
}
/**
* Method to determine if the system state should be altered
* before actions are executed on the components, or after the
* actions have been executed.
*
* @param sCurrentState The current state
* @param sNewState the new state
*
* @return boolean indicating if the state is changed before executing the components (true) or after executing the components (false)
*
*/
//@ requires sCurrentState != null;
//@ requires sNewState != null;
public static boolean changeSystemStateFirst(
String sCurrentState,
String sNewState)
{
/* if the new state is blocked always change the system state first */
if (sNewState.equals(BLOCKED))
{
return true;
}
/* if the currentstate is prepare
and new state is initialized*/
if (sCurrentState.equals(PREPARE) && sNewState.equals(INITIALIZED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is initialized and new state
is open*/
else if (sCurrentState.equals(INITIALIZED) && sNewState.equals(OPEN))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(CLOSED))
{
/* true means that the state is changed
first, before all the components have executed changes */
return true;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(SUSPENDED))
{
/* true means that the state is changed
first, before all the components have executed changes */
return true;
}
/* if the currentstate is blocked and new state
is suspended */
else if (sCurrentState.equals(BLOCKED) && sNewState.equals(SUSPENDED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is suspended and new state
is closed */
else if (sCurrentState.equals(SUSPENDED) && sNewState.equals(CLOSED))
{
/* true means that the state is changed
first, before all the components have executed changes */
return true;
}
/* if the currentstate is suspended and new state
is re-initialized */
else if (
sCurrentState.equals(SUSPENDED)
&& sNewState.equals(RE_INITIALIZED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is re-initialized and new state
is open */
else if (
sCurrentState.equals(RE_INITIALIZED) && sNewState.equals(OPEN))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is closed and new state
is ready to count */
else if (
sCurrentState.equals(CLOSED) && sNewState.equals(READY_TO_COUNT))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is ready to count and new state
is votes counted */
else if (
sCurrentState.equals(READY_TO_COUNT)
&& sNewState.equals(VOTES_COUNTED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/**
* Method to get all the available valid states to change
* to based on the current state.
*
* @param sCurrentState The current state
*
* @return Vector with all states (String) that are valid to change to
*
*/
//@ requires sCurrentState != null;
//@ ensures \result != null;
public static Vector getValidStateChanges(String sCurrentState)
{
Vector vValidStates = new Vector();
/* if the currentstate is prepare */
if (sCurrentState.equals(PREPARE))
{
vValidStates.add(INITIALIZED);
}
/* if the currentstate is initialized */
else if (sCurrentState.equals(INITIALIZED))
{
vValidStates.add(OPEN);
}
/* if the currentstate is open */
else if (sCurrentState.equals(OPEN))
{
vValidStates.add(CLOSED);
vValidStates.add(BLOCKED);
vValidStates.add(SUSPENDED);
}
/* if the currentstate is blocked */
else if (sCurrentState.equals(BLOCKED))
{
vValidStates.add(SUSPENDED);
}
/* if the currentstate is suspended */
else if (sCurrentState.equals(SUSPENDED))
{
vValidStates.add(CLOSED);
vValidStates.add(RE_INITIALIZED);
}
/* if the currentstate is re-initialized */
else if (sCurrentState.equals(RE_INITIALIZED))
{
vValidStates.add(OPEN);
vValidStates.add(SUSPENDED);
}
/* if the currentstate is closed */
else if (sCurrentState.equals(CLOSED))
{
vValidStates.add(READY_TO_COUNT);
}
/* if the currentstate is ready to count */
else if (sCurrentState.equals(READY_TO_COUNT))
{
vValidStates.add(VOTES_COUNTED);
}
return vValidStates;
}
/**
* Translates the State key to a dutch discription of the state.
*
* @param stateKey The key of the state to translate
*
* @return String the translation of the state key
*
*/
//@ requires stateKey != null;
//@ ensures \result != null;
public static String getDutchTranslationForState(String stateKey)
{
if (stateKey == null)
{
return "Onbekende status";
}
stateKey = stateKey.trim();
if (stateKey.equals(SystemState.PREPARE))
{
return "Voorbereiding";
}
else if (stateKey.equals(SystemState.INITIALIZED))
{
return "Gereed voor openen";
}
else if (stateKey.equals(SystemState.OPEN))
{
return "Open";
}
else if (stateKey.equals(SystemState.SUSPENDED))
{
return "Onderbroken";
}
else if (stateKey.equals(SystemState.RE_INITIALIZED))
{
return "Gereed voor hervatten";
}
else if (stateKey.equals(SystemState.BLOCKED))
{
return "Geblokkeerd";
}
else if (stateKey.equals(SystemState.CLOSED))
{
return "Gesloten";
}
else if (stateKey.equals(SystemState.READY_TO_COUNT))
{
return "Gereed voor stemopneming";
}
else if (stateKey.equals(SystemState.VOTES_COUNTED))
{
return "Stemopneming uitgevoerd";
}
else
{
return stateKey;
}
}
/**
* Method to determine if the state change should only be
* performed when all notification are succesful or always
* change the state.
*
* @param sCurrentState The currentstate
* @param sNewState The new state
*
* @return boolean The boolean indicating only to change state if succesfully notified all components (True) or always change state (false)
*
*/
//@ requires sCurrentState != null;
//@ requires sNewState != null;
public static boolean changeStateOnlyForSuccesfulNotify(
String sCurrentState,
String sNewState)
{
/* check if the systemstate should be changed first,
if this is true, always change state, because
this means the state change is to important to cancel */
if (changeSystemStateFirst(sCurrentState, sNewState))
{
/* false means always change state */
return false;
}
/* if the currentstate is prepare
and new state is initialized*/
if (sCurrentState.equals(PREPARE) && sNewState.equals(INITIALIZED))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is initialized and new state
is open*/
else if (sCurrentState.equals(INITIALIZED) && sNewState.equals(OPEN))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(CLOSED))
{
/* false means always change state */
return false;
}
/* if the currentstate is open and new state
is blocked */
else if (sCurrentState.equals(OPEN) && sNewState.equals(BLOCKED))
{
/* false means always change state */
return false;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(SUSPENDED))
{
/* false means always change state */
return false;
}
/* if the currentstate is blocked and new state
is suspended */
else if (sCurrentState.equals(BLOCKED) && sNewState.equals(SUSPENDED))
{
/* false means always change state */
return false;
}
/* if the currentstate is suspended and new state
is closed */
else if (sCurrentState.equals(SUSPENDED) && sNewState.equals(CLOSED))
{
/* false means always change state */
return false;
}
/* if the currentstate is suspended and new state
is re-initialized */
else if (
sCurrentState.equals(SUSPENDED)
&& sNewState.equals(RE_INITIALIZED))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is re-initialized and new state
is open */
else if (
sCurrentState.equals(RE_INITIALIZED) && sNewState.equals(OPEN))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is closed and new state
is ready to count */
else if (
sCurrentState.equals(CLOSED) && sNewState.equals(READY_TO_COUNT))
{
/* false means always change state */
return false;
}
/* if the currentstate is ready to count and new state
is votes counted */
else if (
sCurrentState.equals(READY_TO_COUNT)
&& sNewState.equals(VOTES_COUNTED))
{
/* false means always change state */
return false;
}
/* false means always change state */
return false;
}
/**
* Translates the State key to a whole text to show on the web page for
* the voter.
*
* @param stateKey The key of the state to translate
*
* @return String the text saying the elections are open or closed.
*
*/
//@ requires sCurrentState != null;
public static String getWebTextForState(String sCurrentState)
{
String sText = null;
if (sCurrentState == null || sCurrentState.equals(SystemState.UNKNOWN))
{
KOALogHelper.log(
KOALogHelper.WARNING,
"[SystemState.getWebTextForState] state unknown");
return sText;
}
try
{
ErrorMessageFactory msgFactory =
ErrorMessageFactory.getErrorMessageFactory();
if (sCurrentState.equals(SystemState.OPEN))
{
sText = null;
}
else if (
sCurrentState.equals(SystemState.PREPARE)
|| sCurrentState.equals(SystemState.INITIALIZED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_NOT_YET_OPEN,
null);
}
else if (sCurrentState.equals(SystemState.BLOCKED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_BLOCKED,
null);
}
else if (
sCurrentState.equals(SystemState.SUSPENDED)
|| sCurrentState.equals(SystemState.RE_INITIALIZED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_SUSPENDED,
null);
}
else if (
sCurrentState.equals(SystemState.CLOSED)
|| sCurrentState.equals(SystemState.READY_TO_COUNT)
|| sCurrentState.equals(SystemState.VOTES_COUNTED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_CLOSED,
null);
}
}
catch (IOException ioe)
{
KOALogHelper.logError(
"SystemState.getWebTextForState",
"Failed to get status messages from ErrorMessageFactory",
ioe);
}
/**@author Alan Morkan */
//TODO Properly complete the body of the following catch block
catch(KOAException k){
System.out.println(k);
}
return sText;
}
}
| FreeAndFair/KOA | infrastructure/source/WebVotingSystem/src/ie/ucd/srg/koa/constants/SystemState.java | 5,054 | /** -----------------------------------------------------------------------
*
* ie.ucd.srg.koa.constants.SystemState.java
*
* -----------------------------------------------------------------------
*
* (c) 2003 Ministerie van Binnenlandse Zaken en Koninkrijkrelaties
*
* Project : Kiezen Op Afstand (KOA)
* Project Number : ECF-2651
*
* History:
* Version Date Name Reason
* ---------------------------------------------------------
* 0.1 11-04-2003 MKu First implementation
* -----------------------------------------------------------------------
*/ | block_comment | nl | /** -----------------------------------------------------------------------
<SUF>*/
package ie.ucd.srg.koa.constants;
import java.io.IOException;
import java.util.Vector;
import ie.ucd.srg.koa.exception.*;
import ie.ucd.srg.logica.eplatform.error.ErrorMessageFactory;
import ie.ucd.srg.koa.constants.ErrorConstants;
import ie.ucd.srg.koa.utils.KOALogHelper;
/**
* All possible states the KOA system could
* have are bundled in this class.
* Every state has a constant value.
*
* @author KuijerM
*
*/
public class SystemState
{
/**
* Private constructor to prevent
* creating an instance of this class
*
*/
private SystemState()
{
}
/**
* The system state is not known
*
*/
public final static String UNKNOWN = "UNKNOWN";
/**
* The system will be prepared for the elections
*
*/
public final static String PREPARE = "PREPARE";
/**
* The system is initialized and ready to be opened
*
*/
public final static String INITIALIZED = "INITIALIZED";
/**
* The system is open. In this state votes can be
* posted to the system.
*
*/
public final static String OPEN = "OPEN";
/**
* The system is blocked. If the system indicates that
* there are inconsistenties, it automatically will
* block.
*
*/
public final static String BLOCKED = "BLOCKED";
/**
* The system is suspended. During elections and there
* can not be voted.
*
*/
public final static String SUSPENDED = "SUSPENDED";
/**
* The system is closed. There can not be voted anymore.
*
*/
public final static String CLOSED = "CLOSED";
/**
* The system is re-initialized. It is ready to be
* opened.
*
*/
public final static String RE_INITIALIZED = "RE_INITIALIZED";
/**
* The system is closed and the system is ready to
* count the votes.
*
*/
public final static String READY_TO_COUNT = "READY_TO_COUNT";
/**
* The system has counted the votes. This is the final
* state.
*
*/
public final static String VOTES_COUNTED = "VOTES_COUNTED";
/**
* Get the system state mapped to an Integer
*
*/
//@ requires sState != null;
//@ ensures \result >= -1 && \result <= 6;
public static int getStateAsInt(String sState)
{
if (sState.equals(UNKNOWN))
return -1;
if (sState.equals(PREPARE))
return 0;
if (sState.equals(INITIALIZED))
return 1;
if (sState.equals(RE_INITIALIZED))
return 2;
if (sState.equals(OPEN))
return 3;
if (sState.equals(SUSPENDED))
return 4;
if (sState.equals(BLOCKED))
return 5;
if (sState.equals(READY_TO_COUNT)
|| sState.equals(VOTES_COUNTED)
|| sState.equals(CLOSED))
return 6;
return -1;
}
/**
* Method to determine if the system state should be altered
* before actions are executed on the components, or after the
* actions have been executed.
*
* @param sCurrentState The current state
* @param sNewState the new state
*
* @return boolean indicating if the state is changed before executing the components (true) or after executing the components (false)
*
*/
//@ requires sCurrentState != null;
//@ requires sNewState != null;
public static boolean changeSystemStateFirst(
String sCurrentState,
String sNewState)
{
/* if the new state is blocked always change the system state first */
if (sNewState.equals(BLOCKED))
{
return true;
}
/* if the currentstate is prepare
and new state is initialized*/
if (sCurrentState.equals(PREPARE) && sNewState.equals(INITIALIZED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is initialized and new state
is open*/
else if (sCurrentState.equals(INITIALIZED) && sNewState.equals(OPEN))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(CLOSED))
{
/* true means that the state is changed
first, before all the components have executed changes */
return true;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(SUSPENDED))
{
/* true means that the state is changed
first, before all the components have executed changes */
return true;
}
/* if the currentstate is blocked and new state
is suspended */
else if (sCurrentState.equals(BLOCKED) && sNewState.equals(SUSPENDED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is suspended and new state
is closed */
else if (sCurrentState.equals(SUSPENDED) && sNewState.equals(CLOSED))
{
/* true means that the state is changed
first, before all the components have executed changes */
return true;
}
/* if the currentstate is suspended and new state
is re-initialized */
else if (
sCurrentState.equals(SUSPENDED)
&& sNewState.equals(RE_INITIALIZED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is re-initialized and new state
is open */
else if (
sCurrentState.equals(RE_INITIALIZED) && sNewState.equals(OPEN))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is closed and new state
is ready to count */
else if (
sCurrentState.equals(CLOSED) && sNewState.equals(READY_TO_COUNT))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* if the currentstate is ready to count and new state
is votes counted */
else if (
sCurrentState.equals(READY_TO_COUNT)
&& sNewState.equals(VOTES_COUNTED))
{
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/* false means that the state is changed
after all the components have executed changes */
return false;
}
/**
* Method to get all the available valid states to change
* to based on the current state.
*
* @param sCurrentState The current state
*
* @return Vector with all states (String) that are valid to change to
*
*/
//@ requires sCurrentState != null;
//@ ensures \result != null;
public static Vector getValidStateChanges(String sCurrentState)
{
Vector vValidStates = new Vector();
/* if the currentstate is prepare */
if (sCurrentState.equals(PREPARE))
{
vValidStates.add(INITIALIZED);
}
/* if the currentstate is initialized */
else if (sCurrentState.equals(INITIALIZED))
{
vValidStates.add(OPEN);
}
/* if the currentstate is open */
else if (sCurrentState.equals(OPEN))
{
vValidStates.add(CLOSED);
vValidStates.add(BLOCKED);
vValidStates.add(SUSPENDED);
}
/* if the currentstate is blocked */
else if (sCurrentState.equals(BLOCKED))
{
vValidStates.add(SUSPENDED);
}
/* if the currentstate is suspended */
else if (sCurrentState.equals(SUSPENDED))
{
vValidStates.add(CLOSED);
vValidStates.add(RE_INITIALIZED);
}
/* if the currentstate is re-initialized */
else if (sCurrentState.equals(RE_INITIALIZED))
{
vValidStates.add(OPEN);
vValidStates.add(SUSPENDED);
}
/* if the currentstate is closed */
else if (sCurrentState.equals(CLOSED))
{
vValidStates.add(READY_TO_COUNT);
}
/* if the currentstate is ready to count */
else if (sCurrentState.equals(READY_TO_COUNT))
{
vValidStates.add(VOTES_COUNTED);
}
return vValidStates;
}
/**
* Translates the State key to a dutch discription of the state.
*
* @param stateKey The key of the state to translate
*
* @return String the translation of the state key
*
*/
//@ requires stateKey != null;
//@ ensures \result != null;
public static String getDutchTranslationForState(String stateKey)
{
if (stateKey == null)
{
return "Onbekende status";
}
stateKey = stateKey.trim();
if (stateKey.equals(SystemState.PREPARE))
{
return "Voorbereiding";
}
else if (stateKey.equals(SystemState.INITIALIZED))
{
return "Gereed voor openen";
}
else if (stateKey.equals(SystemState.OPEN))
{
return "Open";
}
else if (stateKey.equals(SystemState.SUSPENDED))
{
return "Onderbroken";
}
else if (stateKey.equals(SystemState.RE_INITIALIZED))
{
return "Gereed voor hervatten";
}
else if (stateKey.equals(SystemState.BLOCKED))
{
return "Geblokkeerd";
}
else if (stateKey.equals(SystemState.CLOSED))
{
return "Gesloten";
}
else if (stateKey.equals(SystemState.READY_TO_COUNT))
{
return "Gereed voor stemopneming";
}
else if (stateKey.equals(SystemState.VOTES_COUNTED))
{
return "Stemopneming uitgevoerd";
}
else
{
return stateKey;
}
}
/**
* Method to determine if the state change should only be
* performed when all notification are succesful or always
* change the state.
*
* @param sCurrentState The currentstate
* @param sNewState The new state
*
* @return boolean The boolean indicating only to change state if succesfully notified all components (True) or always change state (false)
*
*/
//@ requires sCurrentState != null;
//@ requires sNewState != null;
public static boolean changeStateOnlyForSuccesfulNotify(
String sCurrentState,
String sNewState)
{
/* check if the systemstate should be changed first,
if this is true, always change state, because
this means the state change is to important to cancel */
if (changeSystemStateFirst(sCurrentState, sNewState))
{
/* false means always change state */
return false;
}
/* if the currentstate is prepare
and new state is initialized*/
if (sCurrentState.equals(PREPARE) && sNewState.equals(INITIALIZED))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is initialized and new state
is open*/
else if (sCurrentState.equals(INITIALIZED) && sNewState.equals(OPEN))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(CLOSED))
{
/* false means always change state */
return false;
}
/* if the currentstate is open and new state
is blocked */
else if (sCurrentState.equals(OPEN) && sNewState.equals(BLOCKED))
{
/* false means always change state */
return false;
}
/* if the currentstate is open and new state
is closed */
else if (sCurrentState.equals(OPEN) && sNewState.equals(SUSPENDED))
{
/* false means always change state */
return false;
}
/* if the currentstate is blocked and new state
is suspended */
else if (sCurrentState.equals(BLOCKED) && sNewState.equals(SUSPENDED))
{
/* false means always change state */
return false;
}
/* if the currentstate is suspended and new state
is closed */
else if (sCurrentState.equals(SUSPENDED) && sNewState.equals(CLOSED))
{
/* false means always change state */
return false;
}
/* if the currentstate is suspended and new state
is re-initialized */
else if (
sCurrentState.equals(SUSPENDED)
&& sNewState.equals(RE_INITIALIZED))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is re-initialized and new state
is open */
else if (
sCurrentState.equals(RE_INITIALIZED) && sNewState.equals(OPEN))
{
/* true means only change state if notify succefully */
return true;
}
/* if the currentstate is closed and new state
is ready to count */
else if (
sCurrentState.equals(CLOSED) && sNewState.equals(READY_TO_COUNT))
{
/* false means always change state */
return false;
}
/* if the currentstate is ready to count and new state
is votes counted */
else if (
sCurrentState.equals(READY_TO_COUNT)
&& sNewState.equals(VOTES_COUNTED))
{
/* false means always change state */
return false;
}
/* false means always change state */
return false;
}
/**
* Translates the State key to a whole text to show on the web page for
* the voter.
*
* @param stateKey The key of the state to translate
*
* @return String the text saying the elections are open or closed.
*
*/
//@ requires sCurrentState != null;
public static String getWebTextForState(String sCurrentState)
{
String sText = null;
if (sCurrentState == null || sCurrentState.equals(SystemState.UNKNOWN))
{
KOALogHelper.log(
KOALogHelper.WARNING,
"[SystemState.getWebTextForState] state unknown");
return sText;
}
try
{
ErrorMessageFactory msgFactory =
ErrorMessageFactory.getErrorMessageFactory();
if (sCurrentState.equals(SystemState.OPEN))
{
sText = null;
}
else if (
sCurrentState.equals(SystemState.PREPARE)
|| sCurrentState.equals(SystemState.INITIALIZED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_NOT_YET_OPEN,
null);
}
else if (sCurrentState.equals(SystemState.BLOCKED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_BLOCKED,
null);
}
else if (
sCurrentState.equals(SystemState.SUSPENDED)
|| sCurrentState.equals(SystemState.RE_INITIALIZED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_SUSPENDED,
null);
}
else if (
sCurrentState.equals(SystemState.CLOSED)
|| sCurrentState.equals(SystemState.READY_TO_COUNT)
|| sCurrentState.equals(SystemState.VOTES_COUNTED))
{
sText =
msgFactory.getErrorMessage(
ErrorConstants.ERR_ELECTION_CLOSED,
null);
}
}
catch (IOException ioe)
{
KOALogHelper.logError(
"SystemState.getWebTextForState",
"Failed to get status messages from ErrorMessageFactory",
ioe);
}
/**@author Alan Morkan */
//TODO Properly complete the body of the following catch block
catch(KOAException k){
System.out.println(k);
}
return sText;
}
}
|
83128_1 | package components;
/**
* SSD class. Contains all the information that a Solid State Drive has.
* All the fields match the fields in the Neo4j Database.
* Extends {@link components.Hardware}
*
* @author Frenesius
* @since 1-1-2015
* @version 0.1
*/
public class SSD extends Hardware{
private String beoordeling;
private String hoogte;
private String verkoopstatus;
private String fabrieksgarantie;
private String product;
private String serie;
private String hardeschijfbusintern; // origineel Hardeschijf bus (intern)
private String behuizingbayintern;
private String ssdeigenschappen;
private String opslagcapaciteit;
private String lezensequentieel; // origineel Lezen (sequentieel)
private String prijspergb;
private String ssdtype; // origineel SSD-type
private String ssdcontroller; // origineel SSD-controller
private String schrijvensequentieel; // origineel Schrijven (sequentieel)
private String stroomverbruiklezen; // origineel Stroomverbruik (lezen)
private String lezenrandom4k; // origineel Lezen (random 4K)
private String schrijvenrandom4k; // origineel Schrijven (random 4K)
private String drivecache;
private String stroomverbruikschrijven; // origineel Stroomverbruik (schrijven)
private String meantimebetweenfailures;
private String hddssdaansluiting; // HDD/SSD-aansluiting
public String getBeoordeling() {
return beoordeling;
}
public void setBeoordeling(String beoordeling) {
this.beoordeling = beoordeling;
}
public String getHoogte() {
return hoogte;
}
public void setHoogte(String hoogte) {
this.hoogte = hoogte;
}
public String getVerkoopstatus() {
return verkoopstatus;
}
public void setVerkoopstatus(String verkoopstatus) {
this.verkoopstatus = verkoopstatus;
}
public String getFabrieksgarantie() {
return fabrieksgarantie;
}
public void setFabrieksgarantie(String fabrieksgarantie) {
this.fabrieksgarantie = fabrieksgarantie;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getSerie() {
return serie;
}
public void setSerie(String serie) {
this.serie = serie;
}
public String getHardeschijfbusintern() {
return hardeschijfbusintern;
}
public void setHardeschijfbusintern(String hardeschijfbusintern) {
this.hardeschijfbusintern = hardeschijfbusintern;
}
public String getBehuizingbayintern() {
return behuizingbayintern;
}
public void setBehuizingbayintern(String behuizingbayintern) {
this.behuizingbayintern = behuizingbayintern;
}
public String getSsdeigenschappen() {
return ssdeigenschappen;
}
public void setSsdeigenschappen(String ssdeigenschappen) {
this.ssdeigenschappen = ssdeigenschappen;
}
public String getOpslagcapaciteit() {
return opslagcapaciteit;
}
public void setOpslagcapaciteit(String opslagcapaciteit) {
this.opslagcapaciteit = opslagcapaciteit;
}
public String getLezensequentieel() {
return lezensequentieel;
}
public void setLezensequentieel(String lezensequentieel) {
this.lezensequentieel = lezensequentieel;
}
public String getPrijspergb() {
return prijspergb;
}
public void setPrijspergb(String prijspergb) {
this.prijspergb = prijspergb;
}
public String getSsdtype() {
return ssdtype;
}
public void setSsdtype(String ssdtype) {
this.ssdtype = ssdtype;
}
public String getSsdcontroller() {
return ssdcontroller;
}
public void setSsdcontroller(String ssdcontroller) {
this.ssdcontroller = ssdcontroller;
}
public String getSchrijvensequentieel() {
return schrijvensequentieel;
}
public void setSchrijvensequentieel(String schrijvensequentieel) {
this.schrijvensequentieel = schrijvensequentieel;
}
public String getStroomverbruiklezen() {
return stroomverbruiklezen;
}
public void setStroomverbruiklezen(String stroomverbruiklezen) {
this.stroomverbruiklezen = stroomverbruiklezen;
}
public String getLezenrandom4k() {
return lezenrandom4k;
}
public void setLezenrandom4k(String lezenrandom4k) {
this.lezenrandom4k = lezenrandom4k;
}
public String getSchrijvenrandom4k() {
return schrijvenrandom4k;
}
public void setSchrijvenrandom4k(String schrijvenrandom4k) {
this.schrijvenrandom4k = schrijvenrandom4k;
}
public String getDrivecache() {
return drivecache;
}
public void setDrivecache(String drivecache) {
this.drivecache = drivecache;
}
public String getStroomverbruikschrijven() {
return stroomverbruikschrijven;
}
public void setStroomverbruikschrijven(String stroomverbruikschrijven) {
this.stroomverbruikschrijven = stroomverbruikschrijven;
}
public String getMeantimebetweenfailures() {
return meantimebetweenfailures;
}
public void setMeantimebetweenfailures(String meantimebetweenfailures) {
this.meantimebetweenfailures = meantimebetweenfailures;
}
public String getHddssdaansluiting() {
return hddssdaansluiting;
}
public void setHddssdaansluiting(String hddssdaansluiting) {
this.hddssdaansluiting = hddssdaansluiting;
}
} | Frenesius/PC-Builder-Matcher | src/components/SSD.java | 1,785 | // origineel Hardeschijf bus (intern)
| line_comment | nl | package components;
/**
* SSD class. Contains all the information that a Solid State Drive has.
* All the fields match the fields in the Neo4j Database.
* Extends {@link components.Hardware}
*
* @author Frenesius
* @since 1-1-2015
* @version 0.1
*/
public class SSD extends Hardware{
private String beoordeling;
private String hoogte;
private String verkoopstatus;
private String fabrieksgarantie;
private String product;
private String serie;
private String hardeschijfbusintern; // origineel Hardeschijf<SUF>
private String behuizingbayintern;
private String ssdeigenschappen;
private String opslagcapaciteit;
private String lezensequentieel; // origineel Lezen (sequentieel)
private String prijspergb;
private String ssdtype; // origineel SSD-type
private String ssdcontroller; // origineel SSD-controller
private String schrijvensequentieel; // origineel Schrijven (sequentieel)
private String stroomverbruiklezen; // origineel Stroomverbruik (lezen)
private String lezenrandom4k; // origineel Lezen (random 4K)
private String schrijvenrandom4k; // origineel Schrijven (random 4K)
private String drivecache;
private String stroomverbruikschrijven; // origineel Stroomverbruik (schrijven)
private String meantimebetweenfailures;
private String hddssdaansluiting; // HDD/SSD-aansluiting
public String getBeoordeling() {
return beoordeling;
}
public void setBeoordeling(String beoordeling) {
this.beoordeling = beoordeling;
}
public String getHoogte() {
return hoogte;
}
public void setHoogte(String hoogte) {
this.hoogte = hoogte;
}
public String getVerkoopstatus() {
return verkoopstatus;
}
public void setVerkoopstatus(String verkoopstatus) {
this.verkoopstatus = verkoopstatus;
}
public String getFabrieksgarantie() {
return fabrieksgarantie;
}
public void setFabrieksgarantie(String fabrieksgarantie) {
this.fabrieksgarantie = fabrieksgarantie;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getSerie() {
return serie;
}
public void setSerie(String serie) {
this.serie = serie;
}
public String getHardeschijfbusintern() {
return hardeschijfbusintern;
}
public void setHardeschijfbusintern(String hardeschijfbusintern) {
this.hardeschijfbusintern = hardeschijfbusintern;
}
public String getBehuizingbayintern() {
return behuizingbayintern;
}
public void setBehuizingbayintern(String behuizingbayintern) {
this.behuizingbayintern = behuizingbayintern;
}
public String getSsdeigenschappen() {
return ssdeigenschappen;
}
public void setSsdeigenschappen(String ssdeigenschappen) {
this.ssdeigenschappen = ssdeigenschappen;
}
public String getOpslagcapaciteit() {
return opslagcapaciteit;
}
public void setOpslagcapaciteit(String opslagcapaciteit) {
this.opslagcapaciteit = opslagcapaciteit;
}
public String getLezensequentieel() {
return lezensequentieel;
}
public void setLezensequentieel(String lezensequentieel) {
this.lezensequentieel = lezensequentieel;
}
public String getPrijspergb() {
return prijspergb;
}
public void setPrijspergb(String prijspergb) {
this.prijspergb = prijspergb;
}
public String getSsdtype() {
return ssdtype;
}
public void setSsdtype(String ssdtype) {
this.ssdtype = ssdtype;
}
public String getSsdcontroller() {
return ssdcontroller;
}
public void setSsdcontroller(String ssdcontroller) {
this.ssdcontroller = ssdcontroller;
}
public String getSchrijvensequentieel() {
return schrijvensequentieel;
}
public void setSchrijvensequentieel(String schrijvensequentieel) {
this.schrijvensequentieel = schrijvensequentieel;
}
public String getStroomverbruiklezen() {
return stroomverbruiklezen;
}
public void setStroomverbruiklezen(String stroomverbruiklezen) {
this.stroomverbruiklezen = stroomverbruiklezen;
}
public String getLezenrandom4k() {
return lezenrandom4k;
}
public void setLezenrandom4k(String lezenrandom4k) {
this.lezenrandom4k = lezenrandom4k;
}
public String getSchrijvenrandom4k() {
return schrijvenrandom4k;
}
public void setSchrijvenrandom4k(String schrijvenrandom4k) {
this.schrijvenrandom4k = schrijvenrandom4k;
}
public String getDrivecache() {
return drivecache;
}
public void setDrivecache(String drivecache) {
this.drivecache = drivecache;
}
public String getStroomverbruikschrijven() {
return stroomverbruikschrijven;
}
public void setStroomverbruikschrijven(String stroomverbruikschrijven) {
this.stroomverbruikschrijven = stroomverbruikschrijven;
}
public String getMeantimebetweenfailures() {
return meantimebetweenfailures;
}
public void setMeantimebetweenfailures(String meantimebetweenfailures) {
this.meantimebetweenfailures = meantimebetweenfailures;
}
public String getHddssdaansluiting() {
return hddssdaansluiting;
}
public void setHddssdaansluiting(String hddssdaansluiting) {
this.hddssdaansluiting = hddssdaansluiting;
}
} |
35437_11 | package Database;
import CentralPoint.Staff;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.awt.geom.Point2D;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Kaj Suiker on 20-3-2016.
*/
public class DaoStaff extends DaoGeneric<Staff> {
private final static String TABLENAME = DbTables.PERSONEEL.toString();
private final String ID = "ID";
private final String Achternaam = "Achternaam";
private final String Tussenvoegsel = "Tussenvoegsel";
private final String Voornaam = "Voornaam";
private final String Gebruikersnaam = "Gebruikersnaam";
private final String Wachtwoord = "Wachtwoord";
private final String LocatieX = "LocatieX";
private final String LocatieY = "LocatieY";
private final String Soort = "Soort";
private final String OpLocatie = "OpLocatie";
private final String TeamID = "TeamID";
private final String MissionID = "MissieID";
/**
* uses daoGenerics
* database class of Staff table
* @param connection database connection
*/
public DaoStaff(Connection connection) {
super(connection, TABLENAME);
}
/**
* Returns list of people who are involved in the mission
* @param id for specific list
* @return list of Staff
*/
@Override
public ObservableList<Staff> getSpecificList(int id) {
String query;
if (id == 0) {
query = "Select * FROM Personeel INNER JOIN Team ON Personeel.ID = Team.PersoneelID AND Team.MissieID IS NOT NULL AND Personeel.OpLocatie = 1";
} else {
query = "Select DISTINCT Personeel.* FROM Personeel INNER JOIN Team ON Personeel.ID = Team.PersoneelID AND Personeel.OpLocatie = 0";
}
return getObservableList(query);
}
/**
* Get all members of staff
* @return list of staff
* @see DaoGeneric#getAllRecord()
*/
@Override
public ObservableList<Staff> getAllRecord() {
String query = "SELECT * FROM " + TABLENAME;
return getObservableList(query);
}
/**
* return list of query
*
* @param query the query to execute
* @return return observableList
*/
private ObservableList<Staff> getObservableList(String query) {
List<Staff> staffList = new ArrayList<>();
ObservableList<Staff> obsStaff = FXCollections.observableArrayList(staffList);
ResultSet res;
if(query.contains("DISTINCT")){
try {
Statement statement = connection.createStatement();
res = statement.executeQuery(query);
while (res.next()) {
obsStaff.add(new Staff(res.getInt(ID), res.getString(Voornaam),
res.getString(Tussenvoegsel), res.getString(Achternaam), res.getString(Gebruikersnaam),
res.getString(Wachtwoord), new Point2D.Double(res.getDouble(LocatieX),
res.getDouble(LocatieY)), res.getString(Soort),
false));
}
} catch (SQLException e) {
e.printStackTrace();
}
}else{
try {
Statement statement = connection.createStatement();
res = statement.executeQuery(query);
while (res.next()) {
obsStaff.add(new Staff(res.getInt(ID), res.getString(Voornaam),
res.getString(Tussenvoegsel), res.getString(Achternaam), res.getString(Gebruikersnaam),
res.getString(Wachtwoord), new Point2D.Double(res.getDouble(LocatieX),
res.getDouble(LocatieY)), res.getString(Soort),
true, res.getInt(TeamID), res.getInt(MissionID)));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return obsStaff;
}
/**
* Used for getting login data (true/false)
* @param value object to update
* @param key key of row
* Update bool in a table row
* @return
*/
@Override
public boolean update(Staff value, int key) {
boolean result = false;
ResultSet res;
String bit = value.isOnLocation() ? "1" : "0";
String query = "UPDATE " + TABLENAME + " Set OpLocatie = " + bit + " WHERE id = ?";
try {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, (String.valueOf(value.getId())));
ps.executeUpdate();
result = true;
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
/**
* update staff values
*
* @param value list of to update with int
* @param key key of row
* @return
*/
@Override
public boolean update(Staff value, String key) {
throw new NotImplementedException();
}
/**
* insert new staff
* @param value
* @return
*/
@Override
public boolean insert(Staff value) {
throw new NotImplementedException();
}
/**
* delete staff from database
* @param key
* @return
*/
@Override
public boolean delete(int key) {
throw new NotImplementedException();
}
/**
* not used method
* @param id
* @param id1
*/
@Override
public void insertTwoInts(int id, int id1) {
throw new NotImplementedException();
}
/**
* returns missionID that Staff is part of
*
* @param value object value
* @param key key
* @return the Staff
*/
@Override
public Staff getObject(Staff value, int key) {
Staff result = new Staff();
result.setId(-1);
ResultSet res;
//String query = "SELECT * FROM Personeel WHERE Gebruikersnaam = ? AND Wachtwoord = ?";
String query = "SELECT Missieid From Team WHERE PersoneelID = (SELECT ID FROM Personeel WHERE Gebruikersnaam=? AND Wachtwoord=?)";
try {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, value.getUserName());
ps.setString(2, value.getPassword());
res = ps.executeQuery();
while (res.next()) {
result.setId(res.getInt(MissionID));
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
| Full-House-Fontys/Full-House-Main | src/Database/DaoStaff.java | 1,909 | //String query = "SELECT * FROM Personeel WHERE Gebruikersnaam = ? AND Wachtwoord = ?"; | line_comment | nl | package Database;
import CentralPoint.Staff;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.awt.geom.Point2D;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Kaj Suiker on 20-3-2016.
*/
public class DaoStaff extends DaoGeneric<Staff> {
private final static String TABLENAME = DbTables.PERSONEEL.toString();
private final String ID = "ID";
private final String Achternaam = "Achternaam";
private final String Tussenvoegsel = "Tussenvoegsel";
private final String Voornaam = "Voornaam";
private final String Gebruikersnaam = "Gebruikersnaam";
private final String Wachtwoord = "Wachtwoord";
private final String LocatieX = "LocatieX";
private final String LocatieY = "LocatieY";
private final String Soort = "Soort";
private final String OpLocatie = "OpLocatie";
private final String TeamID = "TeamID";
private final String MissionID = "MissieID";
/**
* uses daoGenerics
* database class of Staff table
* @param connection database connection
*/
public DaoStaff(Connection connection) {
super(connection, TABLENAME);
}
/**
* Returns list of people who are involved in the mission
* @param id for specific list
* @return list of Staff
*/
@Override
public ObservableList<Staff> getSpecificList(int id) {
String query;
if (id == 0) {
query = "Select * FROM Personeel INNER JOIN Team ON Personeel.ID = Team.PersoneelID AND Team.MissieID IS NOT NULL AND Personeel.OpLocatie = 1";
} else {
query = "Select DISTINCT Personeel.* FROM Personeel INNER JOIN Team ON Personeel.ID = Team.PersoneelID AND Personeel.OpLocatie = 0";
}
return getObservableList(query);
}
/**
* Get all members of staff
* @return list of staff
* @see DaoGeneric#getAllRecord()
*/
@Override
public ObservableList<Staff> getAllRecord() {
String query = "SELECT * FROM " + TABLENAME;
return getObservableList(query);
}
/**
* return list of query
*
* @param query the query to execute
* @return return observableList
*/
private ObservableList<Staff> getObservableList(String query) {
List<Staff> staffList = new ArrayList<>();
ObservableList<Staff> obsStaff = FXCollections.observableArrayList(staffList);
ResultSet res;
if(query.contains("DISTINCT")){
try {
Statement statement = connection.createStatement();
res = statement.executeQuery(query);
while (res.next()) {
obsStaff.add(new Staff(res.getInt(ID), res.getString(Voornaam),
res.getString(Tussenvoegsel), res.getString(Achternaam), res.getString(Gebruikersnaam),
res.getString(Wachtwoord), new Point2D.Double(res.getDouble(LocatieX),
res.getDouble(LocatieY)), res.getString(Soort),
false));
}
} catch (SQLException e) {
e.printStackTrace();
}
}else{
try {
Statement statement = connection.createStatement();
res = statement.executeQuery(query);
while (res.next()) {
obsStaff.add(new Staff(res.getInt(ID), res.getString(Voornaam),
res.getString(Tussenvoegsel), res.getString(Achternaam), res.getString(Gebruikersnaam),
res.getString(Wachtwoord), new Point2D.Double(res.getDouble(LocatieX),
res.getDouble(LocatieY)), res.getString(Soort),
true, res.getInt(TeamID), res.getInt(MissionID)));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return obsStaff;
}
/**
* Used for getting login data (true/false)
* @param value object to update
* @param key key of row
* Update bool in a table row
* @return
*/
@Override
public boolean update(Staff value, int key) {
boolean result = false;
ResultSet res;
String bit = value.isOnLocation() ? "1" : "0";
String query = "UPDATE " + TABLENAME + " Set OpLocatie = " + bit + " WHERE id = ?";
try {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, (String.valueOf(value.getId())));
ps.executeUpdate();
result = true;
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
/**
* update staff values
*
* @param value list of to update with int
* @param key key of row
* @return
*/
@Override
public boolean update(Staff value, String key) {
throw new NotImplementedException();
}
/**
* insert new staff
* @param value
* @return
*/
@Override
public boolean insert(Staff value) {
throw new NotImplementedException();
}
/**
* delete staff from database
* @param key
* @return
*/
@Override
public boolean delete(int key) {
throw new NotImplementedException();
}
/**
* not used method
* @param id
* @param id1
*/
@Override
public void insertTwoInts(int id, int id1) {
throw new NotImplementedException();
}
/**
* returns missionID that Staff is part of
*
* @param value object value
* @param key key
* @return the Staff
*/
@Override
public Staff getObject(Staff value, int key) {
Staff result = new Staff();
result.setId(-1);
ResultSet res;
//String query<SUF>
String query = "SELECT Missieid From Team WHERE PersoneelID = (SELECT ID FROM Personeel WHERE Gebruikersnaam=? AND Wachtwoord=?)";
try {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, value.getUserName());
ps.setString(2, value.getPassword());
res = ps.executeQuery();
while (res.next()) {
result.setId(res.getInt(MissionID));
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
|
7436_2 | package controller;
import java.io.File;
import java.io.IOException;
import model.Opleiding;
import server.JSONFileServer;
public class Application {
/**
* Deze klasse is het startpunt voor de applicatie. Hierin maak je een server
* op een bepaalde poort (bijv. 8888). Daarna is er een PrIS-object gemaakt. Dit
* object fungeert als toegangspunt van het domeinmodel. Hiervandaan kan alle
* informatie bereikt worden.
*
* Om het domeinmodel en de Polymer-GUI aan elkaar te koppelen zijn diverse controllers
* gemaakt. Er zijn meerdere controllers om het overzichtelijk te houden. Je mag zoveel
* controller-klassen maken als je nodig denkt te hebben. Elke controller krijgt een
* koppeling naar het PrIS-object om benodigde informatie op te halen.
*
* Je moet wel elke URL die vanaf Polymer aangeroepen kan worden registreren! Dat is
* hieronder gedaan voor een drietal URLs. Je geeft daarbij ook aan welke controller
* de URL moet afhandelen.
*
* Als je alle URLs hebt geregistreerd kun je de server starten en de applicatie in de
* browser opvragen! Zie ook de controller-klassen voor een voorbeeld!
* @throws IOException
*
*/
public static void main(String[] args) throws IOException {
JSONFileServer server = new JSONFileServer(new File("webapp/app"), 80);
Opleiding infoSysteem = new Opleiding();
// Nieuwe knop toevoegen :
// Maak nieuwe controller, maak object
// server.registerHandler
// elements.html : <link rel="import" href="{{te gebruiken klasse}}.html">
// in je controller : controle op pad
// routing.html : nieuwe page toevoegen
// in elements/{{nieuwe route}}/my-{{route}}.html
Controller controller = new Controller(infoSysteem);
// UserController userController = new UserController(infoSysteem);
// DocentController docentController = new DocentController(infoSysteem);
// StudentController studentController = new StudentController(infoSysteem);
// RoosterController roosterController = new RoosterController(infoSysteem);
// AbsentieController absentieController = new AbsentieController(infoSysteem);
// VakController vakController = new VakController(infoSysteem);
server.registerHandler("/api", controller);
// server.registerHandler("/login", userController);
// server.registerHandler("/docent/mijnvakken", docentController);
// server.registerHandler("/student/mijnmedestudenten", studentController);
// server.registerHandler("/student/mijnrooster", roosterController);
// server.registerHandler("/student/absenties", absentieController);
server.start();
}
} | FullCount/PrIS | src/controller/Application.java | 802 | // Maak nieuwe controller, maak object
| line_comment | nl | package controller;
import java.io.File;
import java.io.IOException;
import model.Opleiding;
import server.JSONFileServer;
public class Application {
/**
* Deze klasse is het startpunt voor de applicatie. Hierin maak je een server
* op een bepaalde poort (bijv. 8888). Daarna is er een PrIS-object gemaakt. Dit
* object fungeert als toegangspunt van het domeinmodel. Hiervandaan kan alle
* informatie bereikt worden.
*
* Om het domeinmodel en de Polymer-GUI aan elkaar te koppelen zijn diverse controllers
* gemaakt. Er zijn meerdere controllers om het overzichtelijk te houden. Je mag zoveel
* controller-klassen maken als je nodig denkt te hebben. Elke controller krijgt een
* koppeling naar het PrIS-object om benodigde informatie op te halen.
*
* Je moet wel elke URL die vanaf Polymer aangeroepen kan worden registreren! Dat is
* hieronder gedaan voor een drietal URLs. Je geeft daarbij ook aan welke controller
* de URL moet afhandelen.
*
* Als je alle URLs hebt geregistreerd kun je de server starten en de applicatie in de
* browser opvragen! Zie ook de controller-klassen voor een voorbeeld!
* @throws IOException
*
*/
public static void main(String[] args) throws IOException {
JSONFileServer server = new JSONFileServer(new File("webapp/app"), 80);
Opleiding infoSysteem = new Opleiding();
// Nieuwe knop toevoegen :
// Maak nieuwe<SUF>
// server.registerHandler
// elements.html : <link rel="import" href="{{te gebruiken klasse}}.html">
// in je controller : controle op pad
// routing.html : nieuwe page toevoegen
// in elements/{{nieuwe route}}/my-{{route}}.html
Controller controller = new Controller(infoSysteem);
// UserController userController = new UserController(infoSysteem);
// DocentController docentController = new DocentController(infoSysteem);
// StudentController studentController = new StudentController(infoSysteem);
// RoosterController roosterController = new RoosterController(infoSysteem);
// AbsentieController absentieController = new AbsentieController(infoSysteem);
// VakController vakController = new VakController(infoSysteem);
server.registerHandler("/api", controller);
// server.registerHandler("/login", userController);
// server.registerHandler("/docent/mijnvakken", docentController);
// server.registerHandler("/student/mijnmedestudenten", studentController);
// server.registerHandler("/student/mijnrooster", roosterController);
// server.registerHandler("/student/absenties", absentieController);
server.start();
}
} |
88314_20 | /*
* This file is part of the GeoLatte project.
*
* GeoLatte is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GeoLatte is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GeoLatte. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010 - 2011 and Ownership of code is shared by:
* Qmino bvba - Romeinsestraat 18 - 3001 Heverlee (http://www.qmino.com)
* Geovise bvba - Generaal Eisenhowerlei 9 - 2140 Antwerpen (http://www.geovise.com)
*/
package org.geolatte.geom.jts;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.geolatte.geom.*;
import org.geolatte.geom.crs.*;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Karel Maesen, Geovise BVBA, 2011 (original code)
* @author Yves Vandewoude, Qmino bvba, 2011 (bugfixes)
*/
public class JTS {
private static final PointSequenceCoordinateSequenceFactory pscsFactory = new
PointSequenceCoordinateSequenceFactory();
private static final Map<Class<? extends Geometry>, Class<? extends org.geolatte.geom.Geometry>> JTS2GLClassMap =
new HashMap<Class<? extends Geometry>, Class<? extends org.geolatte.geom.Geometry>>();
private static final ConcurrentHashMap<Integer, GeometryFactory> geometryFactories = new ConcurrentHashMap<>();
static {
//define the class mapping JTS -> Geolatte
JTS2GLClassMap.put(Point.class, org.geolatte.geom.Point.class);
JTS2GLClassMap.put(LineString.class, org.geolatte.geom.LineString.class);
JTS2GLClassMap.put(LinearRing.class, org.geolatte.geom.LinearRing.class);
JTS2GLClassMap.put(Polygon.class, org.geolatte.geom.Polygon.class);
JTS2GLClassMap.put(GeometryCollection.class, org.geolatte.geom.GeometryCollection.class);
JTS2GLClassMap.put(MultiPoint.class, org.geolatte.geom.MultiPoint.class);
JTS2GLClassMap.put(MultiLineString.class, org.geolatte.geom.MultiLineString.class);
JTS2GLClassMap.put(MultiPolygon.class, org.geolatte.geom.MultiPolygon.class);
}
/**
* Returns the JTS Geometry class that corresponds to the specified Geolatte Geometry class.
* <p>Geometry classes correspond iff they are of the same Geometry type in the SFS or SFA geometry model.</p>
*
* @param geometryClass the JTS Geometry class
* @return the corresponding o.g.geom class
* @throws IllegalArgumentException when the geometryClass parameter is null.
* @throws NoSuchElementException when no corresponding class can be found.
*/
public static Class<? extends Geometry> getCorrespondingJTSClass(Class<? extends org.geolatte.geom.Geometry>
geometryClass) {
if (geometryClass == null) throw new IllegalArgumentException("Null argument not allowed.");
for (Map.Entry<Class<? extends Geometry>, Class<? extends org.geolatte.geom.Geometry>> entry : JTS2GLClassMap
.entrySet()) {
if (entry.getValue() == geometryClass) {
return entry.getKey();
}
}
throw new NoSuchElementException(String.format("No mapping for class %s exists in JTS geom.", geometryClass
.getCanonicalName()));
}
/**
* Returns the Geolatte Geometry class that corresponds to the specified JTS class.
* <p>Geometry classes correspond iff they are of the same Geometry type in the SFS or SFA geometry model.</p>
*
* @param jtsGeometryClass the Geolatte Geometry class
* @return the corresponding o.g.geom class
* @throws IllegalArgumentException when the jtsGeometryClass parameter is null.
* @throws NoSuchElementException when no corresponding class can be found.
*/
static Class<? extends org.geolatte.geom.Geometry> getCorrespondingGeolatteClass(Class<? extends Geometry>
jtsGeometryClass) {
if (jtsGeometryClass == null) throw new IllegalArgumentException("Null argument not allowed.");
Class<? extends org.geolatte.geom.Geometry> corresponding = JTS2GLClassMap.get(jtsGeometryClass);
if (corresponding == null) {
throw new NoSuchElementException(String.format("No mapping for class %s exists in JTS geom.",
jtsGeometryClass.getCanonicalName()));
}
return corresponding;
}
/**
* Primary Factory method that converts a JTS geometry into an equivalent geolatte geometry
*
* @param jtsGeometry the jts geometry to convert
* @return an equivalent geolatte geometry
* @throws IllegalArgumentException when a null object is passed
*/
public static org.geolatte.geom.Geometry<?> from(org.locationtech.jts.geom.Geometry jtsGeometry) {
if (jtsGeometry == null) {
throw new IllegalArgumentException("Null object passed.");
}
Coordinate testCo = jtsGeometry.getCoordinate();
boolean is3D = !(testCo == null || Double.isNaN(testCo.z));
CoordinateReferenceSystem<?> crs = CrsRegistry.ifAbsentReturnProjected2D(jtsGeometry.getSRID());
if (is3D) {
crs = CoordinateReferenceSystems.addVerticalSystem(crs, LinearUnit.METER);
}
// to translate measure, add Measure as LinearSystem
boolean hasM = isMeasuredCoordinate(testCo)
&& !Double.isNaN(testCo.getM());
if (hasM) {
crs = CoordinateReferenceSystems.addLinearSystem(crs, LinearUnit.METER);
}
return from(jtsGeometry, crs);
}
private static boolean isMeasuredCoordinate(Coordinate testCo) {
return testCo instanceof CoordinateXYZM || testCo instanceof CoordinateXYM;
}
/**
* Factory method that converts a JTS geometry into an equivalent geolatte geometry and allows the caller to
* specify the CoordinateReferenceSystem of the resulting geolatte geometry.
*
* @param jtsGeometry the jtsGeometry
* @param crs the CoordinateReferenceSystem
* @return A geolatte geometry that corresponds with the given JTS geometry
* @throws IllegalArgumentException when a null object is passed
*/
public static <P extends Position> org.geolatte.geom.Geometry<P> from(Geometry jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry == null) {
throw new IllegalArgumentException("Null object passed.");
}
if (jtsGeometry instanceof Point) {
return from((Point) jtsGeometry, crs);
} else if (jtsGeometry instanceof LineString) {
return from((LineString) jtsGeometry, crs);
} else if (jtsGeometry instanceof Polygon) {
return from((Polygon) jtsGeometry, crs);
} else if (jtsGeometry instanceof MultiPoint) {
return from((MultiPoint) jtsGeometry, crs);
} else if (jtsGeometry instanceof MultiLineString) {
return from((MultiLineString) jtsGeometry, crs);
} else if (jtsGeometry instanceof MultiPolygon) {
return from((MultiPolygon) jtsGeometry, crs);
} else if (jtsGeometry instanceof GeometryCollection) {
return from((GeometryCollection) jtsGeometry, crs);
} else {
throw new JTSConversionException();
}
}
/**
* Primary factory method that converts a geolatte geometry into an equivalent jts geometry
*
* @param geometry the geolatte geometry to start from
* @param gFact the GeometryFactory to use for creating the JTS Geometry
* @return the equivalent JTS geometry
* @throws IllegalArgumentException when a null object is passed
*/
public static <P extends Position> org.locationtech.jts.geom.Geometry to(org.geolatte.geom.Geometry<P> geometry, GeometryFactory gFact) {
if (geometry == null || gFact == null) {
throw new IllegalArgumentException("Null object passed.");
}
if (geometry instanceof org.geolatte.geom.Point) {
return to((org.geolatte.geom.Point<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.LineString) {
return to((org.geolatte.geom.LineString<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.MultiPoint) {
return to((org.geolatte.geom.MultiPoint<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.Polygon) {
return to((org.geolatte.geom.Polygon<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.MultiLineString) {
return to((org.geolatte.geom.MultiLineString<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.MultiPolygon) {
return to((org.geolatte.geom.MultiPolygon<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.GeometryCollection) {
return to((org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>>) geometry, gFact);
} else {
throw new JTSConversionException();
}
}
public static <P extends Position> org.locationtech.jts.geom.Geometry to(org.geolatte.geom.Geometry<P> geometry) {
if (geometry == null) {
throw new IllegalArgumentException("Null object passed.");
}
GeometryFactory gFact = geometryFactory(geometry.getSRID());
return to(geometry, gFact);
}
private static GeometryFactory geometryFactory(int srid) {
return geometryFactories.computeIfAbsent(srid, id -> buildGeometryFactory(id));
}
private static GeometryFactory buildGeometryFactory(int srid) {
return new GeometryFactory(new PrecisionModel(), srid, pscsFactory);
}
/**
* Converts a JTS <code>Envelope</code> to a geolatte <code>Envelope</code>.
*
* @param jtsEnvelope the JTS Envelope to convert
* @return the corresponding geolatte Envelope.
* @throws IllegalArgumentException when a null object is passed
*/
public static org.geolatte.geom.Envelope<C2D> from(org.locationtech.jts.geom.Envelope jtsEnvelope) {
if (jtsEnvelope == null) {
throw new IllegalArgumentException("Null object passed.");
}
return new org.geolatte.geom.Envelope<C2D>(jtsEnvelope.getMinX(), jtsEnvelope.getMinY(), jtsEnvelope.getMaxX
(), jtsEnvelope.getMaxY(), CoordinateReferenceSystems.PROJECTED_2D_METER);
}
/**
* Converts a JTS <code>Envelope</code> to a geolatte <code>Envelope</code> with the
* specified CRS.
*
* @param jtsEnvelope the JTS Envelope to convert.
* @param crs the <code>CoordinateReferenceSystem</code> to use for the return value.
* @return the corresponding geolatte Envelope, having the CRS specified in the crsId parameter.
* @throws IllegalArgumentException when a null object is passed
*/
public static <P extends Position> org.geolatte.geom.Envelope<P> from(org.locationtech.jts.geom.Envelope
jtsEnvelope,
CoordinateReferenceSystem<P> crs) {
if (jtsEnvelope == null) {
throw new IllegalArgumentException("Null object passed.");
}
return new org.geolatte.geom.Envelope<P>(jtsEnvelope.getMinX(), jtsEnvelope.getMinY(), jtsEnvelope.getMaxX(),
jtsEnvelope.getMaxY(), crs);
}
/**
* Converts a Geolatte <code>Envelope</code> to a JTS <code>Envelope</code>.
*
* @param env the geolatte Envelope.
* @return the corresponding JTS Envelope.
* @throws IllegalArgumentException when a null object is passed
*/
public static org.locationtech.jts.geom.Envelope to(org.geolatte.geom.Envelope<?> env) {
if (env == null) {
throw new IllegalArgumentException("Null object passed.");
}
return new org.locationtech.jts.geom.Envelope(env.lowerLeft().getCoordinate(0), env.upperRight()
.getCoordinate(0), env.lowerLeft().getCoordinate(1), env.upperRight().getCoordinate(1));
}
///
/// Helpermethods: jts --> geolatte
///
/*
* Converts a jts multipolygon into a geolatte multipolygon
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.MultiPolygon<P> from(MultiPolygon jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.getNumGeometries() == 0) return new org.geolatte.geom.MultiPolygon<P>(crs);
org.geolatte.geom.Polygon<P>[] polygons = (org.geolatte.geom.Polygon<P>[]) new org.geolatte.geom
.Polygon[jtsGeometry.getNumGeometries()];
for (int i = 0; i < jtsGeometry.getNumGeometries(); i++) {
polygons[i] = from((Polygon) jtsGeometry.getGeometryN(i), crs);
}
return new org.geolatte.geom.MultiPolygon<P>(polygons);
}
/*
* Converts a jts polygon into a geolatte polygon
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.Polygon<P> from(Polygon jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.isEmpty()) {
return new org.geolatte.geom.Polygon<P>(crs);
}
org.geolatte.geom.LinearRing<P>[] rings = new org.geolatte.geom.LinearRing[jtsGeometry.getNumInteriorRing() +
1];
org.geolatte.geom.LineString<P> extRing = from(jtsGeometry.getExteriorRing(), crs);
rings[0] = new org.geolatte.geom.LinearRing(extRing.getPositions(), extRing.getCoordinateReferenceSystem());
for (int i = 1; i < rings.length; i++) {
org.geolatte.geom.LineString intRing = from(jtsGeometry.getInteriorRingN(i - 1), crs);
rings[i] = new org.geolatte.geom.LinearRing(intRing);
}
return new org.geolatte.geom.Polygon(rings);
}
/*
* Converts a jts multilinestring into a geolatte multilinestring
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.MultiLineString<P> from(MultiLineString jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.getNumGeometries() == 0) return new org.geolatte.geom.MultiLineString<P>(crs);
org.geolatte.geom.LineString<P>[] linestrings = new org.geolatte.geom.LineString[jtsGeometry.getNumGeometries
()];
for (int i = 0; i < linestrings.length; i++) {
linestrings[i] = from((LineString) jtsGeometry.getGeometryN(i), crs);
}
return new org.geolatte.geom.MultiLineString<P>(linestrings);
}
/*
* Converts a jts geometrycollection into a geolatte geometrycollection
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>> from
(GeometryCollection jtsGeometry, CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.getNumGeometries() == 0)
return new org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>>(crs);
org.geolatte.geom.Geometry<P>[] geoms = new org.geolatte.geom.Geometry[jtsGeometry.getNumGeometries()];
for (int i = 0; i < jtsGeometry.getNumGeometries(); i++) {
geoms[i] = from(jtsGeometry.getGeometryN(i), crs);
}
return new org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>>(geoms);
}
/*
* Converts a jts linestring into a geolatte linestring
*/
private static <P extends Position> org.geolatte.geom.LineString<P> from(LineString jtsLineString,
CoordinateReferenceSystem<P> crs) {
CoordinateSequence cs = jtsLineString.getCoordinateSequence();
return new org.geolatte.geom.LineString<P>(pscsFactory.toPositionSequence(cs, crs.getPositionClass(), crs),
crs);
}
/*
* Converts a jts multipoint into a geolatte multipoint
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.MultiPoint<P> from(MultiPoint jtsMultiPoint,
CoordinateReferenceSystem<P> crs) {
if (jtsMultiPoint == null || jtsMultiPoint.getNumGeometries() == 0)
return new org.geolatte.geom.MultiPoint<P>(crs);
org.geolatte.geom.Point<P>[] points = new org.geolatte.geom.Point[jtsMultiPoint.getNumGeometries()];
for (int i = 0; i < points.length; i++) {
points[i] = from((Point) jtsMultiPoint.getGeometryN(i), crs);
}
return new org.geolatte.geom.MultiPoint<P>(points);
}
/*
* Converts a jts point into a geolatte point
*/
private static <P extends Position> org.geolatte.geom.Point<P> from(org.locationtech.jts.geom.Point jtsPoint,
CoordinateReferenceSystem<P> crs) {
CoordinateSequence cs = jtsPoint.getCoordinateSequence();
return new org.geolatte.geom.Point<P>(pscsFactory.toPositionSequence(cs, crs.getPositionClass(), crs), crs);
}
///
/// Helpermethods: geolatte --> jts
///
private static <P extends Position> Polygon to(org.geolatte.geom.Polygon<P> polygon, GeometryFactory gFact) {
LinearRing shell = to(polygon.getExteriorRing(), gFact);
LinearRing[] holes = new LinearRing[polygon.getNumInteriorRing()];
for (int i = 0; i < holes.length; i++) {
holes[i] = to(polygon.getInteriorRingN(i), gFact);
}
return gFact.createPolygon(shell, holes);
}
private static <P extends Position> Point to(org.geolatte.geom.Point<P> point, GeometryFactory gFact) {
return gFact.createPoint(sequenceOf(point));
}
private static <P extends Position> LineString to(org.geolatte.geom.LineString<P> lineString, GeometryFactory gFact) {
return gFact.createLineString(sequenceOf(lineString));
}
private static <P extends Position> LinearRing to(org.geolatte.geom.LinearRing<P> linearRing, GeometryFactory gFact) {
return gFact.createLinearRing(sequenceOf(linearRing));
}
private static <P extends Position> MultiPoint to(org.geolatte.geom.MultiPoint<P> multiPoint, GeometryFactory gFact) {
Point[] points = new Point[multiPoint.getNumGeometries()];
for (int i = 0; i < multiPoint.getNumGeometries(); i++) {
points[i] = to(multiPoint.getGeometryN(i), gFact);
}
return gFact.createMultiPoint(points);
}
private static <P extends Position> MultiLineString to(org.geolatte.geom.MultiLineString<P> multiLineString, GeometryFactory gFact) {
LineString[] lineStrings = new LineString[multiLineString.getNumGeometries()];
for (int i = 0; i < multiLineString.getNumGeometries(); i++) {
lineStrings[i] = to(multiLineString.getGeometryN(i), gFact);
}
return gFact.createMultiLineString(lineStrings);
}
private static <P extends Position> MultiPolygon to(org.geolatte.geom.MultiPolygon<P> multiPolygon, GeometryFactory gFact) {
Polygon[] polygons = new Polygon[multiPolygon.getNumGeometries()];
for (int i = 0; i < multiPolygon.getNumGeometries(); i++) {
polygons[i] = to(multiPolygon.getGeometryN(i), gFact);
}
return gFact.createMultiPolygon(polygons);
}
private static <P extends Position> GeometryCollection to(org.geolatte.geom.GeometryCollection<P, org.geolatte
.geom.Geometry<P>> collection, GeometryFactory gFact) {
Geometry[] geoms = new Geometry[collection.getNumGeometries()];
for (int i = 0; i < collection.getNumGeometries(); i++) {
geoms[i] = to(collection.getGeometryN(i));
}
return gFact.createGeometryCollection(geoms);
}
private static CoordinateSequence sequenceOf(org.geolatte.geom.Geometry geometry) {
if (geometry == null) {
throw new JTSConversionException("Can't convert null geometries.");
} else {
return (CoordinateSequence) geometry.getPositions();
}
}
}
| Furcube/geolatte-geom | geom/src/main/java/org/geolatte/geom/jts/JTS.java | 6,598 | /// Helpermethods: geolatte --> jts | line_comment | nl | /*
* This file is part of the GeoLatte project.
*
* GeoLatte is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GeoLatte is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GeoLatte. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010 - 2011 and Ownership of code is shared by:
* Qmino bvba - Romeinsestraat 18 - 3001 Heverlee (http://www.qmino.com)
* Geovise bvba - Generaal Eisenhowerlei 9 - 2140 Antwerpen (http://www.geovise.com)
*/
package org.geolatte.geom.jts;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.geolatte.geom.*;
import org.geolatte.geom.crs.*;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Karel Maesen, Geovise BVBA, 2011 (original code)
* @author Yves Vandewoude, Qmino bvba, 2011 (bugfixes)
*/
public class JTS {
private static final PointSequenceCoordinateSequenceFactory pscsFactory = new
PointSequenceCoordinateSequenceFactory();
private static final Map<Class<? extends Geometry>, Class<? extends org.geolatte.geom.Geometry>> JTS2GLClassMap =
new HashMap<Class<? extends Geometry>, Class<? extends org.geolatte.geom.Geometry>>();
private static final ConcurrentHashMap<Integer, GeometryFactory> geometryFactories = new ConcurrentHashMap<>();
static {
//define the class mapping JTS -> Geolatte
JTS2GLClassMap.put(Point.class, org.geolatte.geom.Point.class);
JTS2GLClassMap.put(LineString.class, org.geolatte.geom.LineString.class);
JTS2GLClassMap.put(LinearRing.class, org.geolatte.geom.LinearRing.class);
JTS2GLClassMap.put(Polygon.class, org.geolatte.geom.Polygon.class);
JTS2GLClassMap.put(GeometryCollection.class, org.geolatte.geom.GeometryCollection.class);
JTS2GLClassMap.put(MultiPoint.class, org.geolatte.geom.MultiPoint.class);
JTS2GLClassMap.put(MultiLineString.class, org.geolatte.geom.MultiLineString.class);
JTS2GLClassMap.put(MultiPolygon.class, org.geolatte.geom.MultiPolygon.class);
}
/**
* Returns the JTS Geometry class that corresponds to the specified Geolatte Geometry class.
* <p>Geometry classes correspond iff they are of the same Geometry type in the SFS or SFA geometry model.</p>
*
* @param geometryClass the JTS Geometry class
* @return the corresponding o.g.geom class
* @throws IllegalArgumentException when the geometryClass parameter is null.
* @throws NoSuchElementException when no corresponding class can be found.
*/
public static Class<? extends Geometry> getCorrespondingJTSClass(Class<? extends org.geolatte.geom.Geometry>
geometryClass) {
if (geometryClass == null) throw new IllegalArgumentException("Null argument not allowed.");
for (Map.Entry<Class<? extends Geometry>, Class<? extends org.geolatte.geom.Geometry>> entry : JTS2GLClassMap
.entrySet()) {
if (entry.getValue() == geometryClass) {
return entry.getKey();
}
}
throw new NoSuchElementException(String.format("No mapping for class %s exists in JTS geom.", geometryClass
.getCanonicalName()));
}
/**
* Returns the Geolatte Geometry class that corresponds to the specified JTS class.
* <p>Geometry classes correspond iff they are of the same Geometry type in the SFS or SFA geometry model.</p>
*
* @param jtsGeometryClass the Geolatte Geometry class
* @return the corresponding o.g.geom class
* @throws IllegalArgumentException when the jtsGeometryClass parameter is null.
* @throws NoSuchElementException when no corresponding class can be found.
*/
static Class<? extends org.geolatte.geom.Geometry> getCorrespondingGeolatteClass(Class<? extends Geometry>
jtsGeometryClass) {
if (jtsGeometryClass == null) throw new IllegalArgumentException("Null argument not allowed.");
Class<? extends org.geolatte.geom.Geometry> corresponding = JTS2GLClassMap.get(jtsGeometryClass);
if (corresponding == null) {
throw new NoSuchElementException(String.format("No mapping for class %s exists in JTS geom.",
jtsGeometryClass.getCanonicalName()));
}
return corresponding;
}
/**
* Primary Factory method that converts a JTS geometry into an equivalent geolatte geometry
*
* @param jtsGeometry the jts geometry to convert
* @return an equivalent geolatte geometry
* @throws IllegalArgumentException when a null object is passed
*/
public static org.geolatte.geom.Geometry<?> from(org.locationtech.jts.geom.Geometry jtsGeometry) {
if (jtsGeometry == null) {
throw new IllegalArgumentException("Null object passed.");
}
Coordinate testCo = jtsGeometry.getCoordinate();
boolean is3D = !(testCo == null || Double.isNaN(testCo.z));
CoordinateReferenceSystem<?> crs = CrsRegistry.ifAbsentReturnProjected2D(jtsGeometry.getSRID());
if (is3D) {
crs = CoordinateReferenceSystems.addVerticalSystem(crs, LinearUnit.METER);
}
// to translate measure, add Measure as LinearSystem
boolean hasM = isMeasuredCoordinate(testCo)
&& !Double.isNaN(testCo.getM());
if (hasM) {
crs = CoordinateReferenceSystems.addLinearSystem(crs, LinearUnit.METER);
}
return from(jtsGeometry, crs);
}
private static boolean isMeasuredCoordinate(Coordinate testCo) {
return testCo instanceof CoordinateXYZM || testCo instanceof CoordinateXYM;
}
/**
* Factory method that converts a JTS geometry into an equivalent geolatte geometry and allows the caller to
* specify the CoordinateReferenceSystem of the resulting geolatte geometry.
*
* @param jtsGeometry the jtsGeometry
* @param crs the CoordinateReferenceSystem
* @return A geolatte geometry that corresponds with the given JTS geometry
* @throws IllegalArgumentException when a null object is passed
*/
public static <P extends Position> org.geolatte.geom.Geometry<P> from(Geometry jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry == null) {
throw new IllegalArgumentException("Null object passed.");
}
if (jtsGeometry instanceof Point) {
return from((Point) jtsGeometry, crs);
} else if (jtsGeometry instanceof LineString) {
return from((LineString) jtsGeometry, crs);
} else if (jtsGeometry instanceof Polygon) {
return from((Polygon) jtsGeometry, crs);
} else if (jtsGeometry instanceof MultiPoint) {
return from((MultiPoint) jtsGeometry, crs);
} else if (jtsGeometry instanceof MultiLineString) {
return from((MultiLineString) jtsGeometry, crs);
} else if (jtsGeometry instanceof MultiPolygon) {
return from((MultiPolygon) jtsGeometry, crs);
} else if (jtsGeometry instanceof GeometryCollection) {
return from((GeometryCollection) jtsGeometry, crs);
} else {
throw new JTSConversionException();
}
}
/**
* Primary factory method that converts a geolatte geometry into an equivalent jts geometry
*
* @param geometry the geolatte geometry to start from
* @param gFact the GeometryFactory to use for creating the JTS Geometry
* @return the equivalent JTS geometry
* @throws IllegalArgumentException when a null object is passed
*/
public static <P extends Position> org.locationtech.jts.geom.Geometry to(org.geolatte.geom.Geometry<P> geometry, GeometryFactory gFact) {
if (geometry == null || gFact == null) {
throw new IllegalArgumentException("Null object passed.");
}
if (geometry instanceof org.geolatte.geom.Point) {
return to((org.geolatte.geom.Point<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.LineString) {
return to((org.geolatte.geom.LineString<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.MultiPoint) {
return to((org.geolatte.geom.MultiPoint<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.Polygon) {
return to((org.geolatte.geom.Polygon<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.MultiLineString) {
return to((org.geolatte.geom.MultiLineString<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.MultiPolygon) {
return to((org.geolatte.geom.MultiPolygon<P>) geometry, gFact);
} else if (geometry instanceof org.geolatte.geom.GeometryCollection) {
return to((org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>>) geometry, gFact);
} else {
throw new JTSConversionException();
}
}
public static <P extends Position> org.locationtech.jts.geom.Geometry to(org.geolatte.geom.Geometry<P> geometry) {
if (geometry == null) {
throw new IllegalArgumentException("Null object passed.");
}
GeometryFactory gFact = geometryFactory(geometry.getSRID());
return to(geometry, gFact);
}
private static GeometryFactory geometryFactory(int srid) {
return geometryFactories.computeIfAbsent(srid, id -> buildGeometryFactory(id));
}
private static GeometryFactory buildGeometryFactory(int srid) {
return new GeometryFactory(new PrecisionModel(), srid, pscsFactory);
}
/**
* Converts a JTS <code>Envelope</code> to a geolatte <code>Envelope</code>.
*
* @param jtsEnvelope the JTS Envelope to convert
* @return the corresponding geolatte Envelope.
* @throws IllegalArgumentException when a null object is passed
*/
public static org.geolatte.geom.Envelope<C2D> from(org.locationtech.jts.geom.Envelope jtsEnvelope) {
if (jtsEnvelope == null) {
throw new IllegalArgumentException("Null object passed.");
}
return new org.geolatte.geom.Envelope<C2D>(jtsEnvelope.getMinX(), jtsEnvelope.getMinY(), jtsEnvelope.getMaxX
(), jtsEnvelope.getMaxY(), CoordinateReferenceSystems.PROJECTED_2D_METER);
}
/**
* Converts a JTS <code>Envelope</code> to a geolatte <code>Envelope</code> with the
* specified CRS.
*
* @param jtsEnvelope the JTS Envelope to convert.
* @param crs the <code>CoordinateReferenceSystem</code> to use for the return value.
* @return the corresponding geolatte Envelope, having the CRS specified in the crsId parameter.
* @throws IllegalArgumentException when a null object is passed
*/
public static <P extends Position> org.geolatte.geom.Envelope<P> from(org.locationtech.jts.geom.Envelope
jtsEnvelope,
CoordinateReferenceSystem<P> crs) {
if (jtsEnvelope == null) {
throw new IllegalArgumentException("Null object passed.");
}
return new org.geolatte.geom.Envelope<P>(jtsEnvelope.getMinX(), jtsEnvelope.getMinY(), jtsEnvelope.getMaxX(),
jtsEnvelope.getMaxY(), crs);
}
/**
* Converts a Geolatte <code>Envelope</code> to a JTS <code>Envelope</code>.
*
* @param env the geolatte Envelope.
* @return the corresponding JTS Envelope.
* @throws IllegalArgumentException when a null object is passed
*/
public static org.locationtech.jts.geom.Envelope to(org.geolatte.geom.Envelope<?> env) {
if (env == null) {
throw new IllegalArgumentException("Null object passed.");
}
return new org.locationtech.jts.geom.Envelope(env.lowerLeft().getCoordinate(0), env.upperRight()
.getCoordinate(0), env.lowerLeft().getCoordinate(1), env.upperRight().getCoordinate(1));
}
///
/// Helpermethods: jts --> geolatte
///
/*
* Converts a jts multipolygon into a geolatte multipolygon
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.MultiPolygon<P> from(MultiPolygon jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.getNumGeometries() == 0) return new org.geolatte.geom.MultiPolygon<P>(crs);
org.geolatte.geom.Polygon<P>[] polygons = (org.geolatte.geom.Polygon<P>[]) new org.geolatte.geom
.Polygon[jtsGeometry.getNumGeometries()];
for (int i = 0; i < jtsGeometry.getNumGeometries(); i++) {
polygons[i] = from((Polygon) jtsGeometry.getGeometryN(i), crs);
}
return new org.geolatte.geom.MultiPolygon<P>(polygons);
}
/*
* Converts a jts polygon into a geolatte polygon
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.Polygon<P> from(Polygon jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.isEmpty()) {
return new org.geolatte.geom.Polygon<P>(crs);
}
org.geolatte.geom.LinearRing<P>[] rings = new org.geolatte.geom.LinearRing[jtsGeometry.getNumInteriorRing() +
1];
org.geolatte.geom.LineString<P> extRing = from(jtsGeometry.getExteriorRing(), crs);
rings[0] = new org.geolatte.geom.LinearRing(extRing.getPositions(), extRing.getCoordinateReferenceSystem());
for (int i = 1; i < rings.length; i++) {
org.geolatte.geom.LineString intRing = from(jtsGeometry.getInteriorRingN(i - 1), crs);
rings[i] = new org.geolatte.geom.LinearRing(intRing);
}
return new org.geolatte.geom.Polygon(rings);
}
/*
* Converts a jts multilinestring into a geolatte multilinestring
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.MultiLineString<P> from(MultiLineString jtsGeometry,
CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.getNumGeometries() == 0) return new org.geolatte.geom.MultiLineString<P>(crs);
org.geolatte.geom.LineString<P>[] linestrings = new org.geolatte.geom.LineString[jtsGeometry.getNumGeometries
()];
for (int i = 0; i < linestrings.length; i++) {
linestrings[i] = from((LineString) jtsGeometry.getGeometryN(i), crs);
}
return new org.geolatte.geom.MultiLineString<P>(linestrings);
}
/*
* Converts a jts geometrycollection into a geolatte geometrycollection
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>> from
(GeometryCollection jtsGeometry, CoordinateReferenceSystem<P> crs) {
if (jtsGeometry.getNumGeometries() == 0)
return new org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>>(crs);
org.geolatte.geom.Geometry<P>[] geoms = new org.geolatte.geom.Geometry[jtsGeometry.getNumGeometries()];
for (int i = 0; i < jtsGeometry.getNumGeometries(); i++) {
geoms[i] = from(jtsGeometry.getGeometryN(i), crs);
}
return new org.geolatte.geom.GeometryCollection<P, org.geolatte.geom.Geometry<P>>(geoms);
}
/*
* Converts a jts linestring into a geolatte linestring
*/
private static <P extends Position> org.geolatte.geom.LineString<P> from(LineString jtsLineString,
CoordinateReferenceSystem<P> crs) {
CoordinateSequence cs = jtsLineString.getCoordinateSequence();
return new org.geolatte.geom.LineString<P>(pscsFactory.toPositionSequence(cs, crs.getPositionClass(), crs),
crs);
}
/*
* Converts a jts multipoint into a geolatte multipoint
*/
@SuppressWarnings("unchecked")
private static <P extends Position> org.geolatte.geom.MultiPoint<P> from(MultiPoint jtsMultiPoint,
CoordinateReferenceSystem<P> crs) {
if (jtsMultiPoint == null || jtsMultiPoint.getNumGeometries() == 0)
return new org.geolatte.geom.MultiPoint<P>(crs);
org.geolatte.geom.Point<P>[] points = new org.geolatte.geom.Point[jtsMultiPoint.getNumGeometries()];
for (int i = 0; i < points.length; i++) {
points[i] = from((Point) jtsMultiPoint.getGeometryN(i), crs);
}
return new org.geolatte.geom.MultiPoint<P>(points);
}
/*
* Converts a jts point into a geolatte point
*/
private static <P extends Position> org.geolatte.geom.Point<P> from(org.locationtech.jts.geom.Point jtsPoint,
CoordinateReferenceSystem<P> crs) {
CoordinateSequence cs = jtsPoint.getCoordinateSequence();
return new org.geolatte.geom.Point<P>(pscsFactory.toPositionSequence(cs, crs.getPositionClass(), crs), crs);
}
///
/// Helpermethods: geolatte<SUF>
///
private static <P extends Position> Polygon to(org.geolatte.geom.Polygon<P> polygon, GeometryFactory gFact) {
LinearRing shell = to(polygon.getExteriorRing(), gFact);
LinearRing[] holes = new LinearRing[polygon.getNumInteriorRing()];
for (int i = 0; i < holes.length; i++) {
holes[i] = to(polygon.getInteriorRingN(i), gFact);
}
return gFact.createPolygon(shell, holes);
}
private static <P extends Position> Point to(org.geolatte.geom.Point<P> point, GeometryFactory gFact) {
return gFact.createPoint(sequenceOf(point));
}
private static <P extends Position> LineString to(org.geolatte.geom.LineString<P> lineString, GeometryFactory gFact) {
return gFact.createLineString(sequenceOf(lineString));
}
private static <P extends Position> LinearRing to(org.geolatte.geom.LinearRing<P> linearRing, GeometryFactory gFact) {
return gFact.createLinearRing(sequenceOf(linearRing));
}
private static <P extends Position> MultiPoint to(org.geolatte.geom.MultiPoint<P> multiPoint, GeometryFactory gFact) {
Point[] points = new Point[multiPoint.getNumGeometries()];
for (int i = 0; i < multiPoint.getNumGeometries(); i++) {
points[i] = to(multiPoint.getGeometryN(i), gFact);
}
return gFact.createMultiPoint(points);
}
private static <P extends Position> MultiLineString to(org.geolatte.geom.MultiLineString<P> multiLineString, GeometryFactory gFact) {
LineString[] lineStrings = new LineString[multiLineString.getNumGeometries()];
for (int i = 0; i < multiLineString.getNumGeometries(); i++) {
lineStrings[i] = to(multiLineString.getGeometryN(i), gFact);
}
return gFact.createMultiLineString(lineStrings);
}
private static <P extends Position> MultiPolygon to(org.geolatte.geom.MultiPolygon<P> multiPolygon, GeometryFactory gFact) {
Polygon[] polygons = new Polygon[multiPolygon.getNumGeometries()];
for (int i = 0; i < multiPolygon.getNumGeometries(); i++) {
polygons[i] = to(multiPolygon.getGeometryN(i), gFact);
}
return gFact.createMultiPolygon(polygons);
}
private static <P extends Position> GeometryCollection to(org.geolatte.geom.GeometryCollection<P, org.geolatte
.geom.Geometry<P>> collection, GeometryFactory gFact) {
Geometry[] geoms = new Geometry[collection.getNumGeometries()];
for (int i = 0; i < collection.getNumGeometries(); i++) {
geoms[i] = to(collection.getGeometryN(i));
}
return gFact.createGeometryCollection(geoms);
}
private static CoordinateSequence sequenceOf(org.geolatte.geom.Geometry geometry) {
if (geometry == null) {
throw new JTSConversionException("Can't convert null geometries.");
} else {
return (CoordinateSequence) geometry.getPositions();
}
}
}
|
32060_12 | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class Geom {
private Geom() {
}
/* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->t = 0 and
* let r be the negated result (this evaluates (uw)(v->s)), then
* r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->s = 0 and
* let r be the negated result (this evaluates (uw)(v->t)), then
* r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Returns a number whose sign matches TransEval(u,v,w) but which
* is cheaper to evaluate. Returns > 0, == 0 , or < 0
* as v is above, on, or below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results
* on some degenerate inputs, so the client must have some way to
* handle this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1,
GLUvertex o2, GLUvertex d2,
GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
double z1, z2;
/* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering,
* and interpolate the intersection s-value from these. Then repeat
* using the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
}
| Fyxar/Air | src/main/java/org/lwjglx/util/glu/tessellation/Geom.java | 4,278 | /* Interpolate between o2 and d1 */ | block_comment | nl | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjglx.util.glu.tessellation;
class Geom {
private Geom() {
}
/* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->t = 0 and
* let r be the negated result (this evaluates (uw)(v->s)), then
* r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->s = 0 and
* let r be the negated result (this evaluates (uw)(v->t)), then
* r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Returns a number whose sign matches TransEval(u,v,w) but which
* is cheaper to evaluate. Returns > 0, == 0 , or < 0
* as v is above, on, or below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results
* on some degenerate inputs, so the client must have some way to
* handle this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1,
GLUvertex o2, GLUvertex d2,
GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
double z1, z2;
/* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering,
* and interpolate the intersection s-value from these. Then repeat
* using the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2<SUF>*/
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
}
|
110824_8 | package tracks.levelGeneration;
import java.util.Random;
public class TestLevelGeneration {
public static void main(String[] args) {
// Available Level Generators
String randomLevelGenerator = "tracks.levelGeneration.randomLevelGenerator.LevelGenerator";
String geneticGenerator = "tracks.levelGeneration.geneticLevelGenerator.LevelGenerator";
String constructiveLevelGenerator = "tracks.levelGeneration.constructiveLevelGenerator.LevelGenerator";
String gamesPath = "examples/gridphysics/";
String physicsGamesPath = "examples/contphysics/";
String generateLevelPath = gamesPath;
String games[] = new String[] { "aliens", "angelsdemons", "assemblyline", "avoidgeorge", "bait", // 0-4
"beltmanager", "blacksmoke", "boloadventures", "bomber", "bomberman", // 5-9
"boulderchase", "boulderdash", "brainman", "butterflies", "cakybaky", // 10-14
"camelRace", "catapults", "chainreaction", "chase", "chipschallenge", // 15-19
"clusters", "colourescape", "chopper", "cookmepasta", "cops", // 20-24
"crossfire", "defem", "defender", "digdug", "dungeon", // 25-29
"eighthpassenger", "eggomania", "enemycitadel", "escape", "factorymanager", // 30-34
"firecaster", "fireman", "firestorms", "freeway", "frogs", // 35-39
"garbagecollector", "gymkhana", "hungrybirds", "iceandfire", "ikaruga", // 40-44
"infection", "intersection", "islands", "jaws", "killBillVol1", // 45-49
"labyrinth", "labyrinthdual", "lasers", "lasers2", "lemmings", // 50-54
"missilecommand", "modality", "overload", "pacman", "painter", // 55-59
"pokemon", "plants", "plaqueattack", "portals", "raceBet", // 60-64
"raceBet2", "realportals", "realsokoban", "rivers", "roadfighter", // 65-69
"roguelike", "run", "seaquest", "sheriff", "shipwreck", // 70-74
"sokoban", "solarfox", "superman", "surround", "survivezombies", // 75-79
"tercio", "thecitadel", "thesnowman", "waitforbreakfast", "watergame", // 80-84
"waves", "whackamole", "wildgunman", "witnessprotection", "wrapsokoban", // 85-89
"zelda", "zenpuzzle"}; //90, 91
String recordActionsFile = null;// "actions_" + games[gameIdx] + "_lvl"
// + levelIdx + "_" + seed + ".txt";
// where to record the actions
// executed. null if not to save.
// Other settings
int seed = new Random().nextInt();
int gameIdx = 11;
String recordLevelFile = generateLevelPath + games[gameIdx] + "_glvl.txt";
String game = generateLevelPath + games[gameIdx] + ".txt";
// 1. This starts a game, in a generated level created by a specific level generator
if(LevelGenMachine.generateOneLevel(game, constructiveLevelGenerator, recordLevelFile)){
LevelGenMachine.playOneGeneratedLevel(game, recordActionsFile, recordLevelFile, seed);
}
// 2. This generates numberOfLevels levels.
// String levelGenerator = "tracks.levelGeneration." + args[0] + ".LevelGenerator";
// int numberOfLevels = 5;
// tracks.levelGeneration.randomLevelGenerator.LevelGenerator.includeBorders = true;
// String[] folderName = levelGenerator.split("\\.");
// generateLevelPath = "examples/generatedLevels/" + folderName[1] + "/";
// game = gamesPath + args[1] + ".txt";
// for (int i = 0; i < numberOfLevels; i++) {
// recordLevelFile = generateLevelPath + args[1] + "_lvl" + i + ".txt";
// LevelGenMachine.generateOneLevel(game, levelGenerator, recordLevelFile);
//}
}
}
| GAIGResearch/GVGAI | src/tracks/levelGeneration/TestLevelGeneration.java | 1,202 | // int numberOfLevels = 5; | line_comment | nl | package tracks.levelGeneration;
import java.util.Random;
public class TestLevelGeneration {
public static void main(String[] args) {
// Available Level Generators
String randomLevelGenerator = "tracks.levelGeneration.randomLevelGenerator.LevelGenerator";
String geneticGenerator = "tracks.levelGeneration.geneticLevelGenerator.LevelGenerator";
String constructiveLevelGenerator = "tracks.levelGeneration.constructiveLevelGenerator.LevelGenerator";
String gamesPath = "examples/gridphysics/";
String physicsGamesPath = "examples/contphysics/";
String generateLevelPath = gamesPath;
String games[] = new String[] { "aliens", "angelsdemons", "assemblyline", "avoidgeorge", "bait", // 0-4
"beltmanager", "blacksmoke", "boloadventures", "bomber", "bomberman", // 5-9
"boulderchase", "boulderdash", "brainman", "butterflies", "cakybaky", // 10-14
"camelRace", "catapults", "chainreaction", "chase", "chipschallenge", // 15-19
"clusters", "colourescape", "chopper", "cookmepasta", "cops", // 20-24
"crossfire", "defem", "defender", "digdug", "dungeon", // 25-29
"eighthpassenger", "eggomania", "enemycitadel", "escape", "factorymanager", // 30-34
"firecaster", "fireman", "firestorms", "freeway", "frogs", // 35-39
"garbagecollector", "gymkhana", "hungrybirds", "iceandfire", "ikaruga", // 40-44
"infection", "intersection", "islands", "jaws", "killBillVol1", // 45-49
"labyrinth", "labyrinthdual", "lasers", "lasers2", "lemmings", // 50-54
"missilecommand", "modality", "overload", "pacman", "painter", // 55-59
"pokemon", "plants", "plaqueattack", "portals", "raceBet", // 60-64
"raceBet2", "realportals", "realsokoban", "rivers", "roadfighter", // 65-69
"roguelike", "run", "seaquest", "sheriff", "shipwreck", // 70-74
"sokoban", "solarfox", "superman", "surround", "survivezombies", // 75-79
"tercio", "thecitadel", "thesnowman", "waitforbreakfast", "watergame", // 80-84
"waves", "whackamole", "wildgunman", "witnessprotection", "wrapsokoban", // 85-89
"zelda", "zenpuzzle"}; //90, 91
String recordActionsFile = null;// "actions_" + games[gameIdx] + "_lvl"
// + levelIdx + "_" + seed + ".txt";
// where to record the actions
// executed. null if not to save.
// Other settings
int seed = new Random().nextInt();
int gameIdx = 11;
String recordLevelFile = generateLevelPath + games[gameIdx] + "_glvl.txt";
String game = generateLevelPath + games[gameIdx] + ".txt";
// 1. This starts a game, in a generated level created by a specific level generator
if(LevelGenMachine.generateOneLevel(game, constructiveLevelGenerator, recordLevelFile)){
LevelGenMachine.playOneGeneratedLevel(game, recordActionsFile, recordLevelFile, seed);
}
// 2. This generates numberOfLevels levels.
// String levelGenerator = "tracks.levelGeneration." + args[0] + ".LevelGenerator";
// int numberOfLevels<SUF>
// tracks.levelGeneration.randomLevelGenerator.LevelGenerator.includeBorders = true;
// String[] folderName = levelGenerator.split("\\.");
// generateLevelPath = "examples/generatedLevels/" + folderName[1] + "/";
// game = gamesPath + args[1] + ".txt";
// for (int i = 0; i < numberOfLevels; i++) {
// recordLevelFile = generateLevelPath + args[1] + "_lvl" + i + ".txt";
// LevelGenMachine.generateOneLevel(game, levelGenerator, recordLevelFile);
//}
}
}
|
29160_42 | // ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = -1; // 630;
public static final int ZONE_HEIGHT = 580; // 630;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int (zone map width)
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double (mim meters between events)
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default zoom without points)
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int (update interval seconds)
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_radius_device[] = new String[] { "auto.skipRadius" , "auto.skipRadius.device" }; // int (skip radius)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
public static final String PROP_auto_radius_fleet[] = new String[] { "auto.skipRadius" , "auto.skipRadius.fleet" }; // int (skip radius)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_include[] = new String[] { "javascript.include", "javascript.src" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
public static final String PROP_createMapCallback[] = new String[] { "createMapCallback" }; // String (JSMap provider JS)
public static final String PROP_postMapInitCallback[] = new String[] { "postMapInitCallback" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
** /
public int getZoneWidth();
*/
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
** /
public int getZoneHeight();
*/
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Gets the default zoom/scale level for this MapProvider when no pushpins are displayed
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getDefaultZoom(int dft);
/**
*** Gets the default zoom/scale level for this MapProvider when displaying pushpins
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getPushpinZoom(int dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
//@Deprecated
//public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinite)
**/
public long getAutoUpdateCount(boolean isFleet);
/**
*** Returns the auto-update skip-radius
*** @param isFleet True for fleet map
*** @return The auto-update skip-radius (0 for no skip)
**/
public double getAutoUpdateSkipRadius(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState)
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
| GBPA/OpenGTS | src/org/opengts/war/tools/MapProvider.java | 6,588 | // int (zone map width) | line_comment | nl | // ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = -1; // 630;
public static final int ZONE_HEIGHT = 580; // 630;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int <SUF>
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double (mim meters between events)
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default zoom without points)
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int (update interval seconds)
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_radius_device[] = new String[] { "auto.skipRadius" , "auto.skipRadius.device" }; // int (skip radius)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
public static final String PROP_auto_radius_fleet[] = new String[] { "auto.skipRadius" , "auto.skipRadius.fleet" }; // int (skip radius)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_include[] = new String[] { "javascript.include", "javascript.src" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
public static final String PROP_createMapCallback[] = new String[] { "createMapCallback" }; // String (JSMap provider JS)
public static final String PROP_postMapInitCallback[] = new String[] { "postMapInitCallback" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
** /
public int getZoneWidth();
*/
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
** /
public int getZoneHeight();
*/
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Gets the default zoom/scale level for this MapProvider when no pushpins are displayed
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getDefaultZoom(int dft);
/**
*** Gets the default zoom/scale level for this MapProvider when displaying pushpins
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getPushpinZoom(int dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
//@Deprecated
//public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinite)
**/
public long getAutoUpdateCount(boolean isFleet);
/**
*** Returns the auto-update skip-radius
*** @param isFleet True for fleet map
*** @return The auto-update skip-radius (0 for no skip)
**/
public double getAutoUpdateSkipRadius(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState)
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
|
205479_15 | package de.tudarmstadt.gdi1.project.cipher.enigma;
import java.util.List;
import de.tudarmstadt.gdi1.project.cipher.enigma.Enigma;
/**
* Implementiert das Enigma Interface.
* @author Quoc Thong Huynh, Dennis Kuhn, Moritz Matthiesen, Erik Laurin Strelow
*
*/
public class EnigmaImpl implements Enigma {
/**
* Liste von Rotoren
*/
List<Rotor> rotors;
/**
* Das Steckbrett
*/
PinBoard pinboard;
/**
* Umkehrrotor
*/
ReverseRotor reverseRotor;
/**
* Konstruktor der Enigma
* @param rotors Liste der Rotoren
* @param pinboard Das Steckbrett
* @param reverseRotor Der Umkehrrotor
*/
public EnigmaImpl (List<Rotor> rotors, PinBoard pinboard, ReverseRotor reverseRotor){
this.rotors = rotors;
this.pinboard = pinboard;
this.reverseRotor = reverseRotor;
}
@Override
public String encrypt(String text){
char[] chars = text.toCharArray();
char[] transChars = new char[chars.length];
String result = "";
int i = 0;
//Einzelnen Buchstaben durch Pinboard und durch alle Rotoren
for(Character c: chars){
transChars[i] = pinboard.translate(c);
//Buchstaben durch alle Rotoren pr��geln
for(int j = 0; j < rotors.size(); j++){
transChars[i] = rotors.get(j).translate(transChars[i], true);
}
//Buchstaben durch reverseRotor werfen
transChars[i] = reverseRotor.translate(transChars[i]);
//Buchstaben durch alle Rotoren in umgekehrter Reihenfolge werfen
for(int k = rotors.size()-1; k >= 0; k--){
transChars[i] = rotors.get(k).translate(transChars[i], false);
}
transChars[i]=pinboard.translate(transChars[i]);
/**for (int j = 1; rotors.get(j-1).rotate() ; j++){
rotors.get(j).rotate();
}**/
RotationAllRotors(0);
result += transChars[i];
i++;
}
for (int z = 0; z < rotors.size(); z++) rotors.get(z).reset();
return result;
}
/**
* Hilfsprozedur RotationAllRotors: Rotiert stets den Rotor an der Stelle i, prueft ob rotate() true ausgibt (also eine komplette Umdrehung erfolgt ist) und ob es einen
* weiteren Rotor gibt, wenn ja wird RotationAllRotors rekursiv fuer den naechsten Rotor aufgerufen
* @param i Der zu rotierende Rotor
*/
public void RotationAllRotors(int i){
if((rotors.get(i).rotate())&&(i+1<rotors.size()))
RotationAllRotors(i+1);
}
@Override
public String decrypt(String text){
char[] chars = text.toCharArray();
char[] transChars = new char[chars.length];
String result = "";
int i = 0;
//Einzelne Buchstaben durch Pinboard und durch alle Rotoren
for(Character c: chars){
transChars[i] = pinboard.translate(c);
//Buchstaben durch alle Rotoren pruegeln
for(int j = 0; j < rotors.size(); j++){
transChars[i] = rotors.get(j).translate(transChars[i], true);
}
//Buchstaben durch reverseRotor werfen
transChars[i] = reverseRotor.translate(transChars[i]);
//Buchstaben durch alle Rotoren in umgekehrter Reihenfolge kloppen
for(int k = rotors.size()-1; k >= 0; k--){
transChars[i] = rotors.get(k).translate(transChars[i], false);
}
transChars[i]=pinboard.translate(transChars[i]);
/**for (int j = 1; rotors.get(j-1).rotate() ; j++){
rotors.get(j).rotate();
}**/
rotors.get(0).rotate();
result += transChars[i];
i++;
}
for (int z = 0; z < rotors.size(); z++) rotors.get(z).reset();
return result;
}
}
| GDIProjekt/GDIProjekt | src/de/tudarmstadt/gdi1/project/cipher/enigma/EnigmaImpl.java | 1,435 | /**for (int j = 1; rotors.get(j-1).rotate() ; j++){
rotors.get(j).rotate();
}**/ | block_comment | nl | package de.tudarmstadt.gdi1.project.cipher.enigma;
import java.util.List;
import de.tudarmstadt.gdi1.project.cipher.enigma.Enigma;
/**
* Implementiert das Enigma Interface.
* @author Quoc Thong Huynh, Dennis Kuhn, Moritz Matthiesen, Erik Laurin Strelow
*
*/
public class EnigmaImpl implements Enigma {
/**
* Liste von Rotoren
*/
List<Rotor> rotors;
/**
* Das Steckbrett
*/
PinBoard pinboard;
/**
* Umkehrrotor
*/
ReverseRotor reverseRotor;
/**
* Konstruktor der Enigma
* @param rotors Liste der Rotoren
* @param pinboard Das Steckbrett
* @param reverseRotor Der Umkehrrotor
*/
public EnigmaImpl (List<Rotor> rotors, PinBoard pinboard, ReverseRotor reverseRotor){
this.rotors = rotors;
this.pinboard = pinboard;
this.reverseRotor = reverseRotor;
}
@Override
public String encrypt(String text){
char[] chars = text.toCharArray();
char[] transChars = new char[chars.length];
String result = "";
int i = 0;
//Einzelnen Buchstaben durch Pinboard und durch alle Rotoren
for(Character c: chars){
transChars[i] = pinboard.translate(c);
//Buchstaben durch alle Rotoren pr��geln
for(int j = 0; j < rotors.size(); j++){
transChars[i] = rotors.get(j).translate(transChars[i], true);
}
//Buchstaben durch reverseRotor werfen
transChars[i] = reverseRotor.translate(transChars[i]);
//Buchstaben durch alle Rotoren in umgekehrter Reihenfolge werfen
for(int k = rotors.size()-1; k >= 0; k--){
transChars[i] = rotors.get(k).translate(transChars[i], false);
}
transChars[i]=pinboard.translate(transChars[i]);
/**for (int j = 1; rotors.get(j-1).rotate() ; j++){
rotors.get(j).rotate();
}**/
RotationAllRotors(0);
result += transChars[i];
i++;
}
for (int z = 0; z < rotors.size(); z++) rotors.get(z).reset();
return result;
}
/**
* Hilfsprozedur RotationAllRotors: Rotiert stets den Rotor an der Stelle i, prueft ob rotate() true ausgibt (also eine komplette Umdrehung erfolgt ist) und ob es einen
* weiteren Rotor gibt, wenn ja wird RotationAllRotors rekursiv fuer den naechsten Rotor aufgerufen
* @param i Der zu rotierende Rotor
*/
public void RotationAllRotors(int i){
if((rotors.get(i).rotate())&&(i+1<rotors.size()))
RotationAllRotors(i+1);
}
@Override
public String decrypt(String text){
char[] chars = text.toCharArray();
char[] transChars = new char[chars.length];
String result = "";
int i = 0;
//Einzelne Buchstaben durch Pinboard und durch alle Rotoren
for(Character c: chars){
transChars[i] = pinboard.translate(c);
//Buchstaben durch alle Rotoren pruegeln
for(int j = 0; j < rotors.size(); j++){
transChars[i] = rotors.get(j).translate(transChars[i], true);
}
//Buchstaben durch reverseRotor werfen
transChars[i] = reverseRotor.translate(transChars[i]);
//Buchstaben durch alle Rotoren in umgekehrter Reihenfolge kloppen
for(int k = rotors.size()-1; k >= 0; k--){
transChars[i] = rotors.get(k).translate(transChars[i], false);
}
transChars[i]=pinboard.translate(transChars[i]);
/**for (int j<SUF>*/
rotors.get(0).rotate();
result += transChars[i];
i++;
}
for (int z = 0; z < rotors.size(); z++) rotors.get(z).reset();
return result;
}
}
|
159979_2 | /*_############################################################################
_##
_## SNMP4J-Agent 2 - Snmp4jHeartbeatMib.java
_##
_## Copyright (C) 2005-2014 Frank Fock (SNMP4J.org)
_##
_## Licensed under the Apache License, Version 2.0 (the "License");
_## you may not use this file except in compliance with the License.
_## You may obtain a copy of the License at
_##
_## http://www.apache.org/licenses/LICENSE-2.0
_##
_## Unless required by applicable law or agreed to in writing, software
_## distributed under the License is distributed on an "AS IS" BASIS,
_## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
_## See the License for the specific language governing permissions and
_## limitations under the License.
_##
_##########################################################################*/
//--AgentGen BEGIN=_BEGIN
package org.snmp4j.agent.mo.snmp4j.example;
//--AgentGen END
import org.snmp4j.smi.*;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.agent.*;
import org.snmp4j.agent.mo.*;
import org.snmp4j.agent.mo.snmp.*;
import org.snmp4j.agent.mo.snmp.smi.*;
import org.snmp4j.agent.request.*;
import org.snmp4j.log.LogFactory;
import org.snmp4j.log.LogAdapter;
import java.util.Timer;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.TimerTask;
import org.snmp4j.agent.mo.snmp4j.example.Snmp4jHeartbeatMib.
Snmp4jAgentHBCtrlEntryRow;
import org.snmp4j.agent.mo.snmp4j.example.Snmp4jHeartbeatMib.HeartbeatTask;
import org.snmp4j.PDU;
import java.util.Date;
import org.snmp4j.agent.io.MOInput;
import java.io.IOException;
import org.snmp4j.agent.io.MOOutput;
import org.snmp4j.SNMP4JSettings;
import org.snmp4j.util.CommonTimer;
//--AgentGen BEGIN=_IMPORT
//--AgentGen END
public class Snmp4jHeartbeatMib
//--AgentGen BEGIN=_EXTENDS
//--AgentGen END
implements MOGroup
//--AgentGen BEGIN=_IMPLEMENTS
, RowStatusListener,
MOTableRowListener<Snmp4jAgentHBCtrlEntryRow>
//--AgentGen END
{
private static final LogAdapter LOGGER =
LogFactory.getLogger(Snmp4jHeartbeatMib.class);
//--AgentGen BEGIN=_STATIC
//--AgentGen END
// Factory
private static MOFactory moFactory = DefaultMOFactory.getInstance();
// Constants
public static final OID oidSnmp4jAgentHBRefTime =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 1, 1, 0});
public static final OID oidSnmp4jAgentHBEvent =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 2, 0, 1});
public static final OID oidTrapVarSnmp4jAgentHBCtrlEvents =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 1, 2, 1, 6});
// Enumerations
public static final class Snmp4jAgentHBCtrlStorageTypeEnum {
/* -- eh? */
public static final int other = 1;
/* -- e.g., in RAM */
public static final int _volatile = 2;
/* -- e.g., in NVRAM */
public static final int nonVolatile = 3;
/* -- e.g., partially in ROM */
public static final int permanent = 4;
/* -- e.g., completely in ROM */
public static final int readOnly = 5;
}
public static final class Snmp4jAgentHBCtrlRowStatusEnum {
public static final int active = 1;
/* -- the following value is a state:
-- this value may be read, but not written */
public static final int notInService = 2;
/* -- the following three values are
-- actions: these values may be written,
-- but are never read */
public static final int notReady = 3;
public static final int createAndGo = 4;
public static final int createAndWait = 5;
public static final int destroy = 6;
}
// TextualConventions
private static final String TC_MODULE_SNMPV2_TC = "SNMPv2-TC";
private static final String TC_DATEANDTIME = "DateAndTime";
// Scalars
private MOScalar snmp4jAgentHBRefTime;
// Tables
public static final OID oidSnmp4jAgentHBCtrlEntry =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 1, 2, 1});
// Column sub-identifer defintions for snmp4jAgentHBCtrlEntry:
public static final int colSnmp4jAgentHBCtrlStartTime = 2;
public static final int colSnmp4jAgentHBCtrlDelay = 3;
public static final int colSnmp4jAgentHBCtrlPeriod = 4;
public static final int colSnmp4jAgentHBCtrlMaxEvents = 5;
public static final int colSnmp4jAgentHBCtrlEvents = 6;
public static final int colSnmp4jAgentHBCtrlLastChange = 7;
public static final int colSnmp4jAgentHBCtrlStorageType = 8;
public static final int colSnmp4jAgentHBCtrlRowStatus = 9;
// Column index defintions for snmp4jAgentHBCtrlEntry:
public static final int idxSnmp4jAgentHBCtrlStartTime = 0;
public static final int idxSnmp4jAgentHBCtrlDelay = 1;
public static final int idxSnmp4jAgentHBCtrlPeriod = 2;
public static final int idxSnmp4jAgentHBCtrlMaxEvents = 3;
public static final int idxSnmp4jAgentHBCtrlEvents = 4;
public static final int idxSnmp4jAgentHBCtrlLastChange = 5;
public static final int idxSnmp4jAgentHBCtrlStorageType = 6;
public static final int idxSnmp4jAgentHBCtrlRowStatus = 7;
private static final MOTableSubIndex[] snmp4jAgentHBCtrlEntryIndexes =
new MOTableSubIndex[] {
moFactory.createSubIndex(null, SMIConstants.SYNTAX_OCTET_STRING, 1, 32)
};
private static final MOTableIndex snmp4jAgentHBCtrlEntryIndex =
moFactory.createIndex(snmp4jAgentHBCtrlEntryIndexes,
true);
private MOTable<Snmp4jAgentHBCtrlEntryRow,MOColumn,MOMutableTableModel<Snmp4jAgentHBCtrlEntryRow>>
snmp4jAgentHBCtrlEntry;
private MOMutableTableModel<Snmp4jAgentHBCtrlEntryRow> snmp4jAgentHBCtrlEntryModel;
//--AgentGen BEGIN=_MEMBERS
private static final int[] PROTECTED_COLS =
{
idxSnmp4jAgentHBCtrlStartTime,
idxSnmp4jAgentHBCtrlDelay,
idxSnmp4jAgentHBCtrlPeriod
};
private CommonTimer heartbeatTimer = SNMP4JSettings.getTimerFactory().createTimer();
private int heartbeatOffset = 0;
private NotificationOriginator notificationOriginator;
private OctetString context;
private SysUpTime sysUpTime;
//--AgentGen END
private Snmp4jHeartbeatMib() {
snmp4jAgentHBRefTime =
new Snmp4jAgentHBRefTime(oidSnmp4jAgentHBRefTime,
MOAccessImpl.ACCESS_READ_WRITE);
snmp4jAgentHBRefTime.addMOValueValidationListener(new
Snmp4jAgentHBRefTimeValidator());
createSnmp4jAgentHBCtrlEntry();
//--AgentGen BEGIN=_DEFAULTCONSTRUCTOR
((RowStatus) snmp4jAgentHBCtrlEntry.getColumn(idxSnmp4jAgentHBCtrlRowStatus)).
addRowStatusListener(this);
snmp4jAgentHBCtrlEntry.addMOTableRowListener(this);
//--AgentGen END
}
//--AgentGen BEGIN=_CONSTRUCTORS
public Snmp4jHeartbeatMib(NotificationOriginator notificationOriginator,
OctetString context, SysUpTime upTime) {
this();
this.notificationOriginator = notificationOriginator;
this.context = context;
this.sysUpTime = upTime;
// make sure that the heartbeat timer related objects are not modified
// while row is active:
for (int i=0; i<PROTECTED_COLS.length; i++) {
((MOMutableColumn)
snmp4jAgentHBCtrlEntry.getColumn(i)).setMutableInService(false);
}
}
//--AgentGen END
public MOTable getSnmp4jAgentHBCtrlEntry() {
return snmp4jAgentHBCtrlEntry;
}
private void createSnmp4jAgentHBCtrlEntry() {
MOColumn[] snmp4jAgentHBCtrlEntryColumns = new MOColumn[8];
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlStartTime] =
new DateAndTime(colSnmp4jAgentHBCtrlStartTime,
MOAccessImpl.ACCESS_READ_CREATE,
null);
ValueConstraint snmp4jAgentHBCtrlStartTimeVC = new ConstraintsImpl();
((ConstraintsImpl) snmp4jAgentHBCtrlStartTimeVC).add(new Constraint(8, 8));
((ConstraintsImpl) snmp4jAgentHBCtrlStartTimeVC).add(new Constraint(11, 11));
((MOMutableColumn) snmp4jAgentHBCtrlEntryColumns[
idxSnmp4jAgentHBCtrlStartTime]).
addMOValueValidationListener(new ValueConstraintValidator(
snmp4jAgentHBCtrlStartTimeVC));
// Although there is only a null default value, this column does not need
// to be set:
((MOMutableColumn) snmp4jAgentHBCtrlEntryColumns[
idxSnmp4jAgentHBCtrlStartTime]).setMandatory(false);
((MOMutableColumn) snmp4jAgentHBCtrlEntryColumns[
idxSnmp4jAgentHBCtrlStartTime]).
addMOValueValidationListener(new Snmp4jAgentHBCtrlStartTimeValidator());
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlDelay] =
new MOMutableColumn(colSnmp4jAgentHBCtrlDelay,
SMIConstants.SYNTAX_GAUGE32,
MOAccessImpl.ACCESS_READ_CREATE,
new UnsignedInteger32(1000));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlPeriod] =
new MOMutableColumn(colSnmp4jAgentHBCtrlPeriod,
SMIConstants.SYNTAX_GAUGE32,
MOAccessImpl.ACCESS_READ_CREATE,
new UnsignedInteger32(60000));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlMaxEvents] =
new MOMutableColumn(colSnmp4jAgentHBCtrlMaxEvents,
SMIConstants.SYNTAX_GAUGE32,
MOAccessImpl.ACCESS_READ_CREATE,
new UnsignedInteger32(0));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlEvents] =
moFactory.createColumn(colSnmp4jAgentHBCtrlEvents,
SMIConstants.SYNTAX_COUNTER64,
MOAccessImpl.ACCESS_READ_ONLY);
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlLastChange] =
moFactory.createColumn(colSnmp4jAgentHBCtrlLastChange,
SMIConstants.SYNTAX_TIMETICKS,
MOAccessImpl.ACCESS_READ_ONLY);
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlEvents] =
moFactory.createColumn(colSnmp4jAgentHBCtrlEvents,
SMIConstants.SYNTAX_COUNTER64,
MOAccessImpl.ACCESS_READ_ONLY);
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlStorageType] =
new StorageType(colSnmp4jAgentHBCtrlStorageType,
MOAccessImpl.ACCESS_READ_CREATE,
new Integer32(3));
ValueConstraint snmp4jAgentHBCtrlStorageTypeVC = new EnumerationConstraint(
new int[] {Snmp4jAgentHBCtrlStorageTypeEnum.other,
Snmp4jAgentHBCtrlStorageTypeEnum._volatile,
Snmp4jAgentHBCtrlStorageTypeEnum.nonVolatile,
Snmp4jAgentHBCtrlStorageTypeEnum.permanent,
Snmp4jAgentHBCtrlStorageTypeEnum.readOnly});
((MOMutableColumn)snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlStorageType]).
addMOValueValidationListener(new ValueConstraintValidator(snmp4jAgentHBCtrlStorageTypeVC));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlRowStatus] =
new RowStatus(colSnmp4jAgentHBCtrlRowStatus);
ValueConstraint snmp4jAgentHBCtrlRowStatusVC = new EnumerationConstraint(
new int[] {Snmp4jAgentHBCtrlRowStatusEnum.active,
Snmp4jAgentHBCtrlRowStatusEnum.notInService,
Snmp4jAgentHBCtrlRowStatusEnum.notReady,
Snmp4jAgentHBCtrlRowStatusEnum.createAndGo,
Snmp4jAgentHBCtrlRowStatusEnum.createAndWait,
Snmp4jAgentHBCtrlRowStatusEnum.destroy});
((MOMutableColumn)snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlRowStatus]).
addMOValueValidationListener(new ValueConstraintValidator(snmp4jAgentHBCtrlRowStatusVC));
snmp4jAgentHBCtrlEntryModel = new DefaultMOMutableTableModel<Snmp4jAgentHBCtrlEntryRow>();
snmp4jAgentHBCtrlEntryModel.setRowFactory(new Snmp4jAgentHBCtrlEntryRowFactory());
snmp4jAgentHBCtrlEntry =
moFactory.createTable(oidSnmp4jAgentHBCtrlEntry,
snmp4jAgentHBCtrlEntryIndex,
snmp4jAgentHBCtrlEntryColumns,
snmp4jAgentHBCtrlEntryModel);
}
public void registerMOs(MOServer server, OctetString context) throws
DuplicateRegistrationException {
// Scalar Objects
server.register(this.snmp4jAgentHBRefTime, context);
server.register(this.snmp4jAgentHBCtrlEntry, context);
//--AgentGen BEGIN=_registerMOs
//--AgentGen END
}
public void unregisterMOs(MOServer server, OctetString context) {
// Scalar Objects
server.unregister(this.snmp4jAgentHBRefTime, context);
server.unregister(this.snmp4jAgentHBCtrlEntry, context);
//--AgentGen BEGIN=_unregisterMOs
//--AgentGen END
}
// Notifications
public void snmp4jAgentHBEvent(NotificationOriginator notificationOriginator,
OctetString context, VariableBinding[] vbs) {
if (vbs.length < 1) {
throw new IllegalArgumentException("Too few notification objects: " +
vbs.length + "<1");
}
if (!(vbs[0].getOid().startsWith(oidTrapVarSnmp4jAgentHBCtrlEvents))) {
throw new IllegalArgumentException("Variable 0 has wrong OID: " +
vbs[0].getOid() +
" does not start with " +
oidTrapVarSnmp4jAgentHBCtrlEvents);
}
if (!snmp4jAgentHBCtrlEntryIndex.isValidIndex(snmp4jAgentHBCtrlEntry.
getIndexPart(vbs[0].getOid()))) {
throw new IllegalArgumentException(
"Illegal index for variable 0 specified: " +
snmp4jAgentHBCtrlEntry.getIndexPart(vbs[0].getOid()));
}
notificationOriginator.notify(context, oidSnmp4jAgentHBEvent, vbs);
}
// Scalars
public class Snmp4jAgentHBRefTime extends DateAndTimeScalar<OctetString> {
Snmp4jAgentHBRefTime(OID oid, MOAccess access) {
super(oid, access, new OctetString());
//--AgentGen BEGIN=snmp4jAgentHBRefTime
//--AgentGen END
}
public int isValueOK(SubRequest request) {
Variable newValue =
request.getVariableBinding().getVariable();
int valueOK = super.isValueOK(request);
if (valueOK != SnmpConstants.SNMP_ERROR_SUCCESS) {
return valueOK;
}
OctetString os = (OctetString) newValue;
if (!(((os.length() >= 8) && (os.length() <= 8)) ||
((os.length() >= 11) && (os.length() <= 11)))) {
valueOK = SnmpConstants.SNMP_ERROR_WRONG_LENGTH;
}
//--AgentGen BEGIN=snmp4jAgentHBRefTime::isValueOK
//--AgentGen END
return valueOK;
}
public OctetString getValue() {
//--AgentGen BEGIN=snmp4jAgentHBRefTime::getValue
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.MILLISECOND, heartbeatOffset);
super.setValue(DateAndTime.makeDateAndTime(gc));
//--AgentGen END
return super.getValue();
}
public int setValue(OctetString newValue) {
//--AgentGen BEGIN=snmp4jAgentHBRefTime::setValue
GregorianCalendar gc = DateAndTime.makeCalendar((OctetString) newValue);
GregorianCalendar curGC = new GregorianCalendar();
heartbeatOffset = (int) (gc.getTimeInMillis() - curGC.getTimeInMillis());
//--AgentGen END
return super.setValue(newValue);
}
//--AgentGen BEGIN=snmp4jAgentHBRefTime::_METHODS
public void load(MOInput input) throws IOException {
heartbeatOffset = ((Integer32)input.readVariable()).getValue();
}
public void save(MOOutput output) throws IOException {
output.writeVariable(new Integer32(heartbeatOffset));
}
//--AgentGen END
}
// Value Validators
/**
* The <code>Snmp4jAgentHBRefTimeValidator</code> implements the value
* validation for <code>Snmp4jAgentHBRefTime</code>.
*/
static class Snmp4jAgentHBRefTimeValidator implements
MOValueValidationListener {
public void validate(MOValueValidationEvent validationEvent) {
Variable newValue = validationEvent.getNewValue();
OctetString os = (OctetString) newValue;
if (!(((os.length() >= 8) && (os.length() <= 8)) ||
((os.length() >= 11) && (os.length() <= 11)))) {
validationEvent.setValidationStatus(SnmpConstants.
SNMP_ERROR_WRONG_LENGTH);
return;
}
//--AgentGen BEGIN=snmp4jAgentHBRefTime::validate
//--AgentGen END
}
}
/**
* The <code>Snmp4jAgentHBCtrlStartTimeValidator</code> implements the value
* validation for <code>Snmp4jAgentHBCtrlStartTime</code>.
*/
static class Snmp4jAgentHBCtrlStartTimeValidator implements
MOValueValidationListener {
public void validate(MOValueValidationEvent validationEvent) {
Variable newValue = validationEvent.getNewValue();
OctetString os = (OctetString) newValue;
if (!(((os.length() >= 8) && (os.length() <= 8)) ||
((os.length() >= 11) && (os.length() <= 11)))) {
validationEvent.setValidationStatus(SnmpConstants.
SNMP_ERROR_WRONG_LENGTH);
return;
}
//--AgentGen BEGIN=snmp4jAgentHBCtrlStartTime::validate
//--AgentGen END
}
}
// Rows and Factories
public class Snmp4jAgentHBCtrlEntryRow extends DefaultMOMutableRow2PC {
public Snmp4jAgentHBCtrlEntryRow(OID index, Variable[] values) {
super(index, values);
}
public OctetString getSnmp4jAgentHBCtrlStartTime() {
return (OctetString) getValue(idxSnmp4jAgentHBCtrlStartTime);
}
public void setSnmp4jAgentHBCtrlStartTime(OctetString newValue) {
setValue(idxSnmp4jAgentHBCtrlStartTime, newValue);
}
public UnsignedInteger32 getSnmp4jAgentHBCtrlDelay() {
return (UnsignedInteger32) getValue(idxSnmp4jAgentHBCtrlDelay);
}
public void setSnmp4jAgentHBCtrlDelay(UnsignedInteger32 newValue) {
setValue(idxSnmp4jAgentHBCtrlDelay, newValue);
}
public UnsignedInteger32 getSnmp4jAgentHBCtrlPeriod() {
return (UnsignedInteger32) getValue(idxSnmp4jAgentHBCtrlPeriod);
}
public void setSnmp4jAgentHBCtrlPeriod(UnsignedInteger32 newValue) {
setValue(idxSnmp4jAgentHBCtrlPeriod, newValue);
}
public UnsignedInteger32 getSnmp4jAgentHBCtrlMaxEvents() {
return (UnsignedInteger32) getValue(idxSnmp4jAgentHBCtrlMaxEvents);
}
public void setSnmp4jAgentHBCtrlMaxEvents(UnsignedInteger32 newValue) {
setValue(idxSnmp4jAgentHBCtrlMaxEvents, newValue);
}
public Counter64 getSnmp4jAgentHBCtrlEvents() {
return (Counter64) getValue(idxSnmp4jAgentHBCtrlEvents);
}
public void setSnmp4jAgentHBCtrlEvents(Counter64 newValue) {
setValue(idxSnmp4jAgentHBCtrlEvents, newValue);
}
public TimeTicks getSnmp4jAgentHBCtrlLastChange() {
return (TimeTicks) getValue(idxSnmp4jAgentHBCtrlLastChange);
}
public void setSnmp4jAgentHBCtrlLastChange(TimeTicks newValue) {
setValue(idxSnmp4jAgentHBCtrlLastChange, newValue);
}
public Integer32 getSnmp4jAgentHBCtrlStorageType() {
return (Integer32) getValue(idxSnmp4jAgentHBCtrlStorageType);
}
public void setSnmp4jAgentHBCtrlStorageType(Integer32 newValue) {
setValue(idxSnmp4jAgentHBCtrlStorageType, newValue);
}
public Integer32 getSnmp4jAgentHBCtrlRowStatus() {
return (Integer32) getValue(idxSnmp4jAgentHBCtrlRowStatus);
}
public void setSnmp4jAgentHBCtrlRowStatus(Integer32 newValue) {
setValue(idxSnmp4jAgentHBCtrlRowStatus, newValue);
}
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::Row
//--AgentGen END
}
class Snmp4jAgentHBCtrlEntryRowFactory
implements MOTableRowFactory<Snmp4jAgentHBCtrlEntryRow> {
public synchronized Snmp4jAgentHBCtrlEntryRow createRow(OID index, Variable[] values) throws
UnsupportedOperationException {
Snmp4jAgentHBCtrlEntryRow row = new Snmp4jAgentHBCtrlEntryRow(index,
values);
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::createRow
row.setSnmp4jAgentHBCtrlLastChange(sysUpTime.get());
row.setSnmp4jAgentHBCtrlEvents(new Counter64(0));
//--AgentGen END
return row;
}
public synchronized void freeRow(Snmp4jAgentHBCtrlEntryRow row) {
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::freeRow
//--AgentGen END
}
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::RowFactory
//--AgentGen END
}
//--AgentGen BEGIN=_METHODS
public void rowStatusChanged(RowStatusEvent event) {
if (event.isDeniable()) {
if (event.isRowActivated()) {
// check column interdependent consistency
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
if ((row.getSnmp4jAgentHBCtrlDelay().getValue() == 0) &&
((row.getSnmp4jAgentHBCtrlStartTime() == null) ||
(DateAndTime.makeCalendar(
row.getSnmp4jAgentHBCtrlStartTime()).getTimeInMillis()
<= System.currentTimeMillis()))) {
event.setDenyReason(PDU.inconsistentValue);
}
}
}
else if (event.isRowActivated()) {
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
HeartbeatTask task = new HeartbeatTask(row);
if (row.getSnmp4jAgentHBCtrlDelay().getValue() == 0) {
long startTime = DateAndTime.makeCalendar(
row.getSnmp4jAgentHBCtrlStartTime()).getTimeInMillis() -
heartbeatOffset;
heartbeatTimer.schedule(task,
new Date(startTime),
row.getSnmp4jAgentHBCtrlPeriod().getValue());
}
else {
heartbeatTimer.schedule(task,
row.getSnmp4jAgentHBCtrlDelay().getValue(),
row.getSnmp4jAgentHBCtrlPeriod().getValue());
}
row.setUserObject(task);
}
else if (event.isRowDeactivated()) {
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
HeartbeatTask task = (HeartbeatTask) row.getUserObject();
if (task != null) {
task.cancel();
}
}
}
public void rowChanged(MOTableRowEvent event) {
if (event.getRow() != null) {
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
if (row.getSnmp4jAgentHBCtrlLastChange() != null) {
row.getSnmp4jAgentHBCtrlLastChange().setValue(sysUpTime.get().getValue());
}
}
}
//--AgentGen END
//--AgentGen BEGIN=_CLASSES
class HeartbeatTask extends TimerTask {
private Snmp4jAgentHBCtrlEntryRow configRow;
public HeartbeatTask(Snmp4jAgentHBCtrlEntryRow configRow) {
this.configRow = configRow;
}
public void run() {
if (configRow.getSnmp4jAgentHBCtrlRowStatus().getValue() ==
RowStatus.active) {
long maxEvents = configRow.getSnmp4jAgentHBCtrlMaxEvents().getValue();
if ((maxEvents > 0) &&
(configRow.getSnmp4jAgentHBCtrlEvents().getValue() < maxEvents)) {
configRow.getSnmp4jAgentHBCtrlEvents().increment();
OID instanceOID =
((DefaultMOTable) snmp4jAgentHBCtrlEntry).
getCellOID(configRow.getIndex(),
idxSnmp4jAgentHBCtrlEvents);
VariableBinding eventVB = new VariableBinding(instanceOID,
configRow.getSnmp4jAgentHBCtrlEvents());
snmp4jAgentHBEvent(notificationOriginator, context,
new VariableBinding[] {eventVB});
}
else {
cancel();
configRow.getSnmp4jAgentHBCtrlRowStatus().setValue(RowStatus.notInService);
}
}
else {
cancel();
}
}
}
//--AgentGen END
//--AgentGen BEGIN=_END
//--AgentGen END
}
| GEBIT/snmp4j | snmp4j-agent-2.4.0/src/main/java/org/snmp4j/agent/mo/snmp4j/example/Snmp4jHeartbeatMib.java | 7,980 | /* -- e.g., in NVRAM */ | block_comment | nl | /*_############################################################################
_##
_## SNMP4J-Agent 2 - Snmp4jHeartbeatMib.java
_##
_## Copyright (C) 2005-2014 Frank Fock (SNMP4J.org)
_##
_## Licensed under the Apache License, Version 2.0 (the "License");
_## you may not use this file except in compliance with the License.
_## You may obtain a copy of the License at
_##
_## http://www.apache.org/licenses/LICENSE-2.0
_##
_## Unless required by applicable law or agreed to in writing, software
_## distributed under the License is distributed on an "AS IS" BASIS,
_## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
_## See the License for the specific language governing permissions and
_## limitations under the License.
_##
_##########################################################################*/
//--AgentGen BEGIN=_BEGIN
package org.snmp4j.agent.mo.snmp4j.example;
//--AgentGen END
import org.snmp4j.smi.*;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.agent.*;
import org.snmp4j.agent.mo.*;
import org.snmp4j.agent.mo.snmp.*;
import org.snmp4j.agent.mo.snmp.smi.*;
import org.snmp4j.agent.request.*;
import org.snmp4j.log.LogFactory;
import org.snmp4j.log.LogAdapter;
import java.util.Timer;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.TimerTask;
import org.snmp4j.agent.mo.snmp4j.example.Snmp4jHeartbeatMib.
Snmp4jAgentHBCtrlEntryRow;
import org.snmp4j.agent.mo.snmp4j.example.Snmp4jHeartbeatMib.HeartbeatTask;
import org.snmp4j.PDU;
import java.util.Date;
import org.snmp4j.agent.io.MOInput;
import java.io.IOException;
import org.snmp4j.agent.io.MOOutput;
import org.snmp4j.SNMP4JSettings;
import org.snmp4j.util.CommonTimer;
//--AgentGen BEGIN=_IMPORT
//--AgentGen END
public class Snmp4jHeartbeatMib
//--AgentGen BEGIN=_EXTENDS
//--AgentGen END
implements MOGroup
//--AgentGen BEGIN=_IMPLEMENTS
, RowStatusListener,
MOTableRowListener<Snmp4jAgentHBCtrlEntryRow>
//--AgentGen END
{
private static final LogAdapter LOGGER =
LogFactory.getLogger(Snmp4jHeartbeatMib.class);
//--AgentGen BEGIN=_STATIC
//--AgentGen END
// Factory
private static MOFactory moFactory = DefaultMOFactory.getInstance();
// Constants
public static final OID oidSnmp4jAgentHBRefTime =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 1, 1, 0});
public static final OID oidSnmp4jAgentHBEvent =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 2, 0, 1});
public static final OID oidTrapVarSnmp4jAgentHBCtrlEvents =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 1, 2, 1, 6});
// Enumerations
public static final class Snmp4jAgentHBCtrlStorageTypeEnum {
/* -- eh? */
public static final int other = 1;
/* -- e.g., in RAM */
public static final int _volatile = 2;
/* -- e.g., in<SUF>*/
public static final int nonVolatile = 3;
/* -- e.g., partially in ROM */
public static final int permanent = 4;
/* -- e.g., completely in ROM */
public static final int readOnly = 5;
}
public static final class Snmp4jAgentHBCtrlRowStatusEnum {
public static final int active = 1;
/* -- the following value is a state:
-- this value may be read, but not written */
public static final int notInService = 2;
/* -- the following three values are
-- actions: these values may be written,
-- but are never read */
public static final int notReady = 3;
public static final int createAndGo = 4;
public static final int createAndWait = 5;
public static final int destroy = 6;
}
// TextualConventions
private static final String TC_MODULE_SNMPV2_TC = "SNMPv2-TC";
private static final String TC_DATEANDTIME = "DateAndTime";
// Scalars
private MOScalar snmp4jAgentHBRefTime;
// Tables
public static final OID oidSnmp4jAgentHBCtrlEntry =
new OID(new int[] {1, 3, 6, 1, 4, 1, 4976, 10, 1, 1, 42, 2, 1, 2, 1});
// Column sub-identifer defintions for snmp4jAgentHBCtrlEntry:
public static final int colSnmp4jAgentHBCtrlStartTime = 2;
public static final int colSnmp4jAgentHBCtrlDelay = 3;
public static final int colSnmp4jAgentHBCtrlPeriod = 4;
public static final int colSnmp4jAgentHBCtrlMaxEvents = 5;
public static final int colSnmp4jAgentHBCtrlEvents = 6;
public static final int colSnmp4jAgentHBCtrlLastChange = 7;
public static final int colSnmp4jAgentHBCtrlStorageType = 8;
public static final int colSnmp4jAgentHBCtrlRowStatus = 9;
// Column index defintions for snmp4jAgentHBCtrlEntry:
public static final int idxSnmp4jAgentHBCtrlStartTime = 0;
public static final int idxSnmp4jAgentHBCtrlDelay = 1;
public static final int idxSnmp4jAgentHBCtrlPeriod = 2;
public static final int idxSnmp4jAgentHBCtrlMaxEvents = 3;
public static final int idxSnmp4jAgentHBCtrlEvents = 4;
public static final int idxSnmp4jAgentHBCtrlLastChange = 5;
public static final int idxSnmp4jAgentHBCtrlStorageType = 6;
public static final int idxSnmp4jAgentHBCtrlRowStatus = 7;
private static final MOTableSubIndex[] snmp4jAgentHBCtrlEntryIndexes =
new MOTableSubIndex[] {
moFactory.createSubIndex(null, SMIConstants.SYNTAX_OCTET_STRING, 1, 32)
};
private static final MOTableIndex snmp4jAgentHBCtrlEntryIndex =
moFactory.createIndex(snmp4jAgentHBCtrlEntryIndexes,
true);
private MOTable<Snmp4jAgentHBCtrlEntryRow,MOColumn,MOMutableTableModel<Snmp4jAgentHBCtrlEntryRow>>
snmp4jAgentHBCtrlEntry;
private MOMutableTableModel<Snmp4jAgentHBCtrlEntryRow> snmp4jAgentHBCtrlEntryModel;
//--AgentGen BEGIN=_MEMBERS
private static final int[] PROTECTED_COLS =
{
idxSnmp4jAgentHBCtrlStartTime,
idxSnmp4jAgentHBCtrlDelay,
idxSnmp4jAgentHBCtrlPeriod
};
private CommonTimer heartbeatTimer = SNMP4JSettings.getTimerFactory().createTimer();
private int heartbeatOffset = 0;
private NotificationOriginator notificationOriginator;
private OctetString context;
private SysUpTime sysUpTime;
//--AgentGen END
private Snmp4jHeartbeatMib() {
snmp4jAgentHBRefTime =
new Snmp4jAgentHBRefTime(oidSnmp4jAgentHBRefTime,
MOAccessImpl.ACCESS_READ_WRITE);
snmp4jAgentHBRefTime.addMOValueValidationListener(new
Snmp4jAgentHBRefTimeValidator());
createSnmp4jAgentHBCtrlEntry();
//--AgentGen BEGIN=_DEFAULTCONSTRUCTOR
((RowStatus) snmp4jAgentHBCtrlEntry.getColumn(idxSnmp4jAgentHBCtrlRowStatus)).
addRowStatusListener(this);
snmp4jAgentHBCtrlEntry.addMOTableRowListener(this);
//--AgentGen END
}
//--AgentGen BEGIN=_CONSTRUCTORS
public Snmp4jHeartbeatMib(NotificationOriginator notificationOriginator,
OctetString context, SysUpTime upTime) {
this();
this.notificationOriginator = notificationOriginator;
this.context = context;
this.sysUpTime = upTime;
// make sure that the heartbeat timer related objects are not modified
// while row is active:
for (int i=0; i<PROTECTED_COLS.length; i++) {
((MOMutableColumn)
snmp4jAgentHBCtrlEntry.getColumn(i)).setMutableInService(false);
}
}
//--AgentGen END
public MOTable getSnmp4jAgentHBCtrlEntry() {
return snmp4jAgentHBCtrlEntry;
}
private void createSnmp4jAgentHBCtrlEntry() {
MOColumn[] snmp4jAgentHBCtrlEntryColumns = new MOColumn[8];
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlStartTime] =
new DateAndTime(colSnmp4jAgentHBCtrlStartTime,
MOAccessImpl.ACCESS_READ_CREATE,
null);
ValueConstraint snmp4jAgentHBCtrlStartTimeVC = new ConstraintsImpl();
((ConstraintsImpl) snmp4jAgentHBCtrlStartTimeVC).add(new Constraint(8, 8));
((ConstraintsImpl) snmp4jAgentHBCtrlStartTimeVC).add(new Constraint(11, 11));
((MOMutableColumn) snmp4jAgentHBCtrlEntryColumns[
idxSnmp4jAgentHBCtrlStartTime]).
addMOValueValidationListener(new ValueConstraintValidator(
snmp4jAgentHBCtrlStartTimeVC));
// Although there is only a null default value, this column does not need
// to be set:
((MOMutableColumn) snmp4jAgentHBCtrlEntryColumns[
idxSnmp4jAgentHBCtrlStartTime]).setMandatory(false);
((MOMutableColumn) snmp4jAgentHBCtrlEntryColumns[
idxSnmp4jAgentHBCtrlStartTime]).
addMOValueValidationListener(new Snmp4jAgentHBCtrlStartTimeValidator());
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlDelay] =
new MOMutableColumn(colSnmp4jAgentHBCtrlDelay,
SMIConstants.SYNTAX_GAUGE32,
MOAccessImpl.ACCESS_READ_CREATE,
new UnsignedInteger32(1000));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlPeriod] =
new MOMutableColumn(colSnmp4jAgentHBCtrlPeriod,
SMIConstants.SYNTAX_GAUGE32,
MOAccessImpl.ACCESS_READ_CREATE,
new UnsignedInteger32(60000));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlMaxEvents] =
new MOMutableColumn(colSnmp4jAgentHBCtrlMaxEvents,
SMIConstants.SYNTAX_GAUGE32,
MOAccessImpl.ACCESS_READ_CREATE,
new UnsignedInteger32(0));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlEvents] =
moFactory.createColumn(colSnmp4jAgentHBCtrlEvents,
SMIConstants.SYNTAX_COUNTER64,
MOAccessImpl.ACCESS_READ_ONLY);
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlLastChange] =
moFactory.createColumn(colSnmp4jAgentHBCtrlLastChange,
SMIConstants.SYNTAX_TIMETICKS,
MOAccessImpl.ACCESS_READ_ONLY);
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlEvents] =
moFactory.createColumn(colSnmp4jAgentHBCtrlEvents,
SMIConstants.SYNTAX_COUNTER64,
MOAccessImpl.ACCESS_READ_ONLY);
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlStorageType] =
new StorageType(colSnmp4jAgentHBCtrlStorageType,
MOAccessImpl.ACCESS_READ_CREATE,
new Integer32(3));
ValueConstraint snmp4jAgentHBCtrlStorageTypeVC = new EnumerationConstraint(
new int[] {Snmp4jAgentHBCtrlStorageTypeEnum.other,
Snmp4jAgentHBCtrlStorageTypeEnum._volatile,
Snmp4jAgentHBCtrlStorageTypeEnum.nonVolatile,
Snmp4jAgentHBCtrlStorageTypeEnum.permanent,
Snmp4jAgentHBCtrlStorageTypeEnum.readOnly});
((MOMutableColumn)snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlStorageType]).
addMOValueValidationListener(new ValueConstraintValidator(snmp4jAgentHBCtrlStorageTypeVC));
snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlRowStatus] =
new RowStatus(colSnmp4jAgentHBCtrlRowStatus);
ValueConstraint snmp4jAgentHBCtrlRowStatusVC = new EnumerationConstraint(
new int[] {Snmp4jAgentHBCtrlRowStatusEnum.active,
Snmp4jAgentHBCtrlRowStatusEnum.notInService,
Snmp4jAgentHBCtrlRowStatusEnum.notReady,
Snmp4jAgentHBCtrlRowStatusEnum.createAndGo,
Snmp4jAgentHBCtrlRowStatusEnum.createAndWait,
Snmp4jAgentHBCtrlRowStatusEnum.destroy});
((MOMutableColumn)snmp4jAgentHBCtrlEntryColumns[idxSnmp4jAgentHBCtrlRowStatus]).
addMOValueValidationListener(new ValueConstraintValidator(snmp4jAgentHBCtrlRowStatusVC));
snmp4jAgentHBCtrlEntryModel = new DefaultMOMutableTableModel<Snmp4jAgentHBCtrlEntryRow>();
snmp4jAgentHBCtrlEntryModel.setRowFactory(new Snmp4jAgentHBCtrlEntryRowFactory());
snmp4jAgentHBCtrlEntry =
moFactory.createTable(oidSnmp4jAgentHBCtrlEntry,
snmp4jAgentHBCtrlEntryIndex,
snmp4jAgentHBCtrlEntryColumns,
snmp4jAgentHBCtrlEntryModel);
}
public void registerMOs(MOServer server, OctetString context) throws
DuplicateRegistrationException {
// Scalar Objects
server.register(this.snmp4jAgentHBRefTime, context);
server.register(this.snmp4jAgentHBCtrlEntry, context);
//--AgentGen BEGIN=_registerMOs
//--AgentGen END
}
public void unregisterMOs(MOServer server, OctetString context) {
// Scalar Objects
server.unregister(this.snmp4jAgentHBRefTime, context);
server.unregister(this.snmp4jAgentHBCtrlEntry, context);
//--AgentGen BEGIN=_unregisterMOs
//--AgentGen END
}
// Notifications
public void snmp4jAgentHBEvent(NotificationOriginator notificationOriginator,
OctetString context, VariableBinding[] vbs) {
if (vbs.length < 1) {
throw new IllegalArgumentException("Too few notification objects: " +
vbs.length + "<1");
}
if (!(vbs[0].getOid().startsWith(oidTrapVarSnmp4jAgentHBCtrlEvents))) {
throw new IllegalArgumentException("Variable 0 has wrong OID: " +
vbs[0].getOid() +
" does not start with " +
oidTrapVarSnmp4jAgentHBCtrlEvents);
}
if (!snmp4jAgentHBCtrlEntryIndex.isValidIndex(snmp4jAgentHBCtrlEntry.
getIndexPart(vbs[0].getOid()))) {
throw new IllegalArgumentException(
"Illegal index for variable 0 specified: " +
snmp4jAgentHBCtrlEntry.getIndexPart(vbs[0].getOid()));
}
notificationOriginator.notify(context, oidSnmp4jAgentHBEvent, vbs);
}
// Scalars
public class Snmp4jAgentHBRefTime extends DateAndTimeScalar<OctetString> {
Snmp4jAgentHBRefTime(OID oid, MOAccess access) {
super(oid, access, new OctetString());
//--AgentGen BEGIN=snmp4jAgentHBRefTime
//--AgentGen END
}
public int isValueOK(SubRequest request) {
Variable newValue =
request.getVariableBinding().getVariable();
int valueOK = super.isValueOK(request);
if (valueOK != SnmpConstants.SNMP_ERROR_SUCCESS) {
return valueOK;
}
OctetString os = (OctetString) newValue;
if (!(((os.length() >= 8) && (os.length() <= 8)) ||
((os.length() >= 11) && (os.length() <= 11)))) {
valueOK = SnmpConstants.SNMP_ERROR_WRONG_LENGTH;
}
//--AgentGen BEGIN=snmp4jAgentHBRefTime::isValueOK
//--AgentGen END
return valueOK;
}
public OctetString getValue() {
//--AgentGen BEGIN=snmp4jAgentHBRefTime::getValue
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.MILLISECOND, heartbeatOffset);
super.setValue(DateAndTime.makeDateAndTime(gc));
//--AgentGen END
return super.getValue();
}
public int setValue(OctetString newValue) {
//--AgentGen BEGIN=snmp4jAgentHBRefTime::setValue
GregorianCalendar gc = DateAndTime.makeCalendar((OctetString) newValue);
GregorianCalendar curGC = new GregorianCalendar();
heartbeatOffset = (int) (gc.getTimeInMillis() - curGC.getTimeInMillis());
//--AgentGen END
return super.setValue(newValue);
}
//--AgentGen BEGIN=snmp4jAgentHBRefTime::_METHODS
public void load(MOInput input) throws IOException {
heartbeatOffset = ((Integer32)input.readVariable()).getValue();
}
public void save(MOOutput output) throws IOException {
output.writeVariable(new Integer32(heartbeatOffset));
}
//--AgentGen END
}
// Value Validators
/**
* The <code>Snmp4jAgentHBRefTimeValidator</code> implements the value
* validation for <code>Snmp4jAgentHBRefTime</code>.
*/
static class Snmp4jAgentHBRefTimeValidator implements
MOValueValidationListener {
public void validate(MOValueValidationEvent validationEvent) {
Variable newValue = validationEvent.getNewValue();
OctetString os = (OctetString) newValue;
if (!(((os.length() >= 8) && (os.length() <= 8)) ||
((os.length() >= 11) && (os.length() <= 11)))) {
validationEvent.setValidationStatus(SnmpConstants.
SNMP_ERROR_WRONG_LENGTH);
return;
}
//--AgentGen BEGIN=snmp4jAgentHBRefTime::validate
//--AgentGen END
}
}
/**
* The <code>Snmp4jAgentHBCtrlStartTimeValidator</code> implements the value
* validation for <code>Snmp4jAgentHBCtrlStartTime</code>.
*/
static class Snmp4jAgentHBCtrlStartTimeValidator implements
MOValueValidationListener {
public void validate(MOValueValidationEvent validationEvent) {
Variable newValue = validationEvent.getNewValue();
OctetString os = (OctetString) newValue;
if (!(((os.length() >= 8) && (os.length() <= 8)) ||
((os.length() >= 11) && (os.length() <= 11)))) {
validationEvent.setValidationStatus(SnmpConstants.
SNMP_ERROR_WRONG_LENGTH);
return;
}
//--AgentGen BEGIN=snmp4jAgentHBCtrlStartTime::validate
//--AgentGen END
}
}
// Rows and Factories
public class Snmp4jAgentHBCtrlEntryRow extends DefaultMOMutableRow2PC {
public Snmp4jAgentHBCtrlEntryRow(OID index, Variable[] values) {
super(index, values);
}
public OctetString getSnmp4jAgentHBCtrlStartTime() {
return (OctetString) getValue(idxSnmp4jAgentHBCtrlStartTime);
}
public void setSnmp4jAgentHBCtrlStartTime(OctetString newValue) {
setValue(idxSnmp4jAgentHBCtrlStartTime, newValue);
}
public UnsignedInteger32 getSnmp4jAgentHBCtrlDelay() {
return (UnsignedInteger32) getValue(idxSnmp4jAgentHBCtrlDelay);
}
public void setSnmp4jAgentHBCtrlDelay(UnsignedInteger32 newValue) {
setValue(idxSnmp4jAgentHBCtrlDelay, newValue);
}
public UnsignedInteger32 getSnmp4jAgentHBCtrlPeriod() {
return (UnsignedInteger32) getValue(idxSnmp4jAgentHBCtrlPeriod);
}
public void setSnmp4jAgentHBCtrlPeriod(UnsignedInteger32 newValue) {
setValue(idxSnmp4jAgentHBCtrlPeriod, newValue);
}
public UnsignedInteger32 getSnmp4jAgentHBCtrlMaxEvents() {
return (UnsignedInteger32) getValue(idxSnmp4jAgentHBCtrlMaxEvents);
}
public void setSnmp4jAgentHBCtrlMaxEvents(UnsignedInteger32 newValue) {
setValue(idxSnmp4jAgentHBCtrlMaxEvents, newValue);
}
public Counter64 getSnmp4jAgentHBCtrlEvents() {
return (Counter64) getValue(idxSnmp4jAgentHBCtrlEvents);
}
public void setSnmp4jAgentHBCtrlEvents(Counter64 newValue) {
setValue(idxSnmp4jAgentHBCtrlEvents, newValue);
}
public TimeTicks getSnmp4jAgentHBCtrlLastChange() {
return (TimeTicks) getValue(idxSnmp4jAgentHBCtrlLastChange);
}
public void setSnmp4jAgentHBCtrlLastChange(TimeTicks newValue) {
setValue(idxSnmp4jAgentHBCtrlLastChange, newValue);
}
public Integer32 getSnmp4jAgentHBCtrlStorageType() {
return (Integer32) getValue(idxSnmp4jAgentHBCtrlStorageType);
}
public void setSnmp4jAgentHBCtrlStorageType(Integer32 newValue) {
setValue(idxSnmp4jAgentHBCtrlStorageType, newValue);
}
public Integer32 getSnmp4jAgentHBCtrlRowStatus() {
return (Integer32) getValue(idxSnmp4jAgentHBCtrlRowStatus);
}
public void setSnmp4jAgentHBCtrlRowStatus(Integer32 newValue) {
setValue(idxSnmp4jAgentHBCtrlRowStatus, newValue);
}
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::Row
//--AgentGen END
}
class Snmp4jAgentHBCtrlEntryRowFactory
implements MOTableRowFactory<Snmp4jAgentHBCtrlEntryRow> {
public synchronized Snmp4jAgentHBCtrlEntryRow createRow(OID index, Variable[] values) throws
UnsupportedOperationException {
Snmp4jAgentHBCtrlEntryRow row = new Snmp4jAgentHBCtrlEntryRow(index,
values);
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::createRow
row.setSnmp4jAgentHBCtrlLastChange(sysUpTime.get());
row.setSnmp4jAgentHBCtrlEvents(new Counter64(0));
//--AgentGen END
return row;
}
public synchronized void freeRow(Snmp4jAgentHBCtrlEntryRow row) {
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::freeRow
//--AgentGen END
}
//--AgentGen BEGIN=snmp4jAgentHBCtrlEntry::RowFactory
//--AgentGen END
}
//--AgentGen BEGIN=_METHODS
public void rowStatusChanged(RowStatusEvent event) {
if (event.isDeniable()) {
if (event.isRowActivated()) {
// check column interdependent consistency
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
if ((row.getSnmp4jAgentHBCtrlDelay().getValue() == 0) &&
((row.getSnmp4jAgentHBCtrlStartTime() == null) ||
(DateAndTime.makeCalendar(
row.getSnmp4jAgentHBCtrlStartTime()).getTimeInMillis()
<= System.currentTimeMillis()))) {
event.setDenyReason(PDU.inconsistentValue);
}
}
}
else if (event.isRowActivated()) {
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
HeartbeatTask task = new HeartbeatTask(row);
if (row.getSnmp4jAgentHBCtrlDelay().getValue() == 0) {
long startTime = DateAndTime.makeCalendar(
row.getSnmp4jAgentHBCtrlStartTime()).getTimeInMillis() -
heartbeatOffset;
heartbeatTimer.schedule(task,
new Date(startTime),
row.getSnmp4jAgentHBCtrlPeriod().getValue());
}
else {
heartbeatTimer.schedule(task,
row.getSnmp4jAgentHBCtrlDelay().getValue(),
row.getSnmp4jAgentHBCtrlPeriod().getValue());
}
row.setUserObject(task);
}
else if (event.isRowDeactivated()) {
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
HeartbeatTask task = (HeartbeatTask) row.getUserObject();
if (task != null) {
task.cancel();
}
}
}
public void rowChanged(MOTableRowEvent event) {
if (event.getRow() != null) {
Snmp4jAgentHBCtrlEntryRow row =
(Snmp4jAgentHBCtrlEntryRow) event.getRow();
if (row.getSnmp4jAgentHBCtrlLastChange() != null) {
row.getSnmp4jAgentHBCtrlLastChange().setValue(sysUpTime.get().getValue());
}
}
}
//--AgentGen END
//--AgentGen BEGIN=_CLASSES
class HeartbeatTask extends TimerTask {
private Snmp4jAgentHBCtrlEntryRow configRow;
public HeartbeatTask(Snmp4jAgentHBCtrlEntryRow configRow) {
this.configRow = configRow;
}
public void run() {
if (configRow.getSnmp4jAgentHBCtrlRowStatus().getValue() ==
RowStatus.active) {
long maxEvents = configRow.getSnmp4jAgentHBCtrlMaxEvents().getValue();
if ((maxEvents > 0) &&
(configRow.getSnmp4jAgentHBCtrlEvents().getValue() < maxEvents)) {
configRow.getSnmp4jAgentHBCtrlEvents().increment();
OID instanceOID =
((DefaultMOTable) snmp4jAgentHBCtrlEntry).
getCellOID(configRow.getIndex(),
idxSnmp4jAgentHBCtrlEvents);
VariableBinding eventVB = new VariableBinding(instanceOID,
configRow.getSnmp4jAgentHBCtrlEvents());
snmp4jAgentHBEvent(notificationOriginator, context,
new VariableBinding[] {eventVB});
}
else {
cancel();
configRow.getSnmp4jAgentHBCtrlRowStatus().setValue(RowStatus.notInService);
}
}
else {
cancel();
}
}
}
//--AgentGen END
//--AgentGen BEGIN=_END
//--AgentGen END
}
|
100511_0 | package nl.han.ica.icss.transforms;
import nl.han.ica.icss.ast.*;
import nl.han.ica.icss.ast.literals.BoolLiteral;
public class RemoveIf implements Transform {
//TR02|Implementeer de `RemoveIf `transformatie. Deze transformatie verwijdert alle `IfClause`s uit de AST.
//Wanneer de conditie van de `IfClause` `TRUE` is wordt deze vervangen door de body van het if-statement.
// Als de conditie `FALSE` is dan verwijder je de `IfClause`volledig uit de AST.
@Override
public void apply(AST ast) {
for(ASTNode node : ast.root.getChildren()){
if(node instanceof Stylerule){
checkIfStatements(node);
}
}
}
private void checkIfStatements(ASTNode parent){
for(ASTNode node : parent.getChildren()){
if(node instanceof IfClause){ //Check of de ASTNode een IfClause is
checkIfStatements(node); //Voer de functie recursief uit
BoolLiteral boolLit = (BoolLiteral)((IfClause) node).conditionalExpression;
if(boolLit.value) { //Als conditie van IfClause TRUE is.
for (ASTNode child : node.getChildren()) {
if (child instanceof Declaration) {
parent.addChild(child); //Voeg body toe.
}
}
}
parent.removeChild(node); //Als conditie false is, verwijder de hele IfClause node.
}
}
}
}
| GGWPs/ASD-ICSS | startcode/src/main/java/nl/han/ica/icss/transforms/RemoveIf.java | 437 | //TR02|Implementeer de `RemoveIf `transformatie. Deze transformatie verwijdert alle `IfClause`s uit de AST. | line_comment | nl | package nl.han.ica.icss.transforms;
import nl.han.ica.icss.ast.*;
import nl.han.ica.icss.ast.literals.BoolLiteral;
public class RemoveIf implements Transform {
//TR02|Implementeer de<SUF>
//Wanneer de conditie van de `IfClause` `TRUE` is wordt deze vervangen door de body van het if-statement.
// Als de conditie `FALSE` is dan verwijder je de `IfClause`volledig uit de AST.
@Override
public void apply(AST ast) {
for(ASTNode node : ast.root.getChildren()){
if(node instanceof Stylerule){
checkIfStatements(node);
}
}
}
private void checkIfStatements(ASTNode parent){
for(ASTNode node : parent.getChildren()){
if(node instanceof IfClause){ //Check of de ASTNode een IfClause is
checkIfStatements(node); //Voer de functie recursief uit
BoolLiteral boolLit = (BoolLiteral)((IfClause) node).conditionalExpression;
if(boolLit.value) { //Als conditie van IfClause TRUE is.
for (ASTNode child : node.getChildren()) {
if (child instanceof Declaration) {
parent.addChild(child); //Voeg body toe.
}
}
}
parent.removeChild(node); //Als conditie false is, verwijder de hele IfClause node.
}
}
}
}
|
70437_4 | package nl.han.ise.DAO;
import nl.han.ise.ConnectionFactory;
import redis.clients.jedis.Jedis;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RapportageDAO {
private ConnectionFactory connectionFactory;
private Jedis jedis;
private Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public RapportageDAO(){
connectionFactory = new ConnectionFactory();
jedis = new Jedis(connectionFactory.getRedisHost());
}
//Vraagt de opgevraagde rapportage op via REDIS
public String getRapportage(String rapportage){
String rapportageJson = jedis.get(rapportage);
jedis.close();
return rapportageJson;
}
//Leegt de Redis database en vult hem opnieuw in vanuit de SQL database.
public void addAndUpdateAllRapportages(){
logger.log(Level.INFO, "redis geupdated op " + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now()));
jedis.flushAll();
List<String> lijstRapportages = lijstRapportagesSql();
for(int i = 0; i <= lijstRapportages.size()-1; i++){
addOrUpdateRapportage(lijstRapportages.get(i));
}
jedis.close();
}
//Functie om een rapportage toe te voegen of te wijzigen
public void addOrUpdateRapportage(String rapportage){
try (Connection connection = connectionFactory.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT (SELECT * FROM "+rapportage+" FOR JSON AUTO) AS Rapportage")) {
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()){
if(resultSet.getString("Rapportage") != null){
jedis.set(rapportage, resultSet.getString("Rapportage"));
}
}
} catch (SQLException e) {
logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN VAN RAPPORTAGES", e);
throw new RuntimeException(e);
}
}
//Functie om een lijst van rapportages op te halen van Jedis.
public List<String> lijstRapportagesRedis(){
List<String> rapportageLijst = new ArrayList<>();
Set<String> keys = jedis.keys("RAPPORTAGE_*");
for (String key : keys) {
rapportageLijst.add(key);
}
java.util.Collections.sort(rapportageLijst);
jedis.close();
return rapportageLijst;
}
//Functie om een lijst van rapportages op te halen van SQL.
public List<String> lijstRapportagesSql() {
List<String> rapportageLijst = new ArrayList<>();
try (Connection connection = connectionFactory.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT name FROM sys.views WHERE name LIKE 'RAPPORTAGE_%'")) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
rapportageLijst.add(resultSet.getString("name"));
}
return rapportageLijst;
} catch (SQLException e) {
logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN LIJST VAN RAPPORTAGES", e);
throw new RuntimeException(e);
}
}
}
| GGWPs/Filmcheques_API | filmcheques_API/src/main/java/nl/han/ise/DAO/RapportageDAO.java | 1,014 | //Functie om een lijst van rapportages op te halen van SQL. | line_comment | nl | package nl.han.ise.DAO;
import nl.han.ise.ConnectionFactory;
import redis.clients.jedis.Jedis;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RapportageDAO {
private ConnectionFactory connectionFactory;
private Jedis jedis;
private Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public RapportageDAO(){
connectionFactory = new ConnectionFactory();
jedis = new Jedis(connectionFactory.getRedisHost());
}
//Vraagt de opgevraagde rapportage op via REDIS
public String getRapportage(String rapportage){
String rapportageJson = jedis.get(rapportage);
jedis.close();
return rapportageJson;
}
//Leegt de Redis database en vult hem opnieuw in vanuit de SQL database.
public void addAndUpdateAllRapportages(){
logger.log(Level.INFO, "redis geupdated op " + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now()));
jedis.flushAll();
List<String> lijstRapportages = lijstRapportagesSql();
for(int i = 0; i <= lijstRapportages.size()-1; i++){
addOrUpdateRapportage(lijstRapportages.get(i));
}
jedis.close();
}
//Functie om een rapportage toe te voegen of te wijzigen
public void addOrUpdateRapportage(String rapportage){
try (Connection connection = connectionFactory.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT (SELECT * FROM "+rapportage+" FOR JSON AUTO) AS Rapportage")) {
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()){
if(resultSet.getString("Rapportage") != null){
jedis.set(rapportage, resultSet.getString("Rapportage"));
}
}
} catch (SQLException e) {
logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN VAN RAPPORTAGES", e);
throw new RuntimeException(e);
}
}
//Functie om een lijst van rapportages op te halen van Jedis.
public List<String> lijstRapportagesRedis(){
List<String> rapportageLijst = new ArrayList<>();
Set<String> keys = jedis.keys("RAPPORTAGE_*");
for (String key : keys) {
rapportageLijst.add(key);
}
java.util.Collections.sort(rapportageLijst);
jedis.close();
return rapportageLijst;
}
//Functie om<SUF>
public List<String> lijstRapportagesSql() {
List<String> rapportageLijst = new ArrayList<>();
try (Connection connection = connectionFactory.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT name FROM sys.views WHERE name LIKE 'RAPPORTAGE_%'")) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
rapportageLijst.add(resultSet.getString("name"));
}
return rapportageLijst;
} catch (SQLException e) {
logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN LIJST VAN RAPPORTAGES", e);
throw new RuntimeException(e);
}
}
}
|
28744_0 | package nl.han.ica.killthememe;
import java.net.URL;
import nl.han.ica.OOPDProcessingEngineHAN.alarm.Alarm;
import nl.han.ica.OOPDProcessingEngineHAN.alarm.IAlarmListener;
import nl.han.ica.OOPDProcessingEngineHAN.objects.AnimatedSpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.objects.SpriteObject;
public class Vogel extends AnimatedSpriteObject implements IAlarmListener {
private boolean inAnimatie;
private MainGame mainGame;
private int totalFramez = 0;
private static URL vogel = Vogel.class.getResource(
"/twitter-bird-sprite.png");
/**
* Vogel constructor
*
* @param mainGame de wereld
*/
public Vogel(MainGame mainGame) {
this(new Sprite(vogel.toString()));
this.mainGame = mainGame;
setCurrentFrameIndex(totalFramez);
}
/**
*
* @param sprite Vogel Sprite
*/
private Vogel(Sprite sprite) {
super(sprite, 4);
setxSpeed(-1);
}
/**
* functie voor de alarm voor de animatie.
*/
public void startAlarm() {
Alarm alarm = new Alarm("Animatie", 1 / 0.99f);
alarm.addTarget(this);
alarm.start();
}
/**
* Zodra de alarm afgaat, wordt deze functie uitgevoerd en wisselt hij een
* boolean voor de animatie en maakt hij magAanvallen false.
*
*/
public void triggerAlarm(String alarmName) {
inAnimatie = false;
}
/**
* Functie die kijkt of de vogel uit het scherm gaat, zodra hij dat doet komt
* hij weer vanuit een random X positie weer terug aan de rechterkant van de
* spelers scherm. Bevat ook een functie voor de animatie van de vogel.
*/
@Override
public void update() {
if (getX() + getWidth() <= 0) {
setX(mainGame.getWidth());
setY(mainGame.random(0, mainGame.getHeight()));
}
if (!inAnimatie) {
if (totalFramez == 4) {
totalFramez = 0;
}
if (totalFramez < 4) {
setCurrentFrameIndex(totalFramez);
totalFramez++;
inAnimatie = true;
startAlarm();
}
}
}
}
| GGWPs/Kill-The-Meme | src/main/java/nl/han/ica/killthememe/Vogel.java | 727 | /**
* Vogel constructor
*
* @param mainGame de wereld
*/ | block_comment | nl | package nl.han.ica.killthememe;
import java.net.URL;
import nl.han.ica.OOPDProcessingEngineHAN.alarm.Alarm;
import nl.han.ica.OOPDProcessingEngineHAN.alarm.IAlarmListener;
import nl.han.ica.OOPDProcessingEngineHAN.objects.AnimatedSpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.objects.SpriteObject;
public class Vogel extends AnimatedSpriteObject implements IAlarmListener {
private boolean inAnimatie;
private MainGame mainGame;
private int totalFramez = 0;
private static URL vogel = Vogel.class.getResource(
"/twitter-bird-sprite.png");
/**
* Vogel constructor
<SUF>*/
public Vogel(MainGame mainGame) {
this(new Sprite(vogel.toString()));
this.mainGame = mainGame;
setCurrentFrameIndex(totalFramez);
}
/**
*
* @param sprite Vogel Sprite
*/
private Vogel(Sprite sprite) {
super(sprite, 4);
setxSpeed(-1);
}
/**
* functie voor de alarm voor de animatie.
*/
public void startAlarm() {
Alarm alarm = new Alarm("Animatie", 1 / 0.99f);
alarm.addTarget(this);
alarm.start();
}
/**
* Zodra de alarm afgaat, wordt deze functie uitgevoerd en wisselt hij een
* boolean voor de animatie en maakt hij magAanvallen false.
*
*/
public void triggerAlarm(String alarmName) {
inAnimatie = false;
}
/**
* Functie die kijkt of de vogel uit het scherm gaat, zodra hij dat doet komt
* hij weer vanuit een random X positie weer terug aan de rechterkant van de
* spelers scherm. Bevat ook een functie voor de animatie van de vogel.
*/
@Override
public void update() {
if (getX() + getWidth() <= 0) {
setX(mainGame.getWidth());
setY(mainGame.random(0, mainGame.getHeight()));
}
if (!inAnimatie) {
if (totalFramez == 4) {
totalFramez = 0;
}
if (totalFramez < 4) {
setCurrentFrameIndex(totalFramez);
totalFramez++;
inAnimatie = true;
startAlarm();
}
}
}
}
|
75970_29 | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.routing.ch;
import com.carrotsearch.hppc.*;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.graphhopper.storage.CHStorageBuilder;
import com.graphhopper.util.BitUtil;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.PMap;
import com.graphhopper.util.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Locale;
import static com.graphhopper.routing.ch.CHParameters.*;
import static com.graphhopper.util.GHUtility.reverseEdgeKey;
import static com.graphhopper.util.Helper.nf;
/**
* This class is used to calculate the priority of or contract a given node in edge-based Contraction Hierarchies as it
* is required to support turn-costs. This implementation follows the 'aggressive' variant described in
* 'Efficient Routing in Road Networks with Turn Costs' by R. Geisberger and C. Vetter. Here, we do not store the center
* node for each shortcut, but introduce helper shortcuts when a loop shortcut is encountered.
* <p>
* This class is mostly concerned with triggering the required local searches and introducing the necessary shortcuts
* or calculating the node priority, while the actual searches for witness paths are delegated to
* {@link EdgeBasedWitnessPathSearcher}.
*
* @author easbar
*/
class EdgeBasedNodeContractor implements NodeContractor {
private static final Logger LOGGER = LoggerFactory.getLogger(EdgeBasedNodeContractor.class);
private final CHPreparationGraph prepareGraph;
private PrepareGraphEdgeExplorer inEdgeExplorer;
private PrepareGraphEdgeExplorer outEdgeExplorer;
private PrepareGraphEdgeExplorer existingShortcutExplorer;
private PrepareGraphOrigEdgeExplorer sourceNodeOrigInEdgeExplorer;
private CHStorageBuilder chBuilder;
private final Params params = new Params();
private final StopWatch dijkstraSW = new StopWatch();
// temporary data used during node contraction
private final IntSet sourceNodes = new IntHashSet(10);
private final IntSet targetNodes = new IntHashSet(10);
private final LongSet addedShortcuts = new LongHashSet();
private final Stats addingStats = new Stats();
private final Stats countingStats = new Stats();
private Stats activeStats;
private int[] hierarchyDepths;
private EdgeBasedWitnessPathSearcher witnessPathSearcher;
private BridgePathFinder bridgePathFinder;
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsHeur = new EdgeBasedWitnessPathSearcher.Stats();
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsContr = new EdgeBasedWitnessPathSearcher.Stats();
// counts the total number of added shortcuts
private int addedShortcutsCount;
// edge counts used to calculate priority
private int numShortcuts;
private int numPrevEdges;
private int numOrigEdges;
private int numPrevOrigEdges;
private int numAllEdges;
private double meanDegree;
public EdgeBasedNodeContractor(CHPreparationGraph prepareGraph, CHStorageBuilder chBuilder, PMap pMap) {
this.prepareGraph = prepareGraph;
this.chBuilder = chBuilder;
extractParams(pMap);
}
private void extractParams(PMap pMap) {
params.edgeQuotientWeight = pMap.getFloat(EDGE_QUOTIENT_WEIGHT, params.edgeQuotientWeight);
params.originalEdgeQuotientWeight = pMap.getFloat(ORIGINAL_EDGE_QUOTIENT_WEIGHT, params.originalEdgeQuotientWeight);
params.hierarchyDepthWeight = pMap.getFloat(HIERARCHY_DEPTH_WEIGHT, params.hierarchyDepthWeight);
params.maxPollFactorHeuristic = pMap.getDouble(MAX_POLL_FACTOR_HEURISTIC_EDGE, params.maxPollFactorHeuristic);
params.maxPollFactorContraction = pMap.getDouble(MAX_POLL_FACTOR_CONTRACTION_EDGE, params.maxPollFactorContraction);
}
@Override
public void initFromGraph() {
inEdgeExplorer = prepareGraph.createInEdgeExplorer();
outEdgeExplorer = prepareGraph.createOutEdgeExplorer();
existingShortcutExplorer = prepareGraph.createOutEdgeExplorer();
sourceNodeOrigInEdgeExplorer = prepareGraph.createInOrigEdgeExplorer();
hierarchyDepths = new int[prepareGraph.getNodes()];
witnessPathSearcher = new EdgeBasedWitnessPathSearcher(prepareGraph);
bridgePathFinder = new BridgePathFinder(prepareGraph);
meanDegree = prepareGraph.getOriginalEdges() * 1.0 / prepareGraph.getNodes();
}
@Override
public float calculatePriority(int node) {
activeStats = countingStats;
resetEdgeCounters();
countPreviousEdges(node);
if (numAllEdges == 0)
// this node is isolated, maybe it belongs to a removed subnetwork, in any case we can quickly contract it
// no shortcuts will be introduced
return Float.NEGATIVE_INFINITY;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::countShortcuts, (int) (meanDegree * params.maxPollFactorHeuristic), wpsStatsHeur);
stats().stopWatch.stop();
// the higher the priority the later (!) this node will be contracted
float edgeQuotient = numShortcuts / (float) (prepareGraph.getDegree(node));
float origEdgeQuotient = numOrigEdges / (float) numPrevOrigEdges;
int hierarchyDepth = hierarchyDepths[node];
float priority = params.edgeQuotientWeight * edgeQuotient +
params.originalEdgeQuotientWeight * origEdgeQuotient +
params.hierarchyDepthWeight * hierarchyDepth;
if (LOGGER.isTraceEnabled())
LOGGER.trace("node: {}, eq: {} / {} = {}, oeq: {} / {} = {}, depth: {} --> {}",
node,
numShortcuts, numPrevEdges, edgeQuotient,
numOrigEdges, numPrevOrigEdges, origEdgeQuotient,
hierarchyDepth, priority);
return priority;
}
@Override
public IntContainer contractNode(int node) {
activeStats = addingStats;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::addShortcutsToPrepareGraph, (int) (meanDegree * params.maxPollFactorContraction), wpsStatsContr);
insertShortcuts(node);
IntContainer neighbors = prepareGraph.disconnect(node);
// We maintain an approximation of the mean degree which we update after every contracted node.
// We do it the same way as for node-based CH for now.
meanDegree = (meanDegree * 2 + neighbors.size()) / 3;
updateHierarchyDepthsOfNeighbors(node, neighbors);
stats().stopWatch.stop();
return neighbors;
}
@Override
public void finishContraction() {
chBuilder.replaceSkippedEdges(prepareGraph::getShortcutForPrepareEdge);
}
@Override
public long getAddedShortcutsCount() {
return addedShortcutsCount;
}
@Override
public float getDijkstraSeconds() {
return dijkstraSW.getCurrentSeconds();
}
@Override
public String getStatisticsString() {
return String.format(Locale.ROOT, "degree_approx: %3.1f", meanDegree) + ", priority : " + countingStats + ", " + wpsStatsHeur + ", contraction: " + addingStats + ", " + wpsStatsContr;
}
/**
* This method performs witness searches between all nodes adjacent to the given node and calls the
* given handler for all required shortcuts.
*/
private void findAndHandlePrepareShortcuts(int node, PrepareShortcutHandler shortcutHandler, int maxPolls, EdgeBasedWitnessPathSearcher.Stats wpsStats) {
stats().nodes++;
addedShortcuts.clear();
sourceNodes.clear();
// traverse incoming edges/shortcuts to find all the source nodes
PrepareGraphEdgeIterator incomingEdges = inEdgeExplorer.setBaseNode(node);
while (incomingEdges.next()) {
final int sourceNode = incomingEdges.getAdjNode();
if (sourceNode == node)
continue;
// make sure we process each source node only once
if (!sourceNodes.add(sourceNode))
continue;
// for each source node we need to look at every incoming original edge and check which target edges are reachable
PrepareGraphOrigEdgeIterator origInIter = sourceNodeOrigInEdgeExplorer.setBaseNode(sourceNode);
while (origInIter.next()) {
int origInKey = reverseEdgeKey(origInIter.getOrigEdgeKeyLast());
// we search 'bridge paths' leading to the target edges
IntObjectMap<BridgePathFinder.BridePathEntry> bridgePaths = bridgePathFinder.find(origInKey, sourceNode, node);
if (bridgePaths.isEmpty())
continue;
witnessPathSearcher.initSearch(origInKey, sourceNode, node, wpsStats);
for (IntObjectCursor<BridgePathFinder.BridePathEntry> bridgePath : bridgePaths) {
if (!Double.isFinite(bridgePath.value.weight))
throw new IllegalStateException("Bridge entry weights should always be finite");
int targetEdgeKey = bridgePath.key;
dijkstraSW.start();
double weight = witnessPathSearcher.runSearch(bridgePath.value.chEntry.adjNode, targetEdgeKey, bridgePath.value.weight, maxPolls);
dijkstraSW.stop();
if (weight <= bridgePath.value.weight)
// we found a witness, nothing to do
continue;
PrepareCHEntry root = bridgePath.value.chEntry;
while (EdgeIterator.Edge.isValid(root.parent.prepareEdge))
root = root.getParent();
// we make sure to add each shortcut only once. when we are actually adding shortcuts we check for existing
// shortcuts anyway, but at least this is important when we *count* shortcuts.
long addedShortcutKey = BitUtil.LITTLE.combineIntsToLong(root.firstEdgeKey, bridgePath.value.chEntry.incEdgeKey);
if (!addedShortcuts.add(addedShortcutKey))
continue;
double initialTurnCost = prepareGraph.getTurnWeight(origInKey, sourceNode, root.firstEdgeKey);
bridgePath.value.chEntry.weight -= initialTurnCost;
LOGGER.trace("Adding shortcuts for target entry {}", bridgePath.value.chEntry);
// todo: re-implement loop-avoidance heuristic as it existed in GH 1.0? it did not work the
// way it was implemented so it was removed at some point
shortcutHandler.handleShortcut(root, bridgePath.value.chEntry, bridgePath.value.chEntry.origEdges);
}
witnessPathSearcher.finishSearch();
}
}
}
/**
* Calls the shortcut handler for all edges and shortcuts adjacent to the given node. After this method is called
* these edges and shortcuts will be removed from the prepare graph, so this method offers the last chance to deal
* with them.
*/
private void insertShortcuts(int node) {
insertOutShortcuts(node);
insertInShortcuts(node);
}
private void insertOutShortcuts(int node) {
PrepareGraphEdgeIterator iter = outEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScFwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void insertInShortcuts(int node) {
PrepareGraphEdgeIterator iter = inEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
// we added loops already using the outEdgeExplorer
if (iter.getAdjNode() == node)
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScBwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void countPreviousEdges(int node) {
// todo: this edge counting can probably be simplified, but we might need to re-optimize heuristic parameters then
PrepareGraphEdgeIterator outIter = outEdgeExplorer.setBaseNode(node);
while (outIter.next()) {
numAllEdges++;
numPrevEdges++;
numPrevOrigEdges += outIter.getOrigEdgeCount();
}
PrepareGraphEdgeIterator inIter = inEdgeExplorer.setBaseNode(node);
while (inIter.next()) {
numAllEdges++;
// do not consider loop edges a second time
if (inIter.getBaseNode() == inIter.getAdjNode())
continue;
numPrevEdges++;
numPrevOrigEdges += inIter.getOrigEdgeCount();
}
}
private void updateHierarchyDepthsOfNeighbors(int node, IntContainer neighbors) {
int level = hierarchyDepths[node];
for (IntCursor n : neighbors) {
if (n.value == node)
continue;
hierarchyDepths[n.value] = Math.max(hierarchyDepths[n.value], level + 1);
}
}
private PrepareCHEntry addShortcutsToPrepareGraph(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
if (edgeTo.parent.prepareEdge != edgeFrom.prepareEdge) {
// counting origEdgeCount correctly is tricky with loop shortcuts and the recursion we use here. so we
// simply ignore this, it probably does not matter that much
PrepareCHEntry prev = addShortcutsToPrepareGraph(edgeFrom, edgeTo.getParent(), origEdgeCount);
return doAddShortcut(prev, edgeTo, origEdgeCount);
} else {
return doAddShortcut(edgeFrom, edgeTo, origEdgeCount);
}
}
private PrepareCHEntry doAddShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int from = edgeFrom.parent.adjNode;
int adjNode = edgeTo.adjNode;
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(from);
while (iter.next()) {
if (!isSameShortcut(iter, adjNode, edgeFrom.firstEdgeKey, edgeTo.incEdgeKey)) {
// this is some other (shortcut) edge -> we do not care
continue;
}
final double existingWeight = iter.getWeight();
if (existingWeight <= edgeTo.weight) {
// our shortcut already exists with lower weight --> do nothing
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, existingWeight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
} else {
// update weight
iter.setSkippedEdges(edgeFrom.prepareEdge, edgeTo.prepareEdge);
iter.setWeight(edgeTo.weight);
iter.setOrigEdgeCount(origEdgeCount);
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
}
// our shortcut is new --> add it
int origFirstKey = edgeFrom.firstEdgeKey;
LOGGER.trace("Adding shortcut from {} to {}, weight: {}, firstOrigEdgeKey: {}, lastOrigEdgeKey: {}",
from, adjNode, edgeTo.weight, origFirstKey, edgeTo.incEdgeKey);
int prepareEdge = prepareGraph.addShortcut(from, adjNode, origFirstKey, edgeTo.incEdgeKey, edgeFrom.prepareEdge, edgeTo.prepareEdge, edgeTo.weight, origEdgeCount);
// does not matter here
int incEdgeKey = -1;
PrepareCHEntry entry = new PrepareCHEntry(prepareEdge, origFirstKey, incEdgeKey, edgeTo.adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
private boolean isSameShortcut(PrepareGraphEdgeIterator iter, int adjNode, int firstOrigEdgeKey, int lastOrigEdgeKey) {
return iter.isShortcut()
&& (iter.getAdjNode() == adjNode)
&& (iter.getOrigEdgeKeyFirst() == firstOrigEdgeKey)
&& (iter.getOrigEdgeKeyLast() == lastOrigEdgeKey);
}
private void resetEdgeCounters() {
numShortcuts = 0;
numPrevEdges = 0;
numOrigEdges = 0;
numPrevOrigEdges = 0;
numAllEdges = 0;
}
@Override
public void close() {
prepareGraph.close();
inEdgeExplorer = null;
outEdgeExplorer = null;
existingShortcutExplorer = null;
sourceNodeOrigInEdgeExplorer = null;
chBuilder = null;
witnessPathSearcher.close();
sourceNodes.release();
targetNodes.release();
addedShortcuts.release();
hierarchyDepths = null;
}
private Stats stats() {
return activeStats;
}
@FunctionalInterface
private interface PrepareShortcutHandler {
void handleShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount);
}
private void countShortcuts(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int fromNode = edgeFrom.parent.adjNode;
int toNode = edgeTo.adjNode;
int firstOrigEdgeKey = edgeFrom.firstEdgeKey;
int lastOrigEdgeKey = edgeTo.incEdgeKey;
// check if this shortcut already exists
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(fromNode);
while (iter.next()) {
if (isSameShortcut(iter, toNode, firstOrigEdgeKey, lastOrigEdgeKey)) {
// this shortcut exists already, maybe its weight will be updated but we should not count it as
// a new edge
return;
}
}
// this shortcut is new --> increase counts
while (edgeTo != edgeFrom) {
numShortcuts++;
edgeTo = edgeTo.parent;
}
numOrigEdges += origEdgeCount;
}
long getNumPolledEdges() {
return wpsStatsContr.numPolls + wpsStatsHeur.numPolls;
}
public static class Params {
private float edgeQuotientWeight = 100;
private float originalEdgeQuotientWeight = 100;
private float hierarchyDepthWeight = 20;
// Increasing these parameters (heuristic especially) will lead to a longer preparation time but also to fewer
// shortcuts and possibly (slightly) faster queries.
private double maxPollFactorHeuristic = 5;
private double maxPollFactorContraction = 200;
}
private static class Stats {
int nodes;
StopWatch stopWatch = new StopWatch();
@Override
public String toString() {
return String.format(Locale.ROOT,
"time: %7.2fs, nodes: %10s", stopWatch.getCurrentSeconds(), nf(nodes));
}
}
}
| GIScience/graphhopper | core/src/main/java/com/graphhopper/routing/ch/EdgeBasedNodeContractor.java | 5,702 | // does not matter here | line_comment | nl | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.routing.ch;
import com.carrotsearch.hppc.*;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.graphhopper.storage.CHStorageBuilder;
import com.graphhopper.util.BitUtil;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.PMap;
import com.graphhopper.util.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Locale;
import static com.graphhopper.routing.ch.CHParameters.*;
import static com.graphhopper.util.GHUtility.reverseEdgeKey;
import static com.graphhopper.util.Helper.nf;
/**
* This class is used to calculate the priority of or contract a given node in edge-based Contraction Hierarchies as it
* is required to support turn-costs. This implementation follows the 'aggressive' variant described in
* 'Efficient Routing in Road Networks with Turn Costs' by R. Geisberger and C. Vetter. Here, we do not store the center
* node for each shortcut, but introduce helper shortcuts when a loop shortcut is encountered.
* <p>
* This class is mostly concerned with triggering the required local searches and introducing the necessary shortcuts
* or calculating the node priority, while the actual searches for witness paths are delegated to
* {@link EdgeBasedWitnessPathSearcher}.
*
* @author easbar
*/
class EdgeBasedNodeContractor implements NodeContractor {
private static final Logger LOGGER = LoggerFactory.getLogger(EdgeBasedNodeContractor.class);
private final CHPreparationGraph prepareGraph;
private PrepareGraphEdgeExplorer inEdgeExplorer;
private PrepareGraphEdgeExplorer outEdgeExplorer;
private PrepareGraphEdgeExplorer existingShortcutExplorer;
private PrepareGraphOrigEdgeExplorer sourceNodeOrigInEdgeExplorer;
private CHStorageBuilder chBuilder;
private final Params params = new Params();
private final StopWatch dijkstraSW = new StopWatch();
// temporary data used during node contraction
private final IntSet sourceNodes = new IntHashSet(10);
private final IntSet targetNodes = new IntHashSet(10);
private final LongSet addedShortcuts = new LongHashSet();
private final Stats addingStats = new Stats();
private final Stats countingStats = new Stats();
private Stats activeStats;
private int[] hierarchyDepths;
private EdgeBasedWitnessPathSearcher witnessPathSearcher;
private BridgePathFinder bridgePathFinder;
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsHeur = new EdgeBasedWitnessPathSearcher.Stats();
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsContr = new EdgeBasedWitnessPathSearcher.Stats();
// counts the total number of added shortcuts
private int addedShortcutsCount;
// edge counts used to calculate priority
private int numShortcuts;
private int numPrevEdges;
private int numOrigEdges;
private int numPrevOrigEdges;
private int numAllEdges;
private double meanDegree;
public EdgeBasedNodeContractor(CHPreparationGraph prepareGraph, CHStorageBuilder chBuilder, PMap pMap) {
this.prepareGraph = prepareGraph;
this.chBuilder = chBuilder;
extractParams(pMap);
}
private void extractParams(PMap pMap) {
params.edgeQuotientWeight = pMap.getFloat(EDGE_QUOTIENT_WEIGHT, params.edgeQuotientWeight);
params.originalEdgeQuotientWeight = pMap.getFloat(ORIGINAL_EDGE_QUOTIENT_WEIGHT, params.originalEdgeQuotientWeight);
params.hierarchyDepthWeight = pMap.getFloat(HIERARCHY_DEPTH_WEIGHT, params.hierarchyDepthWeight);
params.maxPollFactorHeuristic = pMap.getDouble(MAX_POLL_FACTOR_HEURISTIC_EDGE, params.maxPollFactorHeuristic);
params.maxPollFactorContraction = pMap.getDouble(MAX_POLL_FACTOR_CONTRACTION_EDGE, params.maxPollFactorContraction);
}
@Override
public void initFromGraph() {
inEdgeExplorer = prepareGraph.createInEdgeExplorer();
outEdgeExplorer = prepareGraph.createOutEdgeExplorer();
existingShortcutExplorer = prepareGraph.createOutEdgeExplorer();
sourceNodeOrigInEdgeExplorer = prepareGraph.createInOrigEdgeExplorer();
hierarchyDepths = new int[prepareGraph.getNodes()];
witnessPathSearcher = new EdgeBasedWitnessPathSearcher(prepareGraph);
bridgePathFinder = new BridgePathFinder(prepareGraph);
meanDegree = prepareGraph.getOriginalEdges() * 1.0 / prepareGraph.getNodes();
}
@Override
public float calculatePriority(int node) {
activeStats = countingStats;
resetEdgeCounters();
countPreviousEdges(node);
if (numAllEdges == 0)
// this node is isolated, maybe it belongs to a removed subnetwork, in any case we can quickly contract it
// no shortcuts will be introduced
return Float.NEGATIVE_INFINITY;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::countShortcuts, (int) (meanDegree * params.maxPollFactorHeuristic), wpsStatsHeur);
stats().stopWatch.stop();
// the higher the priority the later (!) this node will be contracted
float edgeQuotient = numShortcuts / (float) (prepareGraph.getDegree(node));
float origEdgeQuotient = numOrigEdges / (float) numPrevOrigEdges;
int hierarchyDepth = hierarchyDepths[node];
float priority = params.edgeQuotientWeight * edgeQuotient +
params.originalEdgeQuotientWeight * origEdgeQuotient +
params.hierarchyDepthWeight * hierarchyDepth;
if (LOGGER.isTraceEnabled())
LOGGER.trace("node: {}, eq: {} / {} = {}, oeq: {} / {} = {}, depth: {} --> {}",
node,
numShortcuts, numPrevEdges, edgeQuotient,
numOrigEdges, numPrevOrigEdges, origEdgeQuotient,
hierarchyDepth, priority);
return priority;
}
@Override
public IntContainer contractNode(int node) {
activeStats = addingStats;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::addShortcutsToPrepareGraph, (int) (meanDegree * params.maxPollFactorContraction), wpsStatsContr);
insertShortcuts(node);
IntContainer neighbors = prepareGraph.disconnect(node);
// We maintain an approximation of the mean degree which we update after every contracted node.
// We do it the same way as for node-based CH for now.
meanDegree = (meanDegree * 2 + neighbors.size()) / 3;
updateHierarchyDepthsOfNeighbors(node, neighbors);
stats().stopWatch.stop();
return neighbors;
}
@Override
public void finishContraction() {
chBuilder.replaceSkippedEdges(prepareGraph::getShortcutForPrepareEdge);
}
@Override
public long getAddedShortcutsCount() {
return addedShortcutsCount;
}
@Override
public float getDijkstraSeconds() {
return dijkstraSW.getCurrentSeconds();
}
@Override
public String getStatisticsString() {
return String.format(Locale.ROOT, "degree_approx: %3.1f", meanDegree) + ", priority : " + countingStats + ", " + wpsStatsHeur + ", contraction: " + addingStats + ", " + wpsStatsContr;
}
/**
* This method performs witness searches between all nodes adjacent to the given node and calls the
* given handler for all required shortcuts.
*/
private void findAndHandlePrepareShortcuts(int node, PrepareShortcutHandler shortcutHandler, int maxPolls, EdgeBasedWitnessPathSearcher.Stats wpsStats) {
stats().nodes++;
addedShortcuts.clear();
sourceNodes.clear();
// traverse incoming edges/shortcuts to find all the source nodes
PrepareGraphEdgeIterator incomingEdges = inEdgeExplorer.setBaseNode(node);
while (incomingEdges.next()) {
final int sourceNode = incomingEdges.getAdjNode();
if (sourceNode == node)
continue;
// make sure we process each source node only once
if (!sourceNodes.add(sourceNode))
continue;
// for each source node we need to look at every incoming original edge and check which target edges are reachable
PrepareGraphOrigEdgeIterator origInIter = sourceNodeOrigInEdgeExplorer.setBaseNode(sourceNode);
while (origInIter.next()) {
int origInKey = reverseEdgeKey(origInIter.getOrigEdgeKeyLast());
// we search 'bridge paths' leading to the target edges
IntObjectMap<BridgePathFinder.BridePathEntry> bridgePaths = bridgePathFinder.find(origInKey, sourceNode, node);
if (bridgePaths.isEmpty())
continue;
witnessPathSearcher.initSearch(origInKey, sourceNode, node, wpsStats);
for (IntObjectCursor<BridgePathFinder.BridePathEntry> bridgePath : bridgePaths) {
if (!Double.isFinite(bridgePath.value.weight))
throw new IllegalStateException("Bridge entry weights should always be finite");
int targetEdgeKey = bridgePath.key;
dijkstraSW.start();
double weight = witnessPathSearcher.runSearch(bridgePath.value.chEntry.adjNode, targetEdgeKey, bridgePath.value.weight, maxPolls);
dijkstraSW.stop();
if (weight <= bridgePath.value.weight)
// we found a witness, nothing to do
continue;
PrepareCHEntry root = bridgePath.value.chEntry;
while (EdgeIterator.Edge.isValid(root.parent.prepareEdge))
root = root.getParent();
// we make sure to add each shortcut only once. when we are actually adding shortcuts we check for existing
// shortcuts anyway, but at least this is important when we *count* shortcuts.
long addedShortcutKey = BitUtil.LITTLE.combineIntsToLong(root.firstEdgeKey, bridgePath.value.chEntry.incEdgeKey);
if (!addedShortcuts.add(addedShortcutKey))
continue;
double initialTurnCost = prepareGraph.getTurnWeight(origInKey, sourceNode, root.firstEdgeKey);
bridgePath.value.chEntry.weight -= initialTurnCost;
LOGGER.trace("Adding shortcuts for target entry {}", bridgePath.value.chEntry);
// todo: re-implement loop-avoidance heuristic as it existed in GH 1.0? it did not work the
// way it was implemented so it was removed at some point
shortcutHandler.handleShortcut(root, bridgePath.value.chEntry, bridgePath.value.chEntry.origEdges);
}
witnessPathSearcher.finishSearch();
}
}
}
/**
* Calls the shortcut handler for all edges and shortcuts adjacent to the given node. After this method is called
* these edges and shortcuts will be removed from the prepare graph, so this method offers the last chance to deal
* with them.
*/
private void insertShortcuts(int node) {
insertOutShortcuts(node);
insertInShortcuts(node);
}
private void insertOutShortcuts(int node) {
PrepareGraphEdgeIterator iter = outEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScFwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void insertInShortcuts(int node) {
PrepareGraphEdgeIterator iter = inEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
// we added loops already using the outEdgeExplorer
if (iter.getAdjNode() == node)
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScBwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void countPreviousEdges(int node) {
// todo: this edge counting can probably be simplified, but we might need to re-optimize heuristic parameters then
PrepareGraphEdgeIterator outIter = outEdgeExplorer.setBaseNode(node);
while (outIter.next()) {
numAllEdges++;
numPrevEdges++;
numPrevOrigEdges += outIter.getOrigEdgeCount();
}
PrepareGraphEdgeIterator inIter = inEdgeExplorer.setBaseNode(node);
while (inIter.next()) {
numAllEdges++;
// do not consider loop edges a second time
if (inIter.getBaseNode() == inIter.getAdjNode())
continue;
numPrevEdges++;
numPrevOrigEdges += inIter.getOrigEdgeCount();
}
}
private void updateHierarchyDepthsOfNeighbors(int node, IntContainer neighbors) {
int level = hierarchyDepths[node];
for (IntCursor n : neighbors) {
if (n.value == node)
continue;
hierarchyDepths[n.value] = Math.max(hierarchyDepths[n.value], level + 1);
}
}
private PrepareCHEntry addShortcutsToPrepareGraph(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
if (edgeTo.parent.prepareEdge != edgeFrom.prepareEdge) {
// counting origEdgeCount correctly is tricky with loop shortcuts and the recursion we use here. so we
// simply ignore this, it probably does not matter that much
PrepareCHEntry prev = addShortcutsToPrepareGraph(edgeFrom, edgeTo.getParent(), origEdgeCount);
return doAddShortcut(prev, edgeTo, origEdgeCount);
} else {
return doAddShortcut(edgeFrom, edgeTo, origEdgeCount);
}
}
private PrepareCHEntry doAddShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int from = edgeFrom.parent.adjNode;
int adjNode = edgeTo.adjNode;
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(from);
while (iter.next()) {
if (!isSameShortcut(iter, adjNode, edgeFrom.firstEdgeKey, edgeTo.incEdgeKey)) {
// this is some other (shortcut) edge -> we do not care
continue;
}
final double existingWeight = iter.getWeight();
if (existingWeight <= edgeTo.weight) {
// our shortcut already exists with lower weight --> do nothing
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, existingWeight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
} else {
// update weight
iter.setSkippedEdges(edgeFrom.prepareEdge, edgeTo.prepareEdge);
iter.setWeight(edgeTo.weight);
iter.setOrigEdgeCount(origEdgeCount);
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
}
// our shortcut is new --> add it
int origFirstKey = edgeFrom.firstEdgeKey;
LOGGER.trace("Adding shortcut from {} to {}, weight: {}, firstOrigEdgeKey: {}, lastOrigEdgeKey: {}",
from, adjNode, edgeTo.weight, origFirstKey, edgeTo.incEdgeKey);
int prepareEdge = prepareGraph.addShortcut(from, adjNode, origFirstKey, edgeTo.incEdgeKey, edgeFrom.prepareEdge, edgeTo.prepareEdge, edgeTo.weight, origEdgeCount);
// does not<SUF>
int incEdgeKey = -1;
PrepareCHEntry entry = new PrepareCHEntry(prepareEdge, origFirstKey, incEdgeKey, edgeTo.adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
private boolean isSameShortcut(PrepareGraphEdgeIterator iter, int adjNode, int firstOrigEdgeKey, int lastOrigEdgeKey) {
return iter.isShortcut()
&& (iter.getAdjNode() == adjNode)
&& (iter.getOrigEdgeKeyFirst() == firstOrigEdgeKey)
&& (iter.getOrigEdgeKeyLast() == lastOrigEdgeKey);
}
private void resetEdgeCounters() {
numShortcuts = 0;
numPrevEdges = 0;
numOrigEdges = 0;
numPrevOrigEdges = 0;
numAllEdges = 0;
}
@Override
public void close() {
prepareGraph.close();
inEdgeExplorer = null;
outEdgeExplorer = null;
existingShortcutExplorer = null;
sourceNodeOrigInEdgeExplorer = null;
chBuilder = null;
witnessPathSearcher.close();
sourceNodes.release();
targetNodes.release();
addedShortcuts.release();
hierarchyDepths = null;
}
private Stats stats() {
return activeStats;
}
@FunctionalInterface
private interface PrepareShortcutHandler {
void handleShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount);
}
private void countShortcuts(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int fromNode = edgeFrom.parent.adjNode;
int toNode = edgeTo.adjNode;
int firstOrigEdgeKey = edgeFrom.firstEdgeKey;
int lastOrigEdgeKey = edgeTo.incEdgeKey;
// check if this shortcut already exists
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(fromNode);
while (iter.next()) {
if (isSameShortcut(iter, toNode, firstOrigEdgeKey, lastOrigEdgeKey)) {
// this shortcut exists already, maybe its weight will be updated but we should not count it as
// a new edge
return;
}
}
// this shortcut is new --> increase counts
while (edgeTo != edgeFrom) {
numShortcuts++;
edgeTo = edgeTo.parent;
}
numOrigEdges += origEdgeCount;
}
long getNumPolledEdges() {
return wpsStatsContr.numPolls + wpsStatsHeur.numPolls;
}
public static class Params {
private float edgeQuotientWeight = 100;
private float originalEdgeQuotientWeight = 100;
private float hierarchyDepthWeight = 20;
// Increasing these parameters (heuristic especially) will lead to a longer preparation time but also to fewer
// shortcuts and possibly (slightly) faster queries.
private double maxPollFactorHeuristic = 5;
private double maxPollFactorContraction = 200;
}
private static class Stats {
int nodes;
StopWatch stopWatch = new StopWatch();
@Override
public String toString() {
return String.format(Locale.ROOT,
"time: %7.2fs, nodes: %10s", stopWatch.getCurrentSeconds(), nf(nodes));
}
}
}
|
160712_16 | package org.heigit.ors.api;
import com.graphhopper.util.Helper;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.lang3.StringUtils;
import org.heigit.ors.routing.RoutingProfileType;
import org.heigit.ors.routing.configuration.RouteProfileConfiguration;
import org.heigit.ors.util.ProfileTools;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Configuration
@ConfigurationProperties(prefix = "ors.engine")
public class EngineProperties {
private int initThreads;
private boolean preparationMode;
private String sourceFile;
private String graphsRootPath;
private String graphsDataAccess;
private ElevationProperties elevation;
private ProfileProperties profileDefault;
private Map<String, ProfileProperties> profiles;
public int getInitThreads() {
return initThreads;
}
public void setInitThreads(int initThreads) {
this.initThreads = initThreads;
}
public boolean isPreparationMode() {
return preparationMode;
}
public void setPreparationMode(boolean preparationMode) {
this.preparationMode = preparationMode;
}
public String getSourceFile() {
return sourceFile;
}
public void setSourceFile(String sourceFile) {
if (StringUtils.isNotBlank(sourceFile))
this.sourceFile = Paths.get(sourceFile).toAbsolutePath().toString();
else this.sourceFile = sourceFile;
}
public String getGraphsRootPath() {
return graphsRootPath;
}
public void setGraphsRootPath(String graphsRootPath) {
if (StringUtils.isNotBlank(graphsRootPath))
this.graphsRootPath = Paths.get(graphsRootPath).toAbsolutePath().toString();
else this.graphsRootPath = graphsRootPath;
}
public String getGraphsDataAccess() {
return graphsDataAccess;
}
public void setGraphsDataAccess(String graphsDataAccess) {
this.graphsDataAccess = graphsDataAccess;
}
public ElevationProperties getElevation() {
return elevation;
}
public void setElevation(ElevationProperties elevation) {
this.elevation = elevation;
}
public ProfileProperties getProfileDefault() {
return profileDefault;
}
public void setProfileDefault(ProfileProperties profileDefault) {
this.profileDefault = profileDefault;
}
public Map<String, ProfileProperties> getProfiles() {
return profiles;
}
public void setProfiles(Map<String, ProfileProperties> profiles) {
this.profiles = profiles;
}
public RouteProfileConfiguration[] getConvertedProfiles() {
List<RouteProfileConfiguration> convertedProfiles = new ArrayList<>();
if (profiles != null) {
for (Map.Entry<String, ProfileProperties> profileEntry : profiles.entrySet()) {
ProfileProperties profile = profileEntry.getValue();
boolean enabled = profile.enabled != null ? profile.enabled : profileDefault.isEnabled();
if (!enabled) {
continue;
}
RouteProfileConfiguration convertedProfile = new RouteProfileConfiguration();
convertedProfile.setName(profileEntry.getKey());
convertedProfile.setEnabled(enabled);
convertedProfile.setProfiles(profile.getProfile());
String graphPath = profile.getGraphPath();
String rootGraphsPath = getGraphsRootPath();
if (!Helper.isEmpty(rootGraphsPath)) {
if (Helper.isEmpty(graphPath))
graphPath = Paths.get(rootGraphsPath, profileEntry.getKey()).toString();
}
convertedProfile.setGraphPath(graphPath);
convertedProfile.setEncoderOptions(profile.getEncoderOptionsString());
convertedProfile.setOptimize(profile.optimize != null ? profile.optimize : profileDefault.getOptimize());
convertedProfile.setEncoderFlagsSize(profile.encoderFlagsSize != null ? profile.encoderFlagsSize : profileDefault.getEncoderFlagsSize());
convertedProfile.setInstructions(profile.instructions != null ? profile.instructions : profileDefault.getInstructions());
convertedProfile.setMaximumDistance(profile.maximumDistance != null ? profile.maximumDistance : profileDefault.getMaximumDistance());
convertedProfile.setMaximumDistanceDynamicWeights(profile.maximumDistanceDynamicWeights != null ? profile.maximumDistanceDynamicWeights : profileDefault.getMaximumDistanceDynamicWeights());
convertedProfile.setMaximumDistanceAvoidAreas(profile.maximumDistanceAvoidAreas != null ? profile.maximumDistanceAvoidAreas : profileDefault.getMaximumDistanceAvoidAreas());
convertedProfile.setMaximumDistanceAlternativeRoutes(profile.maximumDistanceAlternativeRoutes != null ? profile.maximumDistanceAlternativeRoutes : profileDefault.getMaximumDistanceAlternativeRoutes());
convertedProfile.setMaximumDistanceRoundTripRoutes(profile.maximumDistanceRoundTripRoutes != null ? profile.maximumDistanceRoundTripRoutes : profileDefault.getMaximumDistanceRoundTripRoutes());
convertedProfile.setMaximumSpeedLowerBound(profile.maximumSpeedLowerBound != null ? profile.maximumSpeedLowerBound : profileDefault.getMaximumSpeedLowerBound());
convertedProfile.setMaximumWayPoints(profile.maximumWayPoints != null ? profile.maximumWayPoints : profileDefault.getMaximumWayPoints());
convertedProfile.setMaximumSnappingRadius(profile.maximumSnappingRadius != null ? profile.maximumSnappingRadius : profileDefault.getMaximumSnappingRadius());
convertedProfile.setLocationIndexResolution(profile.locationIndexResolution != null ? profile.locationIndexResolution : profileDefault.getLocationIndexResolution());
convertedProfile.setLocationIndexSearchIterations(profile.locationIndexSearchIterations != null ? profile.locationIndexSearchIterations : profileDefault.getLocationIndexSearchIterations());
convertedProfile.setEnforceTurnCosts(profile.forceTurnCosts != null ? profile.forceTurnCosts : profileDefault.getForceTurnCosts());
convertedProfile.setGtfsFile(profile.gtfsFile != null ? profile.gtfsFile : profile.getGtfsFile());
convertedProfile.setMaximumVisitedNodesPT(profile.maximumVisitedNodes != null ? profile.maximumVisitedNodes : profileDefault.getMaximumVisitedNodes());
if (profile.elevation != null && profile.elevation || profileDefault.isElevation()) {
convertedProfile.setElevationProvider(elevation.getProvider());
convertedProfile.setElevationCachePath(elevation.getCachePath());
convertedProfile.setElevationDataAccess(elevation.getDataAccess());
convertedProfile.setElevationCacheClear(elevation.isCacheClear());
convertedProfile.setElevationSmoothing(profile.elevationSmoothing != null ? profile.elevationSmoothing : profileDefault.getElevationSmoothing());
convertedProfile.setInterpolateBridgesAndTunnels(profile.interpolateBridgesAndTunnels != null ? profile.interpolateBridgesAndTunnels : profileDefault.getInterpolateBridgesAndTunnels());
}
Map<String, Object> preparation = profile.preparation != null ? profile.preparation : profileDefault.getPreparation();
if (preparation != null) {
convertedProfile.setPreparationOpts(ConfigFactory.parseMap(preparation));
String methodsKey = "methods";
if (preparation.containsKey(methodsKey) && preparation.get(methodsKey) != null && ((Map<String, Object>) preparation.get(methodsKey)).containsKey("fastisochrones")) {
convertedProfile.setIsochronePreparationOpts(ConfigFactory.parseMap((Map<String, Object>) ((Map<String, Object>) preparation.get(methodsKey)).get("fastisochrones")));
}
}
Map<String, Object> execution = profile.execution != null ? profile.execution : profileDefault.getExecution();
if (execution != null) {
convertedProfile.setExecutionOpts(ConfigFactory.parseMap(execution));
}
if (profile.getExtStorages() != null) {
for (Map<String, String> storageParams : profile.getExtStorages().values()) {
storageParams.put("gh_profile", ProfileTools.makeProfileName(RoutingProfileType.getEncoderName(RoutingProfileType.getFromString(convertedProfile.getProfiles())), "fastest", RouteProfileConfiguration.hasTurnCosts(convertedProfile.getEncoderOptions())));
storageParams.remove("");
}
convertedProfile.getExtStorages().putAll(profile.getExtStorages());
}
convertedProfiles.add(convertedProfile);
}
}
return convertedProfiles.toArray(new RouteProfileConfiguration[0]);
}
public static class ElevationProperties {
private boolean preprocessed;
private boolean cacheClear;
private String provider;
private String cachePath;
private String dataAccess;
public boolean isPreprocessed() {
return preprocessed;
}
public void setPreprocessed(boolean preprocessed) {
this.preprocessed = preprocessed;
}
public boolean isCacheClear() {
return cacheClear;
}
public void setCacheClear(boolean cacheClear) {
this.cacheClear = cacheClear;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getCachePath() {
return cachePath;
}
public void setCachePath(String cachePath) {
if (StringUtils.isNotBlank(cachePath))
this.cachePath = Paths.get(cachePath).toAbsolutePath().toString();
else this.cachePath = cachePath;
}
public String getDataAccess() {
return dataAccess;
}
public void setDataAccess(String dataAccess) {
this.dataAccess = dataAccess;
}
}
public static class ProfileProperties {
private String profile;
private Boolean enabled;
private Boolean elevation;
private Boolean elevationSmoothing;
private Boolean traffic;
private Boolean interpolateBridgesAndTunnels;
private Boolean instructions;
private Boolean optimize;
private String graphPath;
private Map<String, String> encoderOptions;
//TODO: For later use when refactoring RoutingManagerConfiguration
// private PreparationProperties preparation;
// private ExecutionProperties execution;
private Map<String, Object> preparation;
private Map<String, Object> execution;
private Map<String, Map<String, String>> extStorages;
private Double maximumDistance;
private Double maximumDistanceDynamicWeights;
private Double maximumDistanceAvoidAreas;
private Double maximumDistanceAlternativeRoutes;
private Double maximumDistanceRoundTripRoutes;
private Double maximumSpeedLowerBound;
private Integer maximumWayPoints;
private Integer maximumSnappingRadius;
private Integer maximumVisitedNodes;
private Integer encoderFlagsSize;
private Integer locationIndexResolution = 500;
private Integer locationIndexSearchIterations = 4;
private Boolean forceTurnCosts;
private String gtfsFile;
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public boolean isEnabled() {
return enabled != null && enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isElevation() {
return elevation != null && elevation;
}
public void setElevation(boolean elevation) {
this.elevation = elevation;
}
public Boolean getElevationSmoothing() {
return elevationSmoothing != null && elevationSmoothing;
}
public void setElevationSmoothing(Boolean elevationSmoothing) {
this.elevationSmoothing = elevationSmoothing;
}
public boolean isTraffic() {
return traffic != null && traffic;
}
public void setTraffic(boolean traffic) {
this.traffic = traffic;
}
public boolean getInterpolateBridgesAndTunnels() {
return interpolateBridgesAndTunnels != null && interpolateBridgesAndTunnels;
}
public void setInterpolateBridgesAndTunnels(Boolean interpolateBridgesAndTunnels) {
this.interpolateBridgesAndTunnels = interpolateBridgesAndTunnels;
}
public boolean getInstructions() {
return instructions != null ? instructions : true;
}
public void setInstructions(Boolean instructions) {
this.instructions = instructions;
}
public boolean getOptimize() {
return optimize != null && optimize;
}
public void setOptimize(Boolean optimize) {
this.optimize = optimize;
}
public String getGraphPath() {
return graphPath;
}
public void setGraphPath(String graphPath) {
if (StringUtils.isNotBlank(graphPath))
this.graphPath = Paths.get(graphPath).toAbsolutePath().toString();
else this.graphPath = graphPath;
}
public Map<String, String> getEncoderOptions() {
return encoderOptions;
}
public String getEncoderOptionsString() {
if (encoderOptions == null || encoderOptions.isEmpty())
return "";
StringBuilder output = new StringBuilder();
for (Map.Entry<String, String> entry : encoderOptions.entrySet()) {
if (!output.isEmpty()) {
output.append("|");
}
output.append(entry.getKey()).append("=").append(entry.getValue());
}
return output.toString();
}
public void setEncoderOptions(Map<String, String> encoderOptions) {
this.encoderOptions = encoderOptions;
}
// For later use when refactoring RoutingManagerConfiguration
// public PreparationProperties getPreparation() {
// return preparation;
// }
//
// public void setPreparation(PreparationProperties preparation) {
// this.preparation = preparation;
// }
//
// public ExecutionProperties getExecution() {
// return execution;
// }
//
// public void setExecution(ExecutionProperties execution) {
// this.execution = execution;
// }
public Map<String, Object> getPreparation() {
return preparation;
}
public void setPreparation(Map<String, Object> preparation) {
this.preparation = preparation;
}
public Map<String, Object> getExecution() {
return execution;
}
public void setExecution(Map<String, Object> execution) {
this.execution = execution;
}
public Map<String, Map<String, String>> getExtStorages() {
return extStorages;
}
public void setExtStorages(Map<String, Map<String, String>> extStorages) {
// Todo write individual storage config classes
// Iterate over each storage in the extStorages and overwrite all paths variables with absolute paths#
for (Map.Entry<String, Map<String, String>> storage : extStorages.entrySet()) {
if (storage.getKey().equals("HereTraffic")) {
// Replace streets, ref_pattern pattern_15min and log_location with absolute paths
String hereTrafficPath = storage.getValue().get("streets");
if (StringUtils.isNotBlank(hereTrafficPath)) {
storage.getValue().put("streets", Paths.get(hereTrafficPath).toAbsolutePath().toString());
}
String hereTrafficRefPattern = storage.getValue().get("ref_pattern");
if (StringUtils.isNotBlank(hereTrafficRefPattern)) {
storage.getValue().put("ref_pattern", Paths.get(hereTrafficRefPattern).toAbsolutePath().toString());
}
String hereTrafficPattern15min = storage.getValue().get("pattern_15min");
if (StringUtils.isNotBlank(hereTrafficPattern15min)) {
storage.getValue().put("pattern_15min", Paths.get(hereTrafficPattern15min).toAbsolutePath().toString());
}
String hereTrafficLogLocation = storage.getValue().get("log_location");
if (StringUtils.isNotBlank(hereTrafficLogLocation)) {
storage.getValue().put("log_location", Paths.get(hereTrafficLogLocation).toAbsolutePath().toString());
}
}
if (storage.getKey().equals("Borders")) {
// Replace boundaries, ids and openborders with absolute paths
String bordersBoundaries = storage.getValue().get("boundaries");
if (StringUtils.isNotBlank(bordersBoundaries)) {
storage.getValue().put("boundaries", Paths.get(bordersBoundaries).toAbsolutePath().toString());
}
String bordersIds = storage.getValue().get("ids");
if (StringUtils.isNotBlank(bordersIds)) {
storage.getValue().put("ids", Paths.get(bordersIds).toAbsolutePath().toString());
}
String openBorders = storage.getValue().get("openborders");
if (StringUtils.isNotBlank(openBorders)) {
storage.getValue().put("openborders", Paths.get(openBorders).toAbsolutePath().toString());
}
}
if (storage.getKey().equals("GreenIndex") || storage.getKey().equals("NoiseIndex") || storage.getKey().equals("csv") || storage.getKey().equals("ShadowIndex")) {
// replace filepath
String indexFilePath = storage.getValue().get("filepath");
if (indexFilePath != null) {
storage.getValue().put("filepath", Paths.get(indexFilePath).toAbsolutePath().toString());
}
}
}
this.extStorages = extStorages;
}
public double getMaximumDistance() {
return maximumDistance != null ? maximumDistance : 0;
}
public void setMaximumDistance(double maximumDistance) {
this.maximumDistance = maximumDistance;
}
public double getMaximumDistanceDynamicWeights() {
return maximumDistanceDynamicWeights != null ? maximumDistanceDynamicWeights : 0;
}
public void setMaximumDistanceDynamicWeights(double maximumDistanceDynamicWeights) {
this.maximumDistanceDynamicWeights = maximumDistanceDynamicWeights;
}
public double getMaximumDistanceAvoidAreas() {
return maximumDistanceAvoidAreas != null ? maximumDistanceAvoidAreas : 0;
}
public void setMaximumDistanceAvoidAreas(double maximumDistanceAvoidAreas) {
this.maximumDistanceAvoidAreas = maximumDistanceAvoidAreas;
}
public double getMaximumDistanceAlternativeRoutes() {
return maximumDistanceAlternativeRoutes != null ? maximumDistanceAlternativeRoutes : 0;
}
public void setMaximumDistanceAlternativeRoutes(double maximumDistanceAlternativeRoutes) {
this.maximumDistanceAlternativeRoutes = maximumDistanceAlternativeRoutes;
}
public double getMaximumDistanceRoundTripRoutes() {
return maximumDistanceRoundTripRoutes != null ? maximumDistanceRoundTripRoutes : 0;
}
public void setMaximumDistanceRoundTripRoutes(double maximumDistanceRoundTripRoutes) {
this.maximumDistanceRoundTripRoutes = maximumDistanceRoundTripRoutes;
}
public double getMaximumSpeedLowerBound() {
return maximumSpeedLowerBound != null ? maximumSpeedLowerBound : 0;
}
public void setMaximumSpeedLowerBound(Double maximumSpeedLowerBound) {
this.maximumSpeedLowerBound = maximumSpeedLowerBound;
}
public int getMaximumWayPoints() {
return maximumWayPoints != null ? maximumWayPoints : 0;
}
public void setMaximumWayPoints(int maximumWayPoints) {
this.maximumWayPoints = maximumWayPoints;
}
public int getMaximumSnappingRadius() {
return maximumSnappingRadius != null ? maximumSnappingRadius : 0;
}
public void setMaximumSnappingRadius(int maximumSnappingRadius) {
this.maximumSnappingRadius = maximumSnappingRadius;
}
public int getMaximumVisitedNodes() {
return maximumVisitedNodes != null ? maximumVisitedNodes : 0;
}
public void setMaximumVisitedNodes(Integer maximumVisitedNodes) {
this.maximumVisitedNodes = maximumVisitedNodes;
}
public int getEncoderFlagsSize() {
return encoderFlagsSize != null ? encoderFlagsSize : 0;
}
public void setEncoderFlagsSize(Integer encoderFlagsSize) {
this.encoderFlagsSize = encoderFlagsSize;
}
public Integer getLocationIndexResolution() {
return locationIndexResolution != null ? locationIndexResolution : 0;
}
public void setLocationIndexResolution(Integer locationIndexResolution) {
this.locationIndexResolution = locationIndexResolution;
}
public Integer getLocationIndexSearchIterations() {
return locationIndexSearchIterations != null ? locationIndexSearchIterations : 0;
}
public void setLocationIndexSearchIterations(Integer locationIndexSearchIterations) {
this.locationIndexSearchIterations = locationIndexSearchIterations;
}
public boolean getForceTurnCosts() {
return forceTurnCosts != null && forceTurnCosts;
}
public void setForceTurnCosts(Boolean forceTurnCosts) {
this.forceTurnCosts = forceTurnCosts;
}
public String getGtfsFile() {
return gtfsFile != null ? gtfsFile : "";
}
public void setGtfsFile(String gtfsFile) {
if (StringUtils.isNotBlank(gtfsFile))
this.gtfsFile = Paths.get(gtfsFile).toAbsolutePath().toString();
else this.gtfsFile = gtfsFile;
}
// For later use when refactoring RoutingManagerConfiguration
// public static class PreparationProperties {
// private int minNetworkSize;
// private int minOneWayNetworkSize;
//
// public MethodsProperties getMethods() {
// return methods;
// }
//
// public PreparationProperties setMethods(MethodsProperties methods) {
// this.methods = methods;
// return this;
// }
//
// private MethodsProperties methods;
//
// public int getMinNetworkSize() {
// return minNetworkSize;
// }
//
// public void setMinNetworkSize(int minNetworkSize) {
// this.minNetworkSize = minNetworkSize;
// }
//
// public int getMinOneWayNetworkSize() {
// return minOneWayNetworkSize;
// }
//
// public void setMinOneWayNetworkSize(int minOneWayNetworkSize) {
// this.minOneWayNetworkSize = minOneWayNetworkSize;
// }
// }
//
// public static class MethodsProperties {
// private CHProperties ch;
// private LMProperties lm;
// private CoreProperties core;
// private FastIsochroneProperties fastisochrones;
//
// public CHProperties getCh() {
// return ch;
// }
//
// public void setCh(CHProperties ch) {
// this.ch = ch;
// }
//
// public LMProperties getLm() {
// return lm;
// }
//
// public void setLm(LMProperties lm) {
// this.lm = lm;
// }
//
// public CoreProperties getCore() {
// return core;
// }
//
// public void setCore(CoreProperties core) {
// this.core = core;
// }
//
// public FastIsochroneProperties getFastisochrones() {
// return fastisochrones;
// }
//
// public void setFastisochrones(FastIsochroneProperties fastisochrones) {
// this.fastisochrones = fastisochrones;
// }
//
// }
//
// public static class CHProperties {
// //TBD
// }
//
// public static class LMProperties {
// //TBD
// }
//
// public static class CoreProperties {
// //TBD
// }
//
// public static class FastIsochroneProperties {
// private boolean enabled;
// private int threads;
// private String weightings;
// private int maxcellnodes;
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public int getThreads() {
// return threads;
// }
//
// public void setThreads(int threads) {
// this.threads = threads;
// }
//
// public String getWeightings() {
// return weightings;
// }
//
// public void setWeightings(String weightings) {
// this.weightings = weightings;
// }
//
// public int getMaxcellnodes() {
// return maxcellnodes;
// }
//
// public void setMaxcellnodes(int maxcellnodes) {
// this.maxcellnodes = maxcellnodes;
// }
// }
//
// public static class ExecutionProperties {
// private Map<String, Map<String, String>> methods;
//
// public Map<String, Map<String, String>> getMethods() {
// return methods;
// }
//
// public void setMethods(Map<String, Map<String, String>> methods) {
// this.methods = methods;
// }
// }
}
}
| GIScience/openrouteservice | ors-api/src/main/java/org/heigit/ors/api/EngineProperties.java | 6,839 | // private int minNetworkSize; | line_comment | nl | package org.heigit.ors.api;
import com.graphhopper.util.Helper;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.lang3.StringUtils;
import org.heigit.ors.routing.RoutingProfileType;
import org.heigit.ors.routing.configuration.RouteProfileConfiguration;
import org.heigit.ors.util.ProfileTools;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Configuration
@ConfigurationProperties(prefix = "ors.engine")
public class EngineProperties {
private int initThreads;
private boolean preparationMode;
private String sourceFile;
private String graphsRootPath;
private String graphsDataAccess;
private ElevationProperties elevation;
private ProfileProperties profileDefault;
private Map<String, ProfileProperties> profiles;
public int getInitThreads() {
return initThreads;
}
public void setInitThreads(int initThreads) {
this.initThreads = initThreads;
}
public boolean isPreparationMode() {
return preparationMode;
}
public void setPreparationMode(boolean preparationMode) {
this.preparationMode = preparationMode;
}
public String getSourceFile() {
return sourceFile;
}
public void setSourceFile(String sourceFile) {
if (StringUtils.isNotBlank(sourceFile))
this.sourceFile = Paths.get(sourceFile).toAbsolutePath().toString();
else this.sourceFile = sourceFile;
}
public String getGraphsRootPath() {
return graphsRootPath;
}
public void setGraphsRootPath(String graphsRootPath) {
if (StringUtils.isNotBlank(graphsRootPath))
this.graphsRootPath = Paths.get(graphsRootPath).toAbsolutePath().toString();
else this.graphsRootPath = graphsRootPath;
}
public String getGraphsDataAccess() {
return graphsDataAccess;
}
public void setGraphsDataAccess(String graphsDataAccess) {
this.graphsDataAccess = graphsDataAccess;
}
public ElevationProperties getElevation() {
return elevation;
}
public void setElevation(ElevationProperties elevation) {
this.elevation = elevation;
}
public ProfileProperties getProfileDefault() {
return profileDefault;
}
public void setProfileDefault(ProfileProperties profileDefault) {
this.profileDefault = profileDefault;
}
public Map<String, ProfileProperties> getProfiles() {
return profiles;
}
public void setProfiles(Map<String, ProfileProperties> profiles) {
this.profiles = profiles;
}
public RouteProfileConfiguration[] getConvertedProfiles() {
List<RouteProfileConfiguration> convertedProfiles = new ArrayList<>();
if (profiles != null) {
for (Map.Entry<String, ProfileProperties> profileEntry : profiles.entrySet()) {
ProfileProperties profile = profileEntry.getValue();
boolean enabled = profile.enabled != null ? profile.enabled : profileDefault.isEnabled();
if (!enabled) {
continue;
}
RouteProfileConfiguration convertedProfile = new RouteProfileConfiguration();
convertedProfile.setName(profileEntry.getKey());
convertedProfile.setEnabled(enabled);
convertedProfile.setProfiles(profile.getProfile());
String graphPath = profile.getGraphPath();
String rootGraphsPath = getGraphsRootPath();
if (!Helper.isEmpty(rootGraphsPath)) {
if (Helper.isEmpty(graphPath))
graphPath = Paths.get(rootGraphsPath, profileEntry.getKey()).toString();
}
convertedProfile.setGraphPath(graphPath);
convertedProfile.setEncoderOptions(profile.getEncoderOptionsString());
convertedProfile.setOptimize(profile.optimize != null ? profile.optimize : profileDefault.getOptimize());
convertedProfile.setEncoderFlagsSize(profile.encoderFlagsSize != null ? profile.encoderFlagsSize : profileDefault.getEncoderFlagsSize());
convertedProfile.setInstructions(profile.instructions != null ? profile.instructions : profileDefault.getInstructions());
convertedProfile.setMaximumDistance(profile.maximumDistance != null ? profile.maximumDistance : profileDefault.getMaximumDistance());
convertedProfile.setMaximumDistanceDynamicWeights(profile.maximumDistanceDynamicWeights != null ? profile.maximumDistanceDynamicWeights : profileDefault.getMaximumDistanceDynamicWeights());
convertedProfile.setMaximumDistanceAvoidAreas(profile.maximumDistanceAvoidAreas != null ? profile.maximumDistanceAvoidAreas : profileDefault.getMaximumDistanceAvoidAreas());
convertedProfile.setMaximumDistanceAlternativeRoutes(profile.maximumDistanceAlternativeRoutes != null ? profile.maximumDistanceAlternativeRoutes : profileDefault.getMaximumDistanceAlternativeRoutes());
convertedProfile.setMaximumDistanceRoundTripRoutes(profile.maximumDistanceRoundTripRoutes != null ? profile.maximumDistanceRoundTripRoutes : profileDefault.getMaximumDistanceRoundTripRoutes());
convertedProfile.setMaximumSpeedLowerBound(profile.maximumSpeedLowerBound != null ? profile.maximumSpeedLowerBound : profileDefault.getMaximumSpeedLowerBound());
convertedProfile.setMaximumWayPoints(profile.maximumWayPoints != null ? profile.maximumWayPoints : profileDefault.getMaximumWayPoints());
convertedProfile.setMaximumSnappingRadius(profile.maximumSnappingRadius != null ? profile.maximumSnappingRadius : profileDefault.getMaximumSnappingRadius());
convertedProfile.setLocationIndexResolution(profile.locationIndexResolution != null ? profile.locationIndexResolution : profileDefault.getLocationIndexResolution());
convertedProfile.setLocationIndexSearchIterations(profile.locationIndexSearchIterations != null ? profile.locationIndexSearchIterations : profileDefault.getLocationIndexSearchIterations());
convertedProfile.setEnforceTurnCosts(profile.forceTurnCosts != null ? profile.forceTurnCosts : profileDefault.getForceTurnCosts());
convertedProfile.setGtfsFile(profile.gtfsFile != null ? profile.gtfsFile : profile.getGtfsFile());
convertedProfile.setMaximumVisitedNodesPT(profile.maximumVisitedNodes != null ? profile.maximumVisitedNodes : profileDefault.getMaximumVisitedNodes());
if (profile.elevation != null && profile.elevation || profileDefault.isElevation()) {
convertedProfile.setElevationProvider(elevation.getProvider());
convertedProfile.setElevationCachePath(elevation.getCachePath());
convertedProfile.setElevationDataAccess(elevation.getDataAccess());
convertedProfile.setElevationCacheClear(elevation.isCacheClear());
convertedProfile.setElevationSmoothing(profile.elevationSmoothing != null ? profile.elevationSmoothing : profileDefault.getElevationSmoothing());
convertedProfile.setInterpolateBridgesAndTunnels(profile.interpolateBridgesAndTunnels != null ? profile.interpolateBridgesAndTunnels : profileDefault.getInterpolateBridgesAndTunnels());
}
Map<String, Object> preparation = profile.preparation != null ? profile.preparation : profileDefault.getPreparation();
if (preparation != null) {
convertedProfile.setPreparationOpts(ConfigFactory.parseMap(preparation));
String methodsKey = "methods";
if (preparation.containsKey(methodsKey) && preparation.get(methodsKey) != null && ((Map<String, Object>) preparation.get(methodsKey)).containsKey("fastisochrones")) {
convertedProfile.setIsochronePreparationOpts(ConfigFactory.parseMap((Map<String, Object>) ((Map<String, Object>) preparation.get(methodsKey)).get("fastisochrones")));
}
}
Map<String, Object> execution = profile.execution != null ? profile.execution : profileDefault.getExecution();
if (execution != null) {
convertedProfile.setExecutionOpts(ConfigFactory.parseMap(execution));
}
if (profile.getExtStorages() != null) {
for (Map<String, String> storageParams : profile.getExtStorages().values()) {
storageParams.put("gh_profile", ProfileTools.makeProfileName(RoutingProfileType.getEncoderName(RoutingProfileType.getFromString(convertedProfile.getProfiles())), "fastest", RouteProfileConfiguration.hasTurnCosts(convertedProfile.getEncoderOptions())));
storageParams.remove("");
}
convertedProfile.getExtStorages().putAll(profile.getExtStorages());
}
convertedProfiles.add(convertedProfile);
}
}
return convertedProfiles.toArray(new RouteProfileConfiguration[0]);
}
public static class ElevationProperties {
private boolean preprocessed;
private boolean cacheClear;
private String provider;
private String cachePath;
private String dataAccess;
public boolean isPreprocessed() {
return preprocessed;
}
public void setPreprocessed(boolean preprocessed) {
this.preprocessed = preprocessed;
}
public boolean isCacheClear() {
return cacheClear;
}
public void setCacheClear(boolean cacheClear) {
this.cacheClear = cacheClear;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getCachePath() {
return cachePath;
}
public void setCachePath(String cachePath) {
if (StringUtils.isNotBlank(cachePath))
this.cachePath = Paths.get(cachePath).toAbsolutePath().toString();
else this.cachePath = cachePath;
}
public String getDataAccess() {
return dataAccess;
}
public void setDataAccess(String dataAccess) {
this.dataAccess = dataAccess;
}
}
public static class ProfileProperties {
private String profile;
private Boolean enabled;
private Boolean elevation;
private Boolean elevationSmoothing;
private Boolean traffic;
private Boolean interpolateBridgesAndTunnels;
private Boolean instructions;
private Boolean optimize;
private String graphPath;
private Map<String, String> encoderOptions;
//TODO: For later use when refactoring RoutingManagerConfiguration
// private PreparationProperties preparation;
// private ExecutionProperties execution;
private Map<String, Object> preparation;
private Map<String, Object> execution;
private Map<String, Map<String, String>> extStorages;
private Double maximumDistance;
private Double maximumDistanceDynamicWeights;
private Double maximumDistanceAvoidAreas;
private Double maximumDistanceAlternativeRoutes;
private Double maximumDistanceRoundTripRoutes;
private Double maximumSpeedLowerBound;
private Integer maximumWayPoints;
private Integer maximumSnappingRadius;
private Integer maximumVisitedNodes;
private Integer encoderFlagsSize;
private Integer locationIndexResolution = 500;
private Integer locationIndexSearchIterations = 4;
private Boolean forceTurnCosts;
private String gtfsFile;
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public boolean isEnabled() {
return enabled != null && enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isElevation() {
return elevation != null && elevation;
}
public void setElevation(boolean elevation) {
this.elevation = elevation;
}
public Boolean getElevationSmoothing() {
return elevationSmoothing != null && elevationSmoothing;
}
public void setElevationSmoothing(Boolean elevationSmoothing) {
this.elevationSmoothing = elevationSmoothing;
}
public boolean isTraffic() {
return traffic != null && traffic;
}
public void setTraffic(boolean traffic) {
this.traffic = traffic;
}
public boolean getInterpolateBridgesAndTunnels() {
return interpolateBridgesAndTunnels != null && interpolateBridgesAndTunnels;
}
public void setInterpolateBridgesAndTunnels(Boolean interpolateBridgesAndTunnels) {
this.interpolateBridgesAndTunnels = interpolateBridgesAndTunnels;
}
public boolean getInstructions() {
return instructions != null ? instructions : true;
}
public void setInstructions(Boolean instructions) {
this.instructions = instructions;
}
public boolean getOptimize() {
return optimize != null && optimize;
}
public void setOptimize(Boolean optimize) {
this.optimize = optimize;
}
public String getGraphPath() {
return graphPath;
}
public void setGraphPath(String graphPath) {
if (StringUtils.isNotBlank(graphPath))
this.graphPath = Paths.get(graphPath).toAbsolutePath().toString();
else this.graphPath = graphPath;
}
public Map<String, String> getEncoderOptions() {
return encoderOptions;
}
public String getEncoderOptionsString() {
if (encoderOptions == null || encoderOptions.isEmpty())
return "";
StringBuilder output = new StringBuilder();
for (Map.Entry<String, String> entry : encoderOptions.entrySet()) {
if (!output.isEmpty()) {
output.append("|");
}
output.append(entry.getKey()).append("=").append(entry.getValue());
}
return output.toString();
}
public void setEncoderOptions(Map<String, String> encoderOptions) {
this.encoderOptions = encoderOptions;
}
// For later use when refactoring RoutingManagerConfiguration
// public PreparationProperties getPreparation() {
// return preparation;
// }
//
// public void setPreparation(PreparationProperties preparation) {
// this.preparation = preparation;
// }
//
// public ExecutionProperties getExecution() {
// return execution;
// }
//
// public void setExecution(ExecutionProperties execution) {
// this.execution = execution;
// }
public Map<String, Object> getPreparation() {
return preparation;
}
public void setPreparation(Map<String, Object> preparation) {
this.preparation = preparation;
}
public Map<String, Object> getExecution() {
return execution;
}
public void setExecution(Map<String, Object> execution) {
this.execution = execution;
}
public Map<String, Map<String, String>> getExtStorages() {
return extStorages;
}
public void setExtStorages(Map<String, Map<String, String>> extStorages) {
// Todo write individual storage config classes
// Iterate over each storage in the extStorages and overwrite all paths variables with absolute paths#
for (Map.Entry<String, Map<String, String>> storage : extStorages.entrySet()) {
if (storage.getKey().equals("HereTraffic")) {
// Replace streets, ref_pattern pattern_15min and log_location with absolute paths
String hereTrafficPath = storage.getValue().get("streets");
if (StringUtils.isNotBlank(hereTrafficPath)) {
storage.getValue().put("streets", Paths.get(hereTrafficPath).toAbsolutePath().toString());
}
String hereTrafficRefPattern = storage.getValue().get("ref_pattern");
if (StringUtils.isNotBlank(hereTrafficRefPattern)) {
storage.getValue().put("ref_pattern", Paths.get(hereTrafficRefPattern).toAbsolutePath().toString());
}
String hereTrafficPattern15min = storage.getValue().get("pattern_15min");
if (StringUtils.isNotBlank(hereTrafficPattern15min)) {
storage.getValue().put("pattern_15min", Paths.get(hereTrafficPattern15min).toAbsolutePath().toString());
}
String hereTrafficLogLocation = storage.getValue().get("log_location");
if (StringUtils.isNotBlank(hereTrafficLogLocation)) {
storage.getValue().put("log_location", Paths.get(hereTrafficLogLocation).toAbsolutePath().toString());
}
}
if (storage.getKey().equals("Borders")) {
// Replace boundaries, ids and openborders with absolute paths
String bordersBoundaries = storage.getValue().get("boundaries");
if (StringUtils.isNotBlank(bordersBoundaries)) {
storage.getValue().put("boundaries", Paths.get(bordersBoundaries).toAbsolutePath().toString());
}
String bordersIds = storage.getValue().get("ids");
if (StringUtils.isNotBlank(bordersIds)) {
storage.getValue().put("ids", Paths.get(bordersIds).toAbsolutePath().toString());
}
String openBorders = storage.getValue().get("openborders");
if (StringUtils.isNotBlank(openBorders)) {
storage.getValue().put("openborders", Paths.get(openBorders).toAbsolutePath().toString());
}
}
if (storage.getKey().equals("GreenIndex") || storage.getKey().equals("NoiseIndex") || storage.getKey().equals("csv") || storage.getKey().equals("ShadowIndex")) {
// replace filepath
String indexFilePath = storage.getValue().get("filepath");
if (indexFilePath != null) {
storage.getValue().put("filepath", Paths.get(indexFilePath).toAbsolutePath().toString());
}
}
}
this.extStorages = extStorages;
}
public double getMaximumDistance() {
return maximumDistance != null ? maximumDistance : 0;
}
public void setMaximumDistance(double maximumDistance) {
this.maximumDistance = maximumDistance;
}
public double getMaximumDistanceDynamicWeights() {
return maximumDistanceDynamicWeights != null ? maximumDistanceDynamicWeights : 0;
}
public void setMaximumDistanceDynamicWeights(double maximumDistanceDynamicWeights) {
this.maximumDistanceDynamicWeights = maximumDistanceDynamicWeights;
}
public double getMaximumDistanceAvoidAreas() {
return maximumDistanceAvoidAreas != null ? maximumDistanceAvoidAreas : 0;
}
public void setMaximumDistanceAvoidAreas(double maximumDistanceAvoidAreas) {
this.maximumDistanceAvoidAreas = maximumDistanceAvoidAreas;
}
public double getMaximumDistanceAlternativeRoutes() {
return maximumDistanceAlternativeRoutes != null ? maximumDistanceAlternativeRoutes : 0;
}
public void setMaximumDistanceAlternativeRoutes(double maximumDistanceAlternativeRoutes) {
this.maximumDistanceAlternativeRoutes = maximumDistanceAlternativeRoutes;
}
public double getMaximumDistanceRoundTripRoutes() {
return maximumDistanceRoundTripRoutes != null ? maximumDistanceRoundTripRoutes : 0;
}
public void setMaximumDistanceRoundTripRoutes(double maximumDistanceRoundTripRoutes) {
this.maximumDistanceRoundTripRoutes = maximumDistanceRoundTripRoutes;
}
public double getMaximumSpeedLowerBound() {
return maximumSpeedLowerBound != null ? maximumSpeedLowerBound : 0;
}
public void setMaximumSpeedLowerBound(Double maximumSpeedLowerBound) {
this.maximumSpeedLowerBound = maximumSpeedLowerBound;
}
public int getMaximumWayPoints() {
return maximumWayPoints != null ? maximumWayPoints : 0;
}
public void setMaximumWayPoints(int maximumWayPoints) {
this.maximumWayPoints = maximumWayPoints;
}
public int getMaximumSnappingRadius() {
return maximumSnappingRadius != null ? maximumSnappingRadius : 0;
}
public void setMaximumSnappingRadius(int maximumSnappingRadius) {
this.maximumSnappingRadius = maximumSnappingRadius;
}
public int getMaximumVisitedNodes() {
return maximumVisitedNodes != null ? maximumVisitedNodes : 0;
}
public void setMaximumVisitedNodes(Integer maximumVisitedNodes) {
this.maximumVisitedNodes = maximumVisitedNodes;
}
public int getEncoderFlagsSize() {
return encoderFlagsSize != null ? encoderFlagsSize : 0;
}
public void setEncoderFlagsSize(Integer encoderFlagsSize) {
this.encoderFlagsSize = encoderFlagsSize;
}
public Integer getLocationIndexResolution() {
return locationIndexResolution != null ? locationIndexResolution : 0;
}
public void setLocationIndexResolution(Integer locationIndexResolution) {
this.locationIndexResolution = locationIndexResolution;
}
public Integer getLocationIndexSearchIterations() {
return locationIndexSearchIterations != null ? locationIndexSearchIterations : 0;
}
public void setLocationIndexSearchIterations(Integer locationIndexSearchIterations) {
this.locationIndexSearchIterations = locationIndexSearchIterations;
}
public boolean getForceTurnCosts() {
return forceTurnCosts != null && forceTurnCosts;
}
public void setForceTurnCosts(Boolean forceTurnCosts) {
this.forceTurnCosts = forceTurnCosts;
}
public String getGtfsFile() {
return gtfsFile != null ? gtfsFile : "";
}
public void setGtfsFile(String gtfsFile) {
if (StringUtils.isNotBlank(gtfsFile))
this.gtfsFile = Paths.get(gtfsFile).toAbsolutePath().toString();
else this.gtfsFile = gtfsFile;
}
// For later use when refactoring RoutingManagerConfiguration
// public static class PreparationProperties {
// private int<SUF>
// private int minOneWayNetworkSize;
//
// public MethodsProperties getMethods() {
// return methods;
// }
//
// public PreparationProperties setMethods(MethodsProperties methods) {
// this.methods = methods;
// return this;
// }
//
// private MethodsProperties methods;
//
// public int getMinNetworkSize() {
// return minNetworkSize;
// }
//
// public void setMinNetworkSize(int minNetworkSize) {
// this.minNetworkSize = minNetworkSize;
// }
//
// public int getMinOneWayNetworkSize() {
// return minOneWayNetworkSize;
// }
//
// public void setMinOneWayNetworkSize(int minOneWayNetworkSize) {
// this.minOneWayNetworkSize = minOneWayNetworkSize;
// }
// }
//
// public static class MethodsProperties {
// private CHProperties ch;
// private LMProperties lm;
// private CoreProperties core;
// private FastIsochroneProperties fastisochrones;
//
// public CHProperties getCh() {
// return ch;
// }
//
// public void setCh(CHProperties ch) {
// this.ch = ch;
// }
//
// public LMProperties getLm() {
// return lm;
// }
//
// public void setLm(LMProperties lm) {
// this.lm = lm;
// }
//
// public CoreProperties getCore() {
// return core;
// }
//
// public void setCore(CoreProperties core) {
// this.core = core;
// }
//
// public FastIsochroneProperties getFastisochrones() {
// return fastisochrones;
// }
//
// public void setFastisochrones(FastIsochroneProperties fastisochrones) {
// this.fastisochrones = fastisochrones;
// }
//
// }
//
// public static class CHProperties {
// //TBD
// }
//
// public static class LMProperties {
// //TBD
// }
//
// public static class CoreProperties {
// //TBD
// }
//
// public static class FastIsochroneProperties {
// private boolean enabled;
// private int threads;
// private String weightings;
// private int maxcellnodes;
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public int getThreads() {
// return threads;
// }
//
// public void setThreads(int threads) {
// this.threads = threads;
// }
//
// public String getWeightings() {
// return weightings;
// }
//
// public void setWeightings(String weightings) {
// this.weightings = weightings;
// }
//
// public int getMaxcellnodes() {
// return maxcellnodes;
// }
//
// public void setMaxcellnodes(int maxcellnodes) {
// this.maxcellnodes = maxcellnodes;
// }
// }
//
// public static class ExecutionProperties {
// private Map<String, Map<String, String>> methods;
//
// public Map<String, Map<String, String>> getMethods() {
// return methods;
// }
//
// public void setMethods(Map<String, Map<String, String>> methods) {
// this.methods = methods;
// }
// }
}
}
|
35497_8 | package model;
import java.util.ArrayList;
import model.klas.Klas;
import model.persoon.Docent;
import model.persoon.Student;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
/**
* De constructor maakt een set met standaard-data aan. Deze data
* moet nog uitgebreidt worden met rooster gegevens die uit een bestand worden
* ingelezen, maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan dit nog veel
* verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op
* dit moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord)
* Docent getDocent(String gebruikersnaam)
* Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen,
* dat kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>();
// Inladen klassen
vulKlassen(deKlassen);
// Inladen studenten in klassen
vulStudenten(deStudenten, deKlassen);
// Inladen docenten
vulDocenten(deDocenten);
} //Einde Pris constructor
//deze method is static onderdeel van PrIS omdat hij als hulp methode
//in veel controllers gebruikt wordt
//een standaardDatumString heeft formaat YYYY-MM-DD
public static Calendar standaardDatumStringToCal(String pStadaardDatumString) {
Calendar lCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
lCal.setTime(sdf.parse(pStadaardDatumString));
} catch (ParseException e) {
e.printStackTrace();
lCal=null;
}
return lCal;
}
//deze method is static onderdeel van PrIS omdat hij als hulp methode
//in veel controllers gebruikt wordt
//een standaardDatumString heeft formaat YYYY-MM-DD
public static String calToStandaardDatumString (Calendar pCalendar) {
int lJaar = pCalendar.get(Calendar.YEAR);
int lMaand= pCalendar.get(Calendar.MONTH) + 1;
int lDag = pCalendar.get(Calendar.DAY_OF_MONTH);
String lMaandStr = Integer.toString(lMaand);
if (lMaandStr.length() == 1) {
lMaandStr = "0"+ lMaandStr;
}
String lDagStr = Integer.toString(lDag);
if (lDagStr.length() == 1) {
lDagStr = "0"+ lDagStr;
}
String lString =
Integer.toString(lJaar) + "-" +
lMaandStr + "-" +
lDagStr;
return lString;
}
public Docent getDocent(String gebruikersnaam) {
Docent resultaat = null;
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
resultaat = d;
break;
}
}
return resultaat;
}
public Klas getKlasVanStudent(Student pStudent) {
//used
for (Klas lKlas : deKlassen) {
if (lKlas.bevatStudent(pStudent)){
return (lKlas);
}
}
return null;
}
public Student getStudent(String pGebruikersnaam) {
// used
Student lGevondenStudent = null;
for (Student lStudent : deStudenten) {
if (lStudent.getGebruikersnaam().equals(pGebruikersnaam)) {
lGevondenStudent = lStudent;
break;
}
}
return lGevondenStudent;
}
public Student getStudent(int pStudentNummer) {
// used
Student lGevondenStudent = null;
for (Student lStudent : deStudenten) {
if (lStudent.getStudentNummer()==(pStudentNummer)) {
lGevondenStudent = lStudent;
break;
}
}
return lGevondenStudent;
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
if (d.komtWachtwoordOvereen(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersnaam().equals(gebruikersnaam)) {
if (s.komtWachtwoordOvereen(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
private void vulDocenten(ArrayList<Docent> pDocenten) {
String csvFile = "././CSV/docenten.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = element[0].toLowerCase();
String voornaam = element[1];
String tussenvoegsel = element[2];
String achternaam = element[3];
pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1));
//System.out.println(gebruikersnaam);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void vulKlassen(ArrayList<Klas> pKlassen) {
//TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt
//V1A is de naam van de klas die ook als file naam voor de studenten van die klas wordt gebruikt
Klas k1 = new Klas("TICT-SIE-V1A", "V1A");
Klas k2 = new Klas("TICT-SIE-V1B", "V1B");
Klas k3 = new Klas("TICT-SIE-V1C", "V1C");
Klas k4 = new Klas("TICT-SIE-V1D", "V1D");
Klas k5 = new Klas("TICT-SIE-V1E", "V1E");
Klas k6 = new Klas("TICT-SIE-V1F", "V1F");
pKlassen.add(k1);
pKlassen.add(k2);
pKlassen.add(k3);
pKlassen.add(k4);
pKlassen.add(k5);
pKlassen.add(k6);
}
private void vulStudenten(
ArrayList<Student> pStudenten,
ArrayList<Klas> pKlassen) {
Student lStudent;
for (Klas k : pKlassen) {
String csvFile = "././CSV/" + k.getNaam() + ".csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl").toLowerCase();
// verwijder spaties tussen dubbele voornamen en tussen bv van der
gebruikersnaam = gebruikersnaam.replace(" ","");
String lStudentNrString = element[0];
int lStudentNr = Integer.parseInt(lStudentNrString);
lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr); //Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam
pStudenten.add(lStudent);
k.voegStudentToe(lStudent);
//System.out.println(gebruikersnaam);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
| GP2017-Absentie/Java_back-end | school_java/model/PrIS.java | 2,968 | //een standaardDatumString heeft formaat YYYY-MM-DD
| line_comment | nl | package model;
import java.util.ArrayList;
import model.klas.Klas;
import model.persoon.Docent;
import model.persoon.Student;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
/**
* De constructor maakt een set met standaard-data aan. Deze data
* moet nog uitgebreidt worden met rooster gegevens die uit een bestand worden
* ingelezen, maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan dit nog veel
* verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op
* dit moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord)
* Docent getDocent(String gebruikersnaam)
* Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen,
* dat kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>();
// Inladen klassen
vulKlassen(deKlassen);
// Inladen studenten in klassen
vulStudenten(deStudenten, deKlassen);
// Inladen docenten
vulDocenten(deDocenten);
} //Einde Pris constructor
//deze method is static onderdeel van PrIS omdat hij als hulp methode
//in veel controllers gebruikt wordt
//een standaardDatumString heeft formaat YYYY-MM-DD
public static Calendar standaardDatumStringToCal(String pStadaardDatumString) {
Calendar lCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
lCal.setTime(sdf.parse(pStadaardDatumString));
} catch (ParseException e) {
e.printStackTrace();
lCal=null;
}
return lCal;
}
//deze method is static onderdeel van PrIS omdat hij als hulp methode
//in veel controllers gebruikt wordt
//een standaardDatumString<SUF>
public static String calToStandaardDatumString (Calendar pCalendar) {
int lJaar = pCalendar.get(Calendar.YEAR);
int lMaand= pCalendar.get(Calendar.MONTH) + 1;
int lDag = pCalendar.get(Calendar.DAY_OF_MONTH);
String lMaandStr = Integer.toString(lMaand);
if (lMaandStr.length() == 1) {
lMaandStr = "0"+ lMaandStr;
}
String lDagStr = Integer.toString(lDag);
if (lDagStr.length() == 1) {
lDagStr = "0"+ lDagStr;
}
String lString =
Integer.toString(lJaar) + "-" +
lMaandStr + "-" +
lDagStr;
return lString;
}
public Docent getDocent(String gebruikersnaam) {
Docent resultaat = null;
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
resultaat = d;
break;
}
}
return resultaat;
}
public Klas getKlasVanStudent(Student pStudent) {
//used
for (Klas lKlas : deKlassen) {
if (lKlas.bevatStudent(pStudent)){
return (lKlas);
}
}
return null;
}
public Student getStudent(String pGebruikersnaam) {
// used
Student lGevondenStudent = null;
for (Student lStudent : deStudenten) {
if (lStudent.getGebruikersnaam().equals(pGebruikersnaam)) {
lGevondenStudent = lStudent;
break;
}
}
return lGevondenStudent;
}
public Student getStudent(int pStudentNummer) {
// used
Student lGevondenStudent = null;
for (Student lStudent : deStudenten) {
if (lStudent.getStudentNummer()==(pStudentNummer)) {
lGevondenStudent = lStudent;
break;
}
}
return lGevondenStudent;
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
if (d.komtWachtwoordOvereen(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersnaam().equals(gebruikersnaam)) {
if (s.komtWachtwoordOvereen(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
private void vulDocenten(ArrayList<Docent> pDocenten) {
String csvFile = "././CSV/docenten.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = element[0].toLowerCase();
String voornaam = element[1];
String tussenvoegsel = element[2];
String achternaam = element[3];
pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1));
//System.out.println(gebruikersnaam);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void vulKlassen(ArrayList<Klas> pKlassen) {
//TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt
//V1A is de naam van de klas die ook als file naam voor de studenten van die klas wordt gebruikt
Klas k1 = new Klas("TICT-SIE-V1A", "V1A");
Klas k2 = new Klas("TICT-SIE-V1B", "V1B");
Klas k3 = new Klas("TICT-SIE-V1C", "V1C");
Klas k4 = new Klas("TICT-SIE-V1D", "V1D");
Klas k5 = new Klas("TICT-SIE-V1E", "V1E");
Klas k6 = new Klas("TICT-SIE-V1F", "V1F");
pKlassen.add(k1);
pKlassen.add(k2);
pKlassen.add(k3);
pKlassen.add(k4);
pKlassen.add(k5);
pKlassen.add(k6);
}
private void vulStudenten(
ArrayList<Student> pStudenten,
ArrayList<Klas> pKlassen) {
Student lStudent;
for (Klas k : pKlassen) {
String csvFile = "././CSV/" + k.getNaam() + ".csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl").toLowerCase();
// verwijder spaties tussen dubbele voornamen en tussen bv van der
gebruikersnaam = gebruikersnaam.replace(" ","");
String lStudentNrString = element[0];
int lStudentNr = Integer.parseInt(lStudentNrString);
lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr); //Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam
pStudenten.add(lStudent);
k.voegStudentToe(lStudent);
//System.out.println(gebruikersnaam);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
|
77274_2 | package com.jypec.wavelet.liftingTransforms;
import com.jypec.util.arrays.ArrayTransforms;
import com.jypec.wavelet.Wavelet;
import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform;
/**
* CDF 9 7 adaptation from:
* https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform
*
* @author Daniel
*
*/
public class LiftingCdf97WaveletTransform implements Wavelet {
private static final float COEFF_PREDICT_1 = -1.586134342f;
private static final float COEFF_PREDICT_2 = 0.8829110762f;
private static final float COEFF_UPDATE_1= -0.05298011854f;
private static final float COEFF_UPDATE_2 = 0.4435068522f;
private static final float COEFF_SCALE = 1/1.149604398f;
/**
* Adds to each odd indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array <br>
* E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br>
* {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the prediction coefficient
*/
private void predict(float[] s, int n, float COEFF) {
// Predict inner values
for (int i = 1; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 == 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array
* E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3}
* {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the updating coefficient
*/
private void update(float[]s, int n, float COEFF) {
// Update first coeff
if (n > 1) {
s[0] += 2*COEFF*s[1];
}
// Update inner values
for (int i = 2; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 != 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF
* @param s the signal to be scaled
* @param n the length of s
* @param COEFF the coefficient applied
*/
private void scale(float[] s, int n, float COEFF) {
for (int i = 0; i < n; i++) {
if (i%2 == 1) {
s[i] *= COEFF;
} else {
s[i] /= COEFF;
}
}
}
@Override
public void forwardTransform(float[] s, int n) {
//predict and update
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
//scale values
scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE);
//pack values (low freq first, high freq last)
ArrayTransforms.pack(s, n);
}
@Override
public void reverseTransform(float[] s, int n) {
//unpack values
ArrayTransforms.unpack(s, n);
//unscale values
scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE);
//unpredict and unupdate
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
}
@Override
public float maxResult(float min, float max) {
return new KernelCdf97WaveletTransform().maxResult(min, max);
}
@Override
public float minResult(float min, float max) {
return new KernelCdf97WaveletTransform().minResult(min, max);
}
}
| GRSEB9S/Jypec | src/com/jypec/wavelet/liftingTransforms/LiftingCdf97WaveletTransform.java | 1,512 | // Predict inner values | line_comment | nl | package com.jypec.wavelet.liftingTransforms;
import com.jypec.util.arrays.ArrayTransforms;
import com.jypec.wavelet.Wavelet;
import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform;
/**
* CDF 9 7 adaptation from:
* https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform
*
* @author Daniel
*
*/
public class LiftingCdf97WaveletTransform implements Wavelet {
private static final float COEFF_PREDICT_1 = -1.586134342f;
private static final float COEFF_PREDICT_2 = 0.8829110762f;
private static final float COEFF_UPDATE_1= -0.05298011854f;
private static final float COEFF_UPDATE_2 = 0.4435068522f;
private static final float COEFF_SCALE = 1/1.149604398f;
/**
* Adds to each odd indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array <br>
* E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br>
* {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the prediction coefficient
*/
private void predict(float[] s, int n, float COEFF) {
// Predict inner<SUF>
for (int i = 1; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 == 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array
* E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3}
* {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the updating coefficient
*/
private void update(float[]s, int n, float COEFF) {
// Update first coeff
if (n > 1) {
s[0] += 2*COEFF*s[1];
}
// Update inner values
for (int i = 2; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 != 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF
* @param s the signal to be scaled
* @param n the length of s
* @param COEFF the coefficient applied
*/
private void scale(float[] s, int n, float COEFF) {
for (int i = 0; i < n; i++) {
if (i%2 == 1) {
s[i] *= COEFF;
} else {
s[i] /= COEFF;
}
}
}
@Override
public void forwardTransform(float[] s, int n) {
//predict and update
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
//scale values
scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE);
//pack values (low freq first, high freq last)
ArrayTransforms.pack(s, n);
}
@Override
public void reverseTransform(float[] s, int n) {
//unpack values
ArrayTransforms.unpack(s, n);
//unscale values
scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE);
//unpredict and unupdate
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
}
@Override
public float maxResult(float min, float max) {
return new KernelCdf97WaveletTransform().maxResult(min, max);
}
@Override
public float minResult(float min, float max) {
return new KernelCdf97WaveletTransform().minResult(min, max);
}
}
|
62222_1 | package control;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import control.PersonaleDisponibileServlet.ComponenteComparator;
import model.bean.ComponenteDellaSquadraBean;
import model.bean.VigileDelFuocoBean;
import model.dao.ComponenteDellaSquadraDao;
import model.dao.VigileDelFuocoDao;
import util.GiornoLavorativo;
import util.Util;
/**
* Servlet implementation class PersonaleDisponibileAJAX
*/
@WebServlet("/PersonaleDisponibileAJAX")
public class PersonaleDisponibileAJAX extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PersonaleDisponibileAJAX() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Util.isCapoTurno(request);
//Prendo l'email del VF da sostituire, il ruolo e il tipo di squadra
String email=request.getParameter("email");
String ruolo= request.getParameter("mansione");
String tipo = request.getParameter("tiposquadra");
int tp= Integer.parseInt(tipo);
HttpSession session = request.getSession();
HashMap<VigileDelFuocoBean, String> squadra=null;
Date data = null;
Date other= null;
if(tp==1) {
squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraDiurno");
data = Date.valueOf( request.getParameter("dataModifica"));
other= Date.valueOf( request.getParameter("altroturno"));
} else {
if(tp==2) {
squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraNotturno");
data = Date.valueOf( request.getParameter("dataModifica"));
other= Date.valueOf( request.getParameter("altroturno"));
}else {
squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadra");
data = Date.valueOf( request.getParameter("dataModifica"));
}
}
ArrayList<VigileDelFuocoBean> vigili=VigileDelFuocoDao.getDisponibili(data);
//Confronto se nell'ArrayList dei vigili ci sono quelli gi� inseriti nelle squadre
ArrayList<VigileDelFuocoBean> nuovoelenco = new ArrayList<VigileDelFuocoBean>();
for(int i=0; i<vigili.size();i++) {
boolean trovato= false;
Iterator it = squadra.entrySet().iterator();
while (it.hasNext()) {
Map.Entry coppia = (Map.Entry) it.next();
VigileDelFuocoBean membro = (VigileDelFuocoBean) coppia.getKey();
//confronto il membro nella squadra con tutta la lista di vigili disponibili
if(membro.getEmail().equalsIgnoreCase(vigili.get(i).getEmail())) {
trovato = true;
}
if(trovato) break;
}
//Se il vigile non � presente nell'HashMap lo inserisco nel nuovo arrayList, controllando se � dello stesso ruolo del VF rimosso
if(trovato==false) {
if(ruolo!=null) {
if(vigili.get(i).getMansione().equalsIgnoreCase(ruolo)) {
nuovoelenco.add(vigili.get(i));
}
}
}
}
request.setAttribute("tiposquadra",tipo);
request.setAttribute("vigili", nuovoelenco);
request.setAttribute("email", email);
request.setAttribute("dataModifica", data);
request.setAttribute("altroturno", other);
request.getRequestDispatcher("JSP/PersonaleDisponibileAJAXJSP.jsp").forward(request, response);
}
}
| GSSDevelopmentTeam/ScheduFIRE | ScheduFIRE/src/control/PersonaleDisponibileAJAX.java | 1,341 | /**
* @see HttpServlet#HttpServlet()
*/ | block_comment | nl | package control;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import control.PersonaleDisponibileServlet.ComponenteComparator;
import model.bean.ComponenteDellaSquadraBean;
import model.bean.VigileDelFuocoBean;
import model.dao.ComponenteDellaSquadraDao;
import model.dao.VigileDelFuocoDao;
import util.GiornoLavorativo;
import util.Util;
/**
* Servlet implementation class PersonaleDisponibileAJAX
*/
@WebServlet("/PersonaleDisponibileAJAX")
public class PersonaleDisponibileAJAX extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
<SUF>*/
public PersonaleDisponibileAJAX() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Util.isCapoTurno(request);
//Prendo l'email del VF da sostituire, il ruolo e il tipo di squadra
String email=request.getParameter("email");
String ruolo= request.getParameter("mansione");
String tipo = request.getParameter("tiposquadra");
int tp= Integer.parseInt(tipo);
HttpSession session = request.getSession();
HashMap<VigileDelFuocoBean, String> squadra=null;
Date data = null;
Date other= null;
if(tp==1) {
squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraDiurno");
data = Date.valueOf( request.getParameter("dataModifica"));
other= Date.valueOf( request.getParameter("altroturno"));
} else {
if(tp==2) {
squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraNotturno");
data = Date.valueOf( request.getParameter("dataModifica"));
other= Date.valueOf( request.getParameter("altroturno"));
}else {
squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadra");
data = Date.valueOf( request.getParameter("dataModifica"));
}
}
ArrayList<VigileDelFuocoBean> vigili=VigileDelFuocoDao.getDisponibili(data);
//Confronto se nell'ArrayList dei vigili ci sono quelli gi� inseriti nelle squadre
ArrayList<VigileDelFuocoBean> nuovoelenco = new ArrayList<VigileDelFuocoBean>();
for(int i=0; i<vigili.size();i++) {
boolean trovato= false;
Iterator it = squadra.entrySet().iterator();
while (it.hasNext()) {
Map.Entry coppia = (Map.Entry) it.next();
VigileDelFuocoBean membro = (VigileDelFuocoBean) coppia.getKey();
//confronto il membro nella squadra con tutta la lista di vigili disponibili
if(membro.getEmail().equalsIgnoreCase(vigili.get(i).getEmail())) {
trovato = true;
}
if(trovato) break;
}
//Se il vigile non � presente nell'HashMap lo inserisco nel nuovo arrayList, controllando se � dello stesso ruolo del VF rimosso
if(trovato==false) {
if(ruolo!=null) {
if(vigili.get(i).getMansione().equalsIgnoreCase(ruolo)) {
nuovoelenco.add(vigili.get(i));
}
}
}
}
request.setAttribute("tiposquadra",tipo);
request.setAttribute("vigili", nuovoelenco);
request.setAttribute("email", email);
request.setAttribute("dataModifica", data);
request.setAttribute("altroturno", other);
request.getRequestDispatcher("JSP/PersonaleDisponibileAJAXJSP.jsp").forward(request, response);
}
}
|
11601_0 | package agent;
import lejos.nxt.NXTRegulatedMotor;
import robotica.SimState;
import standard.Agent;
public class Customer extends Agent
{
private long previousTime;
private long currentTime;
private long timeToWait = 0;
private CustomerBehavior behavior;
private boolean rotating = false;
private NXTRegulatedMotor motor;
public Customer(NXTRegulatedMotor motor, String name)
{
super(name, new SimState("IDLE"));
this.behavior = new CustomerBehavior(4);
resetTime();
this.motor = motor;
motor.resetTachoCount();
}
public void reset()
{
resetTime();
resetRotation();
this.setState(new SimState("IDLE"));
this.setChanged();
}
@Override
public void update()
{
switch (currentState().name())
{
case "IDLE":
idle();
break;
case "WBESTELLEN":
wBestellen();
break;
case "WETEN":
wEten();
break;
case "ETEN":
eten();
break;
case "WBETALEN":
wBetalen();
break;
}
this.updateState();
notifyObservers();
}
private long timePast()
{
currentTime = System.currentTimeMillis();
long timePast = currentTime - previousTime;
previousTime = currentTime;
return timePast;
}
private boolean resetTimeToWait()
{
if (timeToWait <= 0)
{
timeToWait = 0;
return true;
} else
return false;
}
private void resetTime()
{
currentTime = System.currentTimeMillis();
previousTime = currentTime;
timeToWait = 0;
}
private void idle()
{
resetRotation();
if (resetTimeToWait())
timeToWait = behavior.idle();
timeToWait -= timePast();
System.out.println("IDLE");
motor.setSpeed(720);
motor.rotateTo(0);
if (timeToWait < 0)
{
this.setState(new SimState("WBESTELLEN"));
setChanged();
resetTime();
}
}
private void wBestellen()
{
resetRotation();
motor.setSpeed(720);
motor.rotateTo(90);
resetTime();
}
private void wEten()
{
resetRotation();
motor.setSpeed(720);
motor.rotateTo(180);
resetTime();
}
private void eten()
{
if (resetTimeToWait())
timeToWait = behavior.eten();
timeToWait -= timePast();
System.out.println("ETEN");
if (timeToWait < 0)
{
this.setState(new SimState("WBETALEN"));
setChanged();
resetTime();
}
rotating = true;
motor.setSpeed(300);
motor.forward();
}
private void wBetalen()
{
resetRotation();
motor.setSpeed(720);
motor.setSpeed(720);
motor.rotateTo(270);
}
private void resetRotation()
{
if (rotating)
{
int lol = motor.getTachoCount() / 360;
motor.rotateTo(lol * 360);
motor.resetTachoCount();
rotating = false;
}
}
public void processCompletedTask(String task)
{
System.out.println(task);
switch (task)
{
case "BESTELLING_OPGENOMEN":
if (this.currentState().name().equals("WBESTELLEN"))
{
this.setState(new SimState("WETEN"));
this.setChanged();
}
break;
case "ETEN_BEZORGD":
if (this.currentState().name().equals("WETEN"))
{
this.setState(new SimState("ETEN"));
this.setChanged();
}
break;
case "BETALING_AFGEROND":
if (this.currentState().name().equals("WBETALEN"))
{
motor.rotateTo(0);
this.setState(new SimState("STOP"));
this.setChanged();
}
break;
}
}
}
/*
* 5 states:
*
* -idle"IDLE" Niks boven. -Wachten op bestellen: "WBESTELLEN" Rood boven.
* -Wachten op eten: "WETEN" Blauw boven. -Eten: "ETEN" Motor draait rond.
* -Betalen: "WBETALEN" Zwart boven.
*/ | GSamuel/Robotica-2-2013 | Robotica 2 NXT/src/agent/Customer.java | 1,308 | /*
* 5 states:
*
* -idle"IDLE" Niks boven. -Wachten op bestellen: "WBESTELLEN" Rood boven.
* -Wachten op eten: "WETEN" Blauw boven. -Eten: "ETEN" Motor draait rond.
* -Betalen: "WBETALEN" Zwart boven.
*/ | block_comment | nl | package agent;
import lejos.nxt.NXTRegulatedMotor;
import robotica.SimState;
import standard.Agent;
public class Customer extends Agent
{
private long previousTime;
private long currentTime;
private long timeToWait = 0;
private CustomerBehavior behavior;
private boolean rotating = false;
private NXTRegulatedMotor motor;
public Customer(NXTRegulatedMotor motor, String name)
{
super(name, new SimState("IDLE"));
this.behavior = new CustomerBehavior(4);
resetTime();
this.motor = motor;
motor.resetTachoCount();
}
public void reset()
{
resetTime();
resetRotation();
this.setState(new SimState("IDLE"));
this.setChanged();
}
@Override
public void update()
{
switch (currentState().name())
{
case "IDLE":
idle();
break;
case "WBESTELLEN":
wBestellen();
break;
case "WETEN":
wEten();
break;
case "ETEN":
eten();
break;
case "WBETALEN":
wBetalen();
break;
}
this.updateState();
notifyObservers();
}
private long timePast()
{
currentTime = System.currentTimeMillis();
long timePast = currentTime - previousTime;
previousTime = currentTime;
return timePast;
}
private boolean resetTimeToWait()
{
if (timeToWait <= 0)
{
timeToWait = 0;
return true;
} else
return false;
}
private void resetTime()
{
currentTime = System.currentTimeMillis();
previousTime = currentTime;
timeToWait = 0;
}
private void idle()
{
resetRotation();
if (resetTimeToWait())
timeToWait = behavior.idle();
timeToWait -= timePast();
System.out.println("IDLE");
motor.setSpeed(720);
motor.rotateTo(0);
if (timeToWait < 0)
{
this.setState(new SimState("WBESTELLEN"));
setChanged();
resetTime();
}
}
private void wBestellen()
{
resetRotation();
motor.setSpeed(720);
motor.rotateTo(90);
resetTime();
}
private void wEten()
{
resetRotation();
motor.setSpeed(720);
motor.rotateTo(180);
resetTime();
}
private void eten()
{
if (resetTimeToWait())
timeToWait = behavior.eten();
timeToWait -= timePast();
System.out.println("ETEN");
if (timeToWait < 0)
{
this.setState(new SimState("WBETALEN"));
setChanged();
resetTime();
}
rotating = true;
motor.setSpeed(300);
motor.forward();
}
private void wBetalen()
{
resetRotation();
motor.setSpeed(720);
motor.setSpeed(720);
motor.rotateTo(270);
}
private void resetRotation()
{
if (rotating)
{
int lol = motor.getTachoCount() / 360;
motor.rotateTo(lol * 360);
motor.resetTachoCount();
rotating = false;
}
}
public void processCompletedTask(String task)
{
System.out.println(task);
switch (task)
{
case "BESTELLING_OPGENOMEN":
if (this.currentState().name().equals("WBESTELLEN"))
{
this.setState(new SimState("WETEN"));
this.setChanged();
}
break;
case "ETEN_BEZORGD":
if (this.currentState().name().equals("WETEN"))
{
this.setState(new SimState("ETEN"));
this.setChanged();
}
break;
case "BETALING_AFGEROND":
if (this.currentState().name().equals("WBETALEN"))
{
motor.rotateTo(0);
this.setState(new SimState("STOP"));
this.setChanged();
}
break;
}
}
}
/*
* 5 states:
<SUF>*/ |
67390_0 | package main;
import org.opencv.core.Core;
import org.opencv.highgui.VideoCapture;
import com.robotica.nxt.remotecontrol.Command;
import com.robotica.nxt.remotecontrol.CommandCommunicator;
import com.robotica.nxt.remotecontrol.NXTCommand;
import com.robotica.pc.keyboardInput.KeyboardInput;
import com.robotica.pc.model.World;
import com.robotica.pc.remotecontrol.PCConnector;
public class PacmanMain
{
public static void main(String[] args)
{
/*
in herhaling:
uitlezen camera ->
bouw model met behulp van camera data ->
gebruik model in de AI om een pad te generen ->
vertaal pad naar NXT Commands ->
stuur commands naar de juiste brick ->
pas settings van robots aan afhankelijk van feedback
weergeven:
doolhof met up to date posities van entities.
webcam beelden met evt. filters.
entities met de bijbehorende bewegings vectoren/correcties.
see which entities are connected.
*/
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);//Library die we nodig hebben voor opencv etc.
World world = new World(); // dataModel, all needed data should be in here.
world.setCamera(new VideoCapture(3));
//PacmanWindow pacmanWindow = new PacmanWindow(); // all gui elements should be in here
//connect with devices:
PCConnector connector1 = new PCConnector("NXT_9_1");
PCConnector connector2 = new PCConnector("Parasect");
connector1.connectWithBluetooth();
connector2.connectWithBluetooth();
CommandCommunicator comm1 = new CommandCommunicator(connector1);
CommandCommunicator comm2 = new CommandCommunicator(connector2);
//read commands from user input and send commands to the bricks
while (connector1.isConnected() && connector2.isConnected())
{
Command command = KeyboardInput.getCommand();
comm1.sendCommand(command);
comm2.sendCommand(command);
if (command.getNXTCommand() == NXTCommand.EXIT)
break;
}
System.out.println("program finished");
}
}
| GSamuel/Robotica-2014-2015-Pacman | Robotica_2014_Pacman_PC/src/main/PacmanMain.java | 641 | /*
in herhaling:
uitlezen camera ->
bouw model met behulp van camera data ->
gebruik model in de AI om een pad te generen ->
vertaal pad naar NXT Commands ->
stuur commands naar de juiste brick ->
pas settings van robots aan afhankelijk van feedback
weergeven:
doolhof met up to date posities van entities.
webcam beelden met evt. filters.
entities met de bijbehorende bewegings vectoren/correcties.
see which entities are connected.
*/ | block_comment | nl | package main;
import org.opencv.core.Core;
import org.opencv.highgui.VideoCapture;
import com.robotica.nxt.remotecontrol.Command;
import com.robotica.nxt.remotecontrol.CommandCommunicator;
import com.robotica.nxt.remotecontrol.NXTCommand;
import com.robotica.pc.keyboardInput.KeyboardInput;
import com.robotica.pc.model.World;
import com.robotica.pc.remotecontrol.PCConnector;
public class PacmanMain
{
public static void main(String[] args)
{
/*
in herhaling:
<SUF>*/
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);//Library die we nodig hebben voor opencv etc.
World world = new World(); // dataModel, all needed data should be in here.
world.setCamera(new VideoCapture(3));
//PacmanWindow pacmanWindow = new PacmanWindow(); // all gui elements should be in here
//connect with devices:
PCConnector connector1 = new PCConnector("NXT_9_1");
PCConnector connector2 = new PCConnector("Parasect");
connector1.connectWithBluetooth();
connector2.connectWithBluetooth();
CommandCommunicator comm1 = new CommandCommunicator(connector1);
CommandCommunicator comm2 = new CommandCommunicator(connector2);
//read commands from user input and send commands to the bricks
while (connector1.isConnected() && connector2.isConnected())
{
Command command = KeyboardInput.getCommand();
comm1.sendCommand(command);
comm2.sendCommand(command);
if (command.getNXTCommand() == NXTCommand.EXIT)
break;
}
System.out.println("program finished");
}
}
|
4905_7 | /*
* This file is subject to the license.txt file in the main folder
* of this project.
*/
package stanhebben.zenscript.parser;
import java.util.Arrays;
/**
* HashSet implementation which is optimized for integer values.
*
* @author Stan Hebben
*/
public class HashSetI {
private int[] values;
private int[] next;
private int mask;
private int size;
/**
* Creates a new HashSet for integer values.
*/
public HashSetI() {
values = new int[16];
next = new int[16];
mask = 15;
size = 0;
for (int i = 0; i < values.length; i++) {
values[i] = Integer.MIN_VALUE;
}
}
public HashSetI(HashSetI original) {
values = Arrays.copyOf(original.values, original.values.length);
next = Arrays.copyOf(original.next, original.next.length);
mask = original.mask;
size = original.size;
}
/**
* Adds the specified value to this HashSet. If this value is already in
* this HashSet, nothing happens.
*
* @param value value to be added to the HashSet
*/
public void add(int value) {
if (size > (values.length * 3) >> 2) {
expand();
}
int index = value & mask;
if (values[index] == Integer.MIN_VALUE) {
values[index] = value;
} else {
if (values[index] == value) {
return;
}
while (next[index] != 0) {
index = next[index] - 1;
if (values[index] == value) {
return;
}
}
int ref = index;
while (values[index] != Integer.MIN_VALUE) {
index++;
if (index == values.length)
index = 0;
}
next[ref] = index + 1;
values[index] = value;
}
size++;
}
/**
* Checks if this HashSet contains the specified value.
*
* @param value integer value to add
* @return true if this HashSet contains the specified value
*/
public boolean contains(int value) {
int index = value & mask;
while (values[index] != value) {
if (next[index] == 0) {
return false;
}
index = next[index] - 1;
}
return true;
}
/**
* Returns an iterator over this HashSet. The elements are returned in no
* particular order.
*
* @return an iterator over this HashSet
*/
public IteratorI iterator() {
return new KeyIterator();
}
/**
* Converts the contents of this HashSet to an integer array. The order of
* the elements is unspecified.
*
* @return this HashSet as integer array
*/
public int[] toArray() {
int[] result = new int[size];
int ix = 0;
for (int i = 0; i < values.length; i++) {
if (values[i] != Integer.MIN_VALUE) {
result[ix++] = values[i];
}
}
return result;
}
// ////////////////////////
// Private inner methods
// ////////////////////////
/**
* Expands the capacity of this HashSet. (double it)
*/
private void expand() {
int[] newKeys = new int[values.length * 2];
int[] newNext = new int[next.length * 2];
int newMask = newKeys.length - 1;
for (int i = 0; i < newKeys.length; i++) {
newKeys[i] = Integer.MIN_VALUE;
}
for (int i = 0; i < values.length; i++) {
if (values[i] == Integer.MIN_VALUE) {
continue;
}
int key = values[i];
int index = key & newMask;
if (newKeys[index] == Integer.MIN_VALUE) {
newKeys[index] = key;
} else {
while (newNext[index] != 0) {
index = newNext[index] - 1;
}
int ref = index;
while (newKeys[index] != Integer.MIN_VALUE) {
index = (index + 1) & newMask;
}
newNext[ref] = index + 1;
newKeys[index] = key;
}
}
values = newKeys;
next = newNext;
mask = newMask;
}
// ////////////////////////
// Private inner classes
// ////////////////////////
private class KeyIterator implements IteratorI {
private int i;
public KeyIterator() {
i = 0;
skip();
}
@Override
public boolean hasNext() {
return i < values.length;
}
@Override
public int next() {
int result = values[i++];
skip();
return result;
}
private void skip() {
while (i < values.length && values[i] == Integer.MIN_VALUE)
i++;
}
}
}
| GTNewHorizons/NewHorizonsTweaker | ZenScript/src/main/java/stanhebben/zenscript/parser/HashSetI.java | 1,399 | // Private inner methods | line_comment | nl | /*
* This file is subject to the license.txt file in the main folder
* of this project.
*/
package stanhebben.zenscript.parser;
import java.util.Arrays;
/**
* HashSet implementation which is optimized for integer values.
*
* @author Stan Hebben
*/
public class HashSetI {
private int[] values;
private int[] next;
private int mask;
private int size;
/**
* Creates a new HashSet for integer values.
*/
public HashSetI() {
values = new int[16];
next = new int[16];
mask = 15;
size = 0;
for (int i = 0; i < values.length; i++) {
values[i] = Integer.MIN_VALUE;
}
}
public HashSetI(HashSetI original) {
values = Arrays.copyOf(original.values, original.values.length);
next = Arrays.copyOf(original.next, original.next.length);
mask = original.mask;
size = original.size;
}
/**
* Adds the specified value to this HashSet. If this value is already in
* this HashSet, nothing happens.
*
* @param value value to be added to the HashSet
*/
public void add(int value) {
if (size > (values.length * 3) >> 2) {
expand();
}
int index = value & mask;
if (values[index] == Integer.MIN_VALUE) {
values[index] = value;
} else {
if (values[index] == value) {
return;
}
while (next[index] != 0) {
index = next[index] - 1;
if (values[index] == value) {
return;
}
}
int ref = index;
while (values[index] != Integer.MIN_VALUE) {
index++;
if (index == values.length)
index = 0;
}
next[ref] = index + 1;
values[index] = value;
}
size++;
}
/**
* Checks if this HashSet contains the specified value.
*
* @param value integer value to add
* @return true if this HashSet contains the specified value
*/
public boolean contains(int value) {
int index = value & mask;
while (values[index] != value) {
if (next[index] == 0) {
return false;
}
index = next[index] - 1;
}
return true;
}
/**
* Returns an iterator over this HashSet. The elements are returned in no
* particular order.
*
* @return an iterator over this HashSet
*/
public IteratorI iterator() {
return new KeyIterator();
}
/**
* Converts the contents of this HashSet to an integer array. The order of
* the elements is unspecified.
*
* @return this HashSet as integer array
*/
public int[] toArray() {
int[] result = new int[size];
int ix = 0;
for (int i = 0; i < values.length; i++) {
if (values[i] != Integer.MIN_VALUE) {
result[ix++] = values[i];
}
}
return result;
}
// ////////////////////////
// Private inner<SUF>
// ////////////////////////
/**
* Expands the capacity of this HashSet. (double it)
*/
private void expand() {
int[] newKeys = new int[values.length * 2];
int[] newNext = new int[next.length * 2];
int newMask = newKeys.length - 1;
for (int i = 0; i < newKeys.length; i++) {
newKeys[i] = Integer.MIN_VALUE;
}
for (int i = 0; i < values.length; i++) {
if (values[i] == Integer.MIN_VALUE) {
continue;
}
int key = values[i];
int index = key & newMask;
if (newKeys[index] == Integer.MIN_VALUE) {
newKeys[index] = key;
} else {
while (newNext[index] != 0) {
index = newNext[index] - 1;
}
int ref = index;
while (newKeys[index] != Integer.MIN_VALUE) {
index = (index + 1) & newMask;
}
newNext[ref] = index + 1;
newKeys[index] = key;
}
}
values = newKeys;
next = newNext;
mask = newMask;
}
// ////////////////////////
// Private inner classes
// ////////////////////////
private class KeyIterator implements IteratorI {
private int i;
public KeyIterator() {
i = 0;
skip();
}
@Override
public boolean hasNext() {
return i < values.length;
}
@Override
public int next() {
int result = values[i++];
skip();
return result;
}
private void skip() {
while (i < values.length && values[i] == Integer.MIN_VALUE)
i++;
}
}
}
|
56767_4 | package tconstruct.client;
import static net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType.HEALTH;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.potion.Potion;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
public class HealthBarRenderer extends Gui {
private static final boolean isRpghudLoaded = Loader.isModLoaded("rpghud");
private static final boolean isTukmc_vzLoaded = Loader.isModLoaded("tukmc_Vz");
private static final boolean isBorderlandsModLoaded = Loader.isModLoaded("borderlands");
private static final ResourceLocation TINKER_HEARTS = new ResourceLocation("tinker", "textures/gui/newhearts.png");
private static final Minecraft mc = Minecraft.getMinecraft();
private final Random rand = new Random();
private int updateCounter = 0;
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START && !mc.isGamePaused()) {
this.updateCounter++;
}
}
/* HUD */
@SubscribeEvent(priority = EventPriority.HIGH) // Not highest for DualHotbar compatibility
public void renderHealthbar(RenderGameOverlayEvent.Pre event) {
if (event.type != RenderGameOverlayEvent.ElementType.HEALTH) {
return;
}
// uses different display, displays health correctly by itself.
if (isRpghudLoaded) {
return;
}
if (isTukmc_vzLoaded && !isBorderlandsModLoaded) {
// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
return;
}
mc.mcProfiler.startSection("health");
GL11.glEnable(GL11.GL_BLEND);
final int width = event.resolution.getScaledWidth();
final int height = event.resolution.getScaledHeight();
final int xBasePos = width / 2 - 91;
int yBasePos = height - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10) {
highlight = false;
}
final IAttributeInstance attrMaxHealth = mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
final int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
final int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
final float healthMax = Math.min(20F, (float) attrMaxHealth.getAttributeValue());
final float absorb = mc.thePlayer.getAbsorptionAmount();
final int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
final int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed(updateCounter * 312871L);
int left = width / 2 - 91;
int top = height - GuiIngameForge.left_height;
if (!GuiIngameForge.renderExperiance) {
top += 7;
yBasePos += 7;
}
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration)) {
regen = updateCounter % 25;
}
final int TOP;
int tinkerTextureY = 0;
if (mc.theWorld.getWorldInfo().isHardcoreModeEnabled()) {
TOP = 9 * 5;
tinkerTextureY += 27;
} else {
TOP = 0;
}
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison)) {
MARGIN += 36;
tinkerTextureY = 9;
} else if (mc.thePlayer.isPotionActive(Potion.wither)) {
MARGIN += 72;
tinkerTextureY = 18;
}
float absorbRemaining = absorb;
// Render vanilla hearts
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i) {
final int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4) y += rand.nextInt(2);
if (i == regen) y -= 2;
this.drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9); // heart background texture
if (highlight) {
if (i * 2 + 1 < healthLast) {
this.drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // full heart damage texture
} else if (i * 2 + 1 == healthLast) {
this.drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // half heart damage texture
}
}
if (absorbRemaining > 0.0F) {
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F) {
this.drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // half heart absorption texture
} else {
this.drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // full heart absorption texture
}
absorbRemaining -= 2.0F;
} else if (i * 2 + 1 + 20 >= health) {
// only draw red vanilla hearts when it won't be covered by tinkers' hearts
if (i * 2 + 1 < health) {
this.drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // full heart texture
} else if (i * 2 + 1 == health) {
this.drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // half heart texture
}
}
}
if (health > 20) {
// Render tinkers' hearts
mc.getTextureManager().bindTexture(TINKER_HEARTS);
for (int i = Math.max(0, health / 20 - 2); i < health / 20; i++) {
// uncomment the line below to help with debugging
// yBasePos -=20;
final int heartIndexMax = Math.min(10, (health - 20 * (i + 1)) / 2);
for (int j = 0; j < heartIndexMax; j++) {
int y = 0;
if (j == regen) y -= 2;
if ((i + 1) * 20 + j * 2 + 21 >= health) {
// full heart texture
this.drawTexturedModalRect(xBasePos + 8 * j, yBasePos + y, 18 * i, tinkerTextureY, 9, 9);
}
}
if (health % 2 == 1 && heartIndexMax < 10) {
int y = 0;
if (heartIndexMax == regen) y -= 2;
// half heart texture
this.drawTexturedModalRect(
xBasePos + 8 * heartIndexMax,
yBasePos + y,
9 + 18 * i,
tinkerTextureY,
9,
9);
}
}
mc.getTextureManager().bindTexture(icons);
}
GuiIngameForge.left_height += 10;
if (absorb > 0) GuiIngameForge.left_height += 10;
GL11.glDisable(GL11.GL_BLEND);
mc.mcProfiler.endSection();
event.setCanceled(true);
MinecraftForge.EVENT_BUS.post(new RenderGameOverlayEvent.Post(event, HEALTH));
}
}
| GTNewHorizons/TinkersConstruct | src/main/java/tconstruct/client/HealthBarRenderer.java | 2,429 | // Render vanilla hearts | line_comment | nl | package tconstruct.client;
import static net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType.HEALTH;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.potion.Potion;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
public class HealthBarRenderer extends Gui {
private static final boolean isRpghudLoaded = Loader.isModLoaded("rpghud");
private static final boolean isTukmc_vzLoaded = Loader.isModLoaded("tukmc_Vz");
private static final boolean isBorderlandsModLoaded = Loader.isModLoaded("borderlands");
private static final ResourceLocation TINKER_HEARTS = new ResourceLocation("tinker", "textures/gui/newhearts.png");
private static final Minecraft mc = Minecraft.getMinecraft();
private final Random rand = new Random();
private int updateCounter = 0;
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START && !mc.isGamePaused()) {
this.updateCounter++;
}
}
/* HUD */
@SubscribeEvent(priority = EventPriority.HIGH) // Not highest for DualHotbar compatibility
public void renderHealthbar(RenderGameOverlayEvent.Pre event) {
if (event.type != RenderGameOverlayEvent.ElementType.HEALTH) {
return;
}
// uses different display, displays health correctly by itself.
if (isRpghudLoaded) {
return;
}
if (isTukmc_vzLoaded && !isBorderlandsModLoaded) {
// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
return;
}
mc.mcProfiler.startSection("health");
GL11.glEnable(GL11.GL_BLEND);
final int width = event.resolution.getScaledWidth();
final int height = event.resolution.getScaledHeight();
final int xBasePos = width / 2 - 91;
int yBasePos = height - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10) {
highlight = false;
}
final IAttributeInstance attrMaxHealth = mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
final int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
final int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
final float healthMax = Math.min(20F, (float) attrMaxHealth.getAttributeValue());
final float absorb = mc.thePlayer.getAbsorptionAmount();
final int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
final int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed(updateCounter * 312871L);
int left = width / 2 - 91;
int top = height - GuiIngameForge.left_height;
if (!GuiIngameForge.renderExperiance) {
top += 7;
yBasePos += 7;
}
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration)) {
regen = updateCounter % 25;
}
final int TOP;
int tinkerTextureY = 0;
if (mc.theWorld.getWorldInfo().isHardcoreModeEnabled()) {
TOP = 9 * 5;
tinkerTextureY += 27;
} else {
TOP = 0;
}
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison)) {
MARGIN += 36;
tinkerTextureY = 9;
} else if (mc.thePlayer.isPotionActive(Potion.wither)) {
MARGIN += 72;
tinkerTextureY = 18;
}
float absorbRemaining = absorb;
// Render vanilla<SUF>
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i) {
final int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4) y += rand.nextInt(2);
if (i == regen) y -= 2;
this.drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9); // heart background texture
if (highlight) {
if (i * 2 + 1 < healthLast) {
this.drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // full heart damage texture
} else if (i * 2 + 1 == healthLast) {
this.drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // half heart damage texture
}
}
if (absorbRemaining > 0.0F) {
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F) {
this.drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // half heart absorption texture
} else {
this.drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // full heart absorption texture
}
absorbRemaining -= 2.0F;
} else if (i * 2 + 1 + 20 >= health) {
// only draw red vanilla hearts when it won't be covered by tinkers' hearts
if (i * 2 + 1 < health) {
this.drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // full heart texture
} else if (i * 2 + 1 == health) {
this.drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // half heart texture
}
}
}
if (health > 20) {
// Render tinkers' hearts
mc.getTextureManager().bindTexture(TINKER_HEARTS);
for (int i = Math.max(0, health / 20 - 2); i < health / 20; i++) {
// uncomment the line below to help with debugging
// yBasePos -=20;
final int heartIndexMax = Math.min(10, (health - 20 * (i + 1)) / 2);
for (int j = 0; j < heartIndexMax; j++) {
int y = 0;
if (j == regen) y -= 2;
if ((i + 1) * 20 + j * 2 + 21 >= health) {
// full heart texture
this.drawTexturedModalRect(xBasePos + 8 * j, yBasePos + y, 18 * i, tinkerTextureY, 9, 9);
}
}
if (health % 2 == 1 && heartIndexMax < 10) {
int y = 0;
if (heartIndexMax == regen) y -= 2;
// half heart texture
this.drawTexturedModalRect(
xBasePos + 8 * heartIndexMax,
yBasePos + y,
9 + 18 * i,
tinkerTextureY,
9,
9);
}
}
mc.getTextureManager().bindTexture(icons);
}
GuiIngameForge.left_height += 10;
if (absorb > 0) GuiIngameForge.left_height += 10;
GL11.glDisable(GL11.GL_BLEND);
mc.mcProfiler.endSection();
event.setCanceled(true);
MinecraftForge.EVENT_BUS.post(new RenderGameOverlayEvent.Post(event, HEALTH));
}
}
|
23989_4 | package be.intecbrussel;
import java.lang.reflect.Array;
public class MainApp {
public static void main(String[] args) {
// boolean hasSubscription = false;
//
// if (hasSubscription == true) {
// System.out.println("Show article");
// } else {
// System.out.println("Show subscription banner");
// }
String name = "Gabriel";
String language = "NL";
if (language.equals("NL")) {
System.out.println("Goedendag " + name);
} else if (language.equals("DE")) {
System.out.println("Guter tag " + name);
} else if (language.equals("FR")) {
System.out.println("Bonjour " + name);
} else {
System.out.println("Good morning " + name);
}
System.out.println("---- Oefening 1 ----");
int a = 10;
int b = 10;
if (a == b) {
System.out.println("De getallen zijn gelijk : " + a + " = " + b);
} else {
System.out.println("De getallen zijn niet gelijk : " + a + " != " + b);
}
System.out.println("---- Oefening 2 ----");
int number = 11;
if (number % 2 == 0) {
System.out.println(number + " is een even getal.");
} else {
System.out.println(number + " is een oneven getal.");
}
System.out.println("---- SWITCH ----");
language = "AR";
switch (language) {
case "NL":
System.out.println("Goedendag " + name);
break;
case "DE":
System.out.println("Guter tag " + name);
break;
case "FR":
System.out.println("Bojour " + name);
break;
case "PT":
System.out.println("Bom dia " + name);
break;
default:
System.out.println("Good morning " + name);
}
int day = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid");
}
System.out.println("---- complex statements ----");
name = "Jan";
language = "FR";
int time = 19;
if (language.equals("NL") && time < 12) {
System.out.println("Goedemorgen, " + name);
} else if (language.equals("Nl") && time >= 10 && time < 18) {
System.out.println("Goedemiddag, " + name);
} else if (language.equals("NL") && time >= 18 && time <= 24) {
System.out.println("Goede avond, " + name);
}
// Nested if
if (language.equals("NL")) {
if (time < 12) {
System.out.println("Goedemorgen, " + name);
} else if (time >= 12 && time < 18) {
System.out.println("Goedemiddag, " + name);
} else if (time >= 18 && time <= 24) {
System.out.println("Goede avond, " + name);
}
} else if (language.equals("FR")) {
if (time < 12) {
System.out.println("Bonjour, " + name);
} else if (time >= 12 && time < 18) {
System.out.println("Bon après midi, " + name);
} else if (time >= 18 && time <= 24) {
System.out.println("Bonsoir, " + name);
}
}
// ternary operator -> minder belangrijk
int age = 17;
// normale if
if (age > 18) {
System.out.println("Adult");
} else {
System.out.println("Child");
}
// ternary operator -> (?) = if (:) = else
System.out.println((age > 18) ? "Adult" : "Child");
}
}
| Gabe-Alvess/Branching | src/be/intecbrussel/MainApp.java | 1,163 | // ternary operator -> minder belangrijk | line_comment | nl | package be.intecbrussel;
import java.lang.reflect.Array;
public class MainApp {
public static void main(String[] args) {
// boolean hasSubscription = false;
//
// if (hasSubscription == true) {
// System.out.println("Show article");
// } else {
// System.out.println("Show subscription banner");
// }
String name = "Gabriel";
String language = "NL";
if (language.equals("NL")) {
System.out.println("Goedendag " + name);
} else if (language.equals("DE")) {
System.out.println("Guter tag " + name);
} else if (language.equals("FR")) {
System.out.println("Bonjour " + name);
} else {
System.out.println("Good morning " + name);
}
System.out.println("---- Oefening 1 ----");
int a = 10;
int b = 10;
if (a == b) {
System.out.println("De getallen zijn gelijk : " + a + " = " + b);
} else {
System.out.println("De getallen zijn niet gelijk : " + a + " != " + b);
}
System.out.println("---- Oefening 2 ----");
int number = 11;
if (number % 2 == 0) {
System.out.println(number + " is een even getal.");
} else {
System.out.println(number + " is een oneven getal.");
}
System.out.println("---- SWITCH ----");
language = "AR";
switch (language) {
case "NL":
System.out.println("Goedendag " + name);
break;
case "DE":
System.out.println("Guter tag " + name);
break;
case "FR":
System.out.println("Bojour " + name);
break;
case "PT":
System.out.println("Bom dia " + name);
break;
default:
System.out.println("Good morning " + name);
}
int day = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid");
}
System.out.println("---- complex statements ----");
name = "Jan";
language = "FR";
int time = 19;
if (language.equals("NL") && time < 12) {
System.out.println("Goedemorgen, " + name);
} else if (language.equals("Nl") && time >= 10 && time < 18) {
System.out.println("Goedemiddag, " + name);
} else if (language.equals("NL") && time >= 18 && time <= 24) {
System.out.println("Goede avond, " + name);
}
// Nested if
if (language.equals("NL")) {
if (time < 12) {
System.out.println("Goedemorgen, " + name);
} else if (time >= 12 && time < 18) {
System.out.println("Goedemiddag, " + name);
} else if (time >= 18 && time <= 24) {
System.out.println("Goede avond, " + name);
}
} else if (language.equals("FR")) {
if (time < 12) {
System.out.println("Bonjour, " + name);
} else if (time >= 12 && time < 18) {
System.out.println("Bon après midi, " + name);
} else if (time >= 18 && time <= 24) {
System.out.println("Bonsoir, " + name);
}
}
// ternary operator<SUF>
int age = 17;
// normale if
if (age > 18) {
System.out.println("Adult");
} else {
System.out.println("Child");
}
// ternary operator -> (?) = if (:) = else
System.out.println((age > 18) ? "Adult" : "Child");
}
}
|
164649_3 | package be.intecbrussel;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateTime {
public static void main(String[] args) {
Instant epochDate = Instant.EPOCH;
System.out.println("Epoch date -> " + epochDate + "\n"); // -> Epoch date geeft de start datum en tijd van een operating system aan.
Instant now = Instant.now();
System.out.println("Now date -> " + now + "\n"); // -> Geeft tegenwoordige datum en standard tijd aan (coordinated universal time).
LocalTime lt = LocalTime.now();
System.out.println("Local time -> " + lt + "\n"); // -> Geeft de tegenwoordige locale tijd aan.
LocalDate ld = LocalDate.now();
System.out.println("Local date -> " + ld + "\n"); // -> Geeft de tegenwoordige locale datum aan.
LocalDateTime ldt = LocalDateTime.now();
System.out.println("Local date and time -> " + ldt + "\n");
LocalDateTime date = LocalDateTime.of(2018, 01, 20, 12, 30);
System.out.println("Written date and time -> " + date + "\n");
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String myFormattedDateTime = ldt.format(myFormat);
System.out.println("Formatted date and time -> " + myFormattedDateTime + "\n");
/*
* yyyy-MM-dd -> 2023-02-07
* dd/MM/yyyy -> 07/09/2023
* dd-MMM-yyyy -> 29-Feb-2023
* E, MMM dd yyyy -> Tue, Feb 07 2023
*/
Duration secondsInHour = Duration.ofHours(1);
System.out.println(secondsInHour.getSeconds() + " seconds" + "\n");
Duration secondsInDay = Duration.ofDays(1);
System.out.println(secondsInDay.getSeconds() + " seconds" + "\n");
LocalDateTime newDate1 = LocalDateTime.of(2022, 8, 25, 11, 33, 15);
LocalDateTime oldDate1 = LocalDateTime.of(2016, 8, 31, 10, 20, 55);
Duration betweenDate = Duration.between(oldDate1, newDate1);
System.out.println(betweenDate.getSeconds() + " seconds" + "\n");
Period tenDays = Period.ofDays(10).plusDays(10);
System.out.println(tenDays.getDays() + "\n");
Period months1 = Period.ofMonths(1).plusMonths(25);
System.out.println(months1.getMonths() + "\n");
LocalDate newDate2 = LocalDate.of(2022, 8, 25);
LocalDate oldDate2 = LocalDate.of(2000, 1, 1);
Period period = Period.between(oldDate2, newDate2);
System.out.print(period.getYears() + " years, ");
System.out.print(period.getMonths() + " months, ");
System.out.print(period.getDays() + " days" + "\n");
LocalDateTime newDate3 = LocalDateTime.of(2022, 8, 25, 11, 33, 15);
LocalDateTime oldDate3 = LocalDateTime.of(1021, 8, 31, 10, 20, 55);
long millennia = ChronoUnit.MILLENNIA.between(oldDate3, newDate3);
long centuries = ChronoUnit.CENTURIES.between(oldDate3, newDate3);
long decades = ChronoUnit.DECADES.between(oldDate3, newDate3);
long years = ChronoUnit.YEARS.between(oldDate3, newDate3);
long months = ChronoUnit.MONTHS.between(oldDate3, newDate3);
long weeks = ChronoUnit.WEEKS.between(oldDate3, newDate3);
long days = ChronoUnit.DAYS.between(oldDate3, newDate3);
long hours = ChronoUnit.HOURS.between(oldDate3, newDate3);
long minutes = ChronoUnit.MINUTES.between(oldDate3, newDate3);
long seconds = ChronoUnit.SECONDS.between(oldDate3, newDate3);
System.out.println(millennia + " millennia");
System.out.println(centuries + " centuries");
System.out.println(decades + " decades");
System.out.println(years + " years");
System.out.println(months + " months");
System.out.println(weeks + " weeks");
System.out.println(days + " days");
System.out.println(hours + " hours");
System.out.println(minutes + " minutes");
System.out.println(seconds + " seconds" + "\n");
ChronoUnit chronoUnit1 = ChronoUnit.valueOf("DAYS");
Duration getDurationAttribute1 = chronoUnit1.getDuration();
System.out.println("Duration Estimated : " + getDurationAttribute1 + "\n");
ChronoUnit chronoUnit2 = ChronoUnit.valueOf("MONTHS");
Duration getDurationAttribute2 = chronoUnit2.getDuration();
System.out.println("Duration Estimated : " + getDurationAttribute2);
}
}
| Gabe-Alvess/DateTime | src/be/intecbrussel/DateTime.java | 1,441 | // -> Geeft de tegenwoordige locale datum aan. | line_comment | nl | package be.intecbrussel;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateTime {
public static void main(String[] args) {
Instant epochDate = Instant.EPOCH;
System.out.println("Epoch date -> " + epochDate + "\n"); // -> Epoch date geeft de start datum en tijd van een operating system aan.
Instant now = Instant.now();
System.out.println("Now date -> " + now + "\n"); // -> Geeft tegenwoordige datum en standard tijd aan (coordinated universal time).
LocalTime lt = LocalTime.now();
System.out.println("Local time -> " + lt + "\n"); // -> Geeft de tegenwoordige locale tijd aan.
LocalDate ld = LocalDate.now();
System.out.println("Local date -> " + ld + "\n"); // -> Geeft<SUF>
LocalDateTime ldt = LocalDateTime.now();
System.out.println("Local date and time -> " + ldt + "\n");
LocalDateTime date = LocalDateTime.of(2018, 01, 20, 12, 30);
System.out.println("Written date and time -> " + date + "\n");
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String myFormattedDateTime = ldt.format(myFormat);
System.out.println("Formatted date and time -> " + myFormattedDateTime + "\n");
/*
* yyyy-MM-dd -> 2023-02-07
* dd/MM/yyyy -> 07/09/2023
* dd-MMM-yyyy -> 29-Feb-2023
* E, MMM dd yyyy -> Tue, Feb 07 2023
*/
Duration secondsInHour = Duration.ofHours(1);
System.out.println(secondsInHour.getSeconds() + " seconds" + "\n");
Duration secondsInDay = Duration.ofDays(1);
System.out.println(secondsInDay.getSeconds() + " seconds" + "\n");
LocalDateTime newDate1 = LocalDateTime.of(2022, 8, 25, 11, 33, 15);
LocalDateTime oldDate1 = LocalDateTime.of(2016, 8, 31, 10, 20, 55);
Duration betweenDate = Duration.between(oldDate1, newDate1);
System.out.println(betweenDate.getSeconds() + " seconds" + "\n");
Period tenDays = Period.ofDays(10).plusDays(10);
System.out.println(tenDays.getDays() + "\n");
Period months1 = Period.ofMonths(1).plusMonths(25);
System.out.println(months1.getMonths() + "\n");
LocalDate newDate2 = LocalDate.of(2022, 8, 25);
LocalDate oldDate2 = LocalDate.of(2000, 1, 1);
Period period = Period.between(oldDate2, newDate2);
System.out.print(period.getYears() + " years, ");
System.out.print(period.getMonths() + " months, ");
System.out.print(period.getDays() + " days" + "\n");
LocalDateTime newDate3 = LocalDateTime.of(2022, 8, 25, 11, 33, 15);
LocalDateTime oldDate3 = LocalDateTime.of(1021, 8, 31, 10, 20, 55);
long millennia = ChronoUnit.MILLENNIA.between(oldDate3, newDate3);
long centuries = ChronoUnit.CENTURIES.between(oldDate3, newDate3);
long decades = ChronoUnit.DECADES.between(oldDate3, newDate3);
long years = ChronoUnit.YEARS.between(oldDate3, newDate3);
long months = ChronoUnit.MONTHS.between(oldDate3, newDate3);
long weeks = ChronoUnit.WEEKS.between(oldDate3, newDate3);
long days = ChronoUnit.DAYS.between(oldDate3, newDate3);
long hours = ChronoUnit.HOURS.between(oldDate3, newDate3);
long minutes = ChronoUnit.MINUTES.between(oldDate3, newDate3);
long seconds = ChronoUnit.SECONDS.between(oldDate3, newDate3);
System.out.println(millennia + " millennia");
System.out.println(centuries + " centuries");
System.out.println(decades + " decades");
System.out.println(years + " years");
System.out.println(months + " months");
System.out.println(weeks + " weeks");
System.out.println(days + " days");
System.out.println(hours + " hours");
System.out.println(minutes + " minutes");
System.out.println(seconds + " seconds" + "\n");
ChronoUnit chronoUnit1 = ChronoUnit.valueOf("DAYS");
Duration getDurationAttribute1 = chronoUnit1.getDuration();
System.out.println("Duration Estimated : " + getDurationAttribute1 + "\n");
ChronoUnit chronoUnit2 = ChronoUnit.valueOf("MONTHS");
Duration getDurationAttribute2 = chronoUnit2.getDuration();
System.out.println("Duration Estimated : " + getDurationAttribute2);
}
}
|
44956_7 | package be.intecbrussel;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateTimeExercises {
public static void main(String[] args) {
System.out.println("---- Date and Time ----");
System.out.println("---- Oefening - 1 ----");
// 1. Bij deze oefening gaan we gebruik maken van de volgende classes LocalDateTime, DateTimeFormatter en ChronoUnit.
// Print huidige tijd uit.
LocalDateTime ldt = LocalDateTime.now();
System.out.println("Huidige tijd en datum -> " + ldt);
// Print nu een tijd in de toekomst uit. Gebruik de huidige tijd en zorg dat deze 3 jaar verder komt te staan.
LocalDateTime futureDateTime = LocalDateTime.of(2026, 2, 10, 13, 5, 20);
System.out.println("Toekomstige datum en tijd -> " + futureDateTime);
// Bereken het verschil tussen deze 2 tijden: jaren, maanden, dagen, uren, minuten, secondes.
LocalDateTime actualDateTime = LocalDateTime.of(2023, 2, 10, 13, 5, 20);
long years = ChronoUnit.YEARS.between(actualDateTime, futureDateTime);
long months = ChronoUnit.MONTHS.between(actualDateTime, futureDateTime);
long weeks = ChronoUnit.WEEKS.between(actualDateTime, futureDateTime);
long days = ChronoUnit.DAYS.between(actualDateTime, futureDateTime);
long hours = ChronoUnit.HOURS.between(actualDateTime, futureDateTime);
long minutes = ChronoUnit.MINUTES.between(actualDateTime, futureDateTime);
long seconds = ChronoUnit.SECONDS.between(actualDateTime, futureDateTime);
System.out.println(years + " years");
System.out.println(months + " months");
System.out.println(weeks + " weeks");
System.out.println(days + " days");
System.out.println(hours + " hours");
System.out.println(minutes + " minutes");
System.out.println(seconds + " seconds");
// Formateer deze 2 tijden als strings met dit patroon: "yyyy-MM-dd HH:mm:ss".
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedActualDate = actualDateTime.format(format);
String formattedFutureDate = futureDateTime.format(format);
System.out.println("Actual date and time formatted -> " + formattedActualDate + "\n" + "Future date and time formatted -> " + formattedFutureDate);
System.out.println("---- Oefening - 2 ----");
// Schrijf een programma dat van je geboortedatum het volgende afdrukt:
// Bij deze oefening gaan we gebruik maken van de volgende classes LocalDate, LocalTime en LocalDateTime.
// De hoeveelste dag van dat jaar het was.
LocalDate birthDate = LocalDate.of(2000, 11, 20);
System.out.println("My birth date -> " + birthDate + "\n" + "Day of the year -> " + birthDate.getDayOfYear());
// De dag van de maand.
System.out.println("Day of the month -> " + birthDate.getDayOfMonth());
// De dag van de week.
System.out.println("Day of the week -> " + birthDate.getDayOfWeek());
// of je geboorte jaar in een schrikkeljaar was.
System.out.println("Was it a leap year? -> " + (birthDate.isLeapYear()? "Yes" : "No"));
System.out.println("---- Github ----");
System.out.println("---- Oefening - 1 ----");
// 1. Schrijf een programma om de huidige tijd en datum te krijgen.
LocalDateTime huidigeTijdAndDatum = LocalDateTime.now();
System.out.println(huidigeTijdAndDatum.format(format));
System.out.println("---- Oefening - 2 ----");
// 2. Schrijf een programma om de tijd en datum te formatteren naar: ma, 22 aug. 2022 14:54:24
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss");
LocalDateTime randomDateTime = LocalDateTime.of(2022,8, 22, 14, 54, 24);
String formattedDateTime = randomDateTime.format(format1);
System.out.println(formattedDateTime);
System.out.println("---- Oefening - 3 ----");
// 3. Schrijf een programma om je leeftijd te berekenen in dagen, maanden en jaren.
// Niet Duidelijk!
}
}
| Gabe-Alvess/DateTimeWrapperOef | src/be/intecbrussel/DateTimeExercises.java | 1,275 | // De hoeveelste dag van dat jaar het was. | line_comment | nl | package be.intecbrussel;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateTimeExercises {
public static void main(String[] args) {
System.out.println("---- Date and Time ----");
System.out.println("---- Oefening - 1 ----");
// 1. Bij deze oefening gaan we gebruik maken van de volgende classes LocalDateTime, DateTimeFormatter en ChronoUnit.
// Print huidige tijd uit.
LocalDateTime ldt = LocalDateTime.now();
System.out.println("Huidige tijd en datum -> " + ldt);
// Print nu een tijd in de toekomst uit. Gebruik de huidige tijd en zorg dat deze 3 jaar verder komt te staan.
LocalDateTime futureDateTime = LocalDateTime.of(2026, 2, 10, 13, 5, 20);
System.out.println("Toekomstige datum en tijd -> " + futureDateTime);
// Bereken het verschil tussen deze 2 tijden: jaren, maanden, dagen, uren, minuten, secondes.
LocalDateTime actualDateTime = LocalDateTime.of(2023, 2, 10, 13, 5, 20);
long years = ChronoUnit.YEARS.between(actualDateTime, futureDateTime);
long months = ChronoUnit.MONTHS.between(actualDateTime, futureDateTime);
long weeks = ChronoUnit.WEEKS.between(actualDateTime, futureDateTime);
long days = ChronoUnit.DAYS.between(actualDateTime, futureDateTime);
long hours = ChronoUnit.HOURS.between(actualDateTime, futureDateTime);
long minutes = ChronoUnit.MINUTES.between(actualDateTime, futureDateTime);
long seconds = ChronoUnit.SECONDS.between(actualDateTime, futureDateTime);
System.out.println(years + " years");
System.out.println(months + " months");
System.out.println(weeks + " weeks");
System.out.println(days + " days");
System.out.println(hours + " hours");
System.out.println(minutes + " minutes");
System.out.println(seconds + " seconds");
// Formateer deze 2 tijden als strings met dit patroon: "yyyy-MM-dd HH:mm:ss".
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedActualDate = actualDateTime.format(format);
String formattedFutureDate = futureDateTime.format(format);
System.out.println("Actual date and time formatted -> " + formattedActualDate + "\n" + "Future date and time formatted -> " + formattedFutureDate);
System.out.println("---- Oefening - 2 ----");
// Schrijf een programma dat van je geboortedatum het volgende afdrukt:
// Bij deze oefening gaan we gebruik maken van de volgende classes LocalDate, LocalTime en LocalDateTime.
// De hoeveelste<SUF>
LocalDate birthDate = LocalDate.of(2000, 11, 20);
System.out.println("My birth date -> " + birthDate + "\n" + "Day of the year -> " + birthDate.getDayOfYear());
// De dag van de maand.
System.out.println("Day of the month -> " + birthDate.getDayOfMonth());
// De dag van de week.
System.out.println("Day of the week -> " + birthDate.getDayOfWeek());
// of je geboorte jaar in een schrikkeljaar was.
System.out.println("Was it a leap year? -> " + (birthDate.isLeapYear()? "Yes" : "No"));
System.out.println("---- Github ----");
System.out.println("---- Oefening - 1 ----");
// 1. Schrijf een programma om de huidige tijd en datum te krijgen.
LocalDateTime huidigeTijdAndDatum = LocalDateTime.now();
System.out.println(huidigeTijdAndDatum.format(format));
System.out.println("---- Oefening - 2 ----");
// 2. Schrijf een programma om de tijd en datum te formatteren naar: ma, 22 aug. 2022 14:54:24
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss");
LocalDateTime randomDateTime = LocalDateTime.of(2022,8, 22, 14, 54, 24);
String formattedDateTime = randomDateTime.format(format1);
System.out.println(formattedDateTime);
System.out.println("---- Oefening - 3 ----");
// 3. Schrijf een programma om je leeftijd te berekenen in dagen, maanden en jaren.
// Niet Duidelijk!
}
}
|
22652_10 | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
System.out.println("Extra Oefeningen");
System.out.println("---- Oefening 1 ----");
// 1. Schrijf een programma dat het brutoloon omrekent naar het nettoloon.
// Het programma moet rekening houden met de belastingen die ervan afgehouden worden.
//- Brutoloon groter dan 3000 euro = 38% belastingen.
//- Brutoloon tussen 2000 en 3000 euro= 35% belastingen.
//- Brutoloon kleiner dan 2000 euro= 27% belastingen.
int brutoloon = 5000;
int belasting = 0;
int result = 0;
if (brutoloon > 3000) {
belasting = brutoloon / 100 * 38;
result = brutoloon - belasting;
System.out.println("Nettoloon = " + result + "€");
} else if (brutoloon >= 2000 && brutoloon <= 3000 ) {
belasting = brutoloon / 100 * 35;
result = brutoloon - belasting;
System.out.println("Nettoloon = " + result + "€");
} else if (brutoloon < 2000) {
belasting = brutoloon / 100 * 27;
result = brutoloon - belasting;
System.out.println("Nettoloon = " + result + "€");
}
System.out.println(" ---- oefening 2 ---- ");
// 2. Schrijf een programma dat van een gegeven bedrag in euro (1 tot 500 euro) berekent
// welke biljetten en stukken je nodig hebt om het bedrag uit te betalen en hoeveel van elk.
double bedraag = 200;
int biljetten = 0;
int stukken = 0;
boolean evenGetal = bedraag % 2 == 0;
boolean onevenGetal = bedraag % 2 != 0;
if (bedraag >= 1 && bedraag <= 500 && evenGetal) {
} else if (bedraag >= 1 && bedraag <= 500 && onevenGetal) {
} else {
System.out.println("Het bedrag kon niet worden berekend!");
System.out.println("Het bedraag mag minimum 1€ en maximum 500€ zijn.");
}
System.out.println(" ---- oefening 3 ---- ");
// 3. Schrijf een programma met 2 variabelen. Zorg dat je de basic calculaties (+, -, /, *, %) kunt uitvoeren.
// Gebruik hiervoor een switch statement.
int a = 65;
int b = 10;
int res = 0;
String operators = "*";
switch (operators) {
case "+" -> {
res = a + b;
System.out.println(a + " + " + b + " = " + res);
}
case "-" -> {
res = a - b;
System.out.println(a + " - " + b + " = " + res);
}
case "/" -> {
res = a / b;
System.out.println(a + " / " + b + " = " + res);
}
case "*" -> {
res = a * b;
System.out.println(a + " * " + b + " = " + res);
}
case "%" -> {
res = a % b;
System.out.println(a + " % " + b + " = " + res);
}
default -> {
System.out.println("Ongeldige operator!");
}
}
System.out.println(" ---- oefening 4 ---- ");
// 4. Maak een programma dat een geheel aantal seconden, bijvoorbeeld 5924, omrekent in uren, minuten en seconden.
// Het resultaat: U:1 M:38 S:44.
}
}
| Gabe-Alvess/ExtraOefeningen | src/be/intecbrussel/MainApp.java | 1,085 | // Het resultaat: U:1 M:38 S:44. | line_comment | nl | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
System.out.println("Extra Oefeningen");
System.out.println("---- Oefening 1 ----");
// 1. Schrijf een programma dat het brutoloon omrekent naar het nettoloon.
// Het programma moet rekening houden met de belastingen die ervan afgehouden worden.
//- Brutoloon groter dan 3000 euro = 38% belastingen.
//- Brutoloon tussen 2000 en 3000 euro= 35% belastingen.
//- Brutoloon kleiner dan 2000 euro= 27% belastingen.
int brutoloon = 5000;
int belasting = 0;
int result = 0;
if (brutoloon > 3000) {
belasting = brutoloon / 100 * 38;
result = brutoloon - belasting;
System.out.println("Nettoloon = " + result + "€");
} else if (brutoloon >= 2000 && brutoloon <= 3000 ) {
belasting = brutoloon / 100 * 35;
result = brutoloon - belasting;
System.out.println("Nettoloon = " + result + "€");
} else if (brutoloon < 2000) {
belasting = brutoloon / 100 * 27;
result = brutoloon - belasting;
System.out.println("Nettoloon = " + result + "€");
}
System.out.println(" ---- oefening 2 ---- ");
// 2. Schrijf een programma dat van een gegeven bedrag in euro (1 tot 500 euro) berekent
// welke biljetten en stukken je nodig hebt om het bedrag uit te betalen en hoeveel van elk.
double bedraag = 200;
int biljetten = 0;
int stukken = 0;
boolean evenGetal = bedraag % 2 == 0;
boolean onevenGetal = bedraag % 2 != 0;
if (bedraag >= 1 && bedraag <= 500 && evenGetal) {
} else if (bedraag >= 1 && bedraag <= 500 && onevenGetal) {
} else {
System.out.println("Het bedrag kon niet worden berekend!");
System.out.println("Het bedraag mag minimum 1€ en maximum 500€ zijn.");
}
System.out.println(" ---- oefening 3 ---- ");
// 3. Schrijf een programma met 2 variabelen. Zorg dat je de basic calculaties (+, -, /, *, %) kunt uitvoeren.
// Gebruik hiervoor een switch statement.
int a = 65;
int b = 10;
int res = 0;
String operators = "*";
switch (operators) {
case "+" -> {
res = a + b;
System.out.println(a + " + " + b + " = " + res);
}
case "-" -> {
res = a - b;
System.out.println(a + " - " + b + " = " + res);
}
case "/" -> {
res = a / b;
System.out.println(a + " / " + b + " = " + res);
}
case "*" -> {
res = a * b;
System.out.println(a + " * " + b + " = " + res);
}
case "%" -> {
res = a % b;
System.out.println(a + " % " + b + " = " + res);
}
default -> {
System.out.println("Ongeldige operator!");
}
}
System.out.println(" ---- oefening 4 ---- ");
// 4. Maak een programma dat een geheel aantal seconden, bijvoorbeeld 5924, omrekent in uren, minuten en seconden.
// Het resultaat:<SUF>
}
}
|
21120_0 | package be.intecbrussel.the_notebook.app;
import be.intecbrussel.the_notebook.entities.animal_entities.Animal;
import be.intecbrussel.the_notebook.entities.animal_entities.Carnivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Herbivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Omnivore;
import be.intecbrussel.the_notebook.entities.plant_entities.*;
import be.intecbrussel.the_notebook.service.ForestNotebook;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class NatureApp {
public static void main(String[] args) {
lineGenerator();
System.out.println("FOREST NOTEBOOK TEST");
lineGenerator();
ForestNotebook forestNotebook = new ForestNotebook();
Plant plant = new Plant("Orchid", 0.55);
Tree tree = new Tree("Pine tree", 40.5);
tree.setLeafType(LeafType.NEEDLE);
Flower flower = new Flower("Rose", 0.15);
flower.setSmell(Scent.SWEET);
Weed weed = new Weed("Dandelion", 0.05);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurig cijfer daarin geplaatst.
weed.setArea(10.5);
Bush bush = new Bush("Blueberry bush", 3.5);
bush.setLeafType(LeafType.SPEAR);
bush.setFruit("Blueberry");
forestNotebook.addPlant(plant);
forestNotebook.addPlant(tree);
forestNotebook.addPlant(flower);
forestNotebook.addPlant(weed);
forestNotebook.addPlant(bush);
forestNotebook.addPlant(plant);
List<Carnivore> carnivoreList = new ArrayList<>();
List<Herbivore> herbivoreList = new ArrayList<>();
List<Omnivore> omnivoreList = new ArrayList<>();
Carnivore lion = new Carnivore("Lion", 190, 1.2, 2.1);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurige maat daarin geplaatst.
lion.setMaxFoodSize(1.5);
carnivoreList.add(lion);
forestNotebook.setCarnivores(carnivoreList);
Herbivore elephant = new Herbivore("Elephant", 6000, 3.2, 6.5);
Set<Plant> elephantDiet = new LinkedHashSet<>();
Plant plant1 = new Plant("Grasses");
Plant plant2 = new Plant("Leaves");
Plant plant3 = new Plant("Fruits");
Plant plant4 = new Plant("Roots");
elephantDiet.add(plant1);
elephantDiet.add(plant2);
elephantDiet.add(plant3);
elephant.setPlantDiet(elephantDiet);
elephant.addPlantToDiet(plant4);
herbivoreList.add(elephant);
forestNotebook.setHerbivores(herbivoreList);
Omnivore bear = new Omnivore("Bear", 500, 1.5, 2.8);
bear.setMaxFoodSize(1.5);
Set<Plant> bearDiet = new LinkedHashSet<>();
bearDiet.add(new Plant("Berries"));
bearDiet.add(plant1);
bear.setPlantDiet(bearDiet);
bear.addPlantToDiet(plant4);
omnivoreList.add(bear);
forestNotebook.setOmnivores(omnivoreList);
Animal animal1 = new Animal("Gorilla", 270, 1.8, 1.7);
Animal animal2 = new Animal("Anaconda", 250, 0.3, 8.5);
Animal animal3 = new Animal("Red fox", 14, 0.5, 0.85);
Animal animal4 = new Animal("Rabbit", 2, 0.22, 0.45);
Animal animal5 = new Animal("Wolf", 80, 0.85, 1.6);
Animal animal6 = new Animal("Eagle", 6, 0.61, 0.90);
forestNotebook.addAnimal(lion);
forestNotebook.addAnimal(elephant);
forestNotebook.addAnimal(bear);
forestNotebook.addAnimal(animal1);
forestNotebook.addAnimal(animal2);
forestNotebook.addAnimal(animal3);
forestNotebook.addAnimal(animal4);
forestNotebook.addAnimal(animal5);
forestNotebook.addAnimal(animal6);
forestNotebook.addAnimal(lion);
lineGenerator();
System.out.println("TOTAL PLANTS AND ANIMALS");
lineGenerator();
System.out.println("Plants -> " + forestNotebook.getPlantCount());
System.out.println("Animals -> " + forestNotebook.getAnimalCount());
lineGenerator();
System.out.println("UNSORTED LIST OF PLANTS AND ANIMALS");
lineGenerator();
forestNotebook.printNotebook();
lineGenerator();
System.out.println("LIST OF CARNIVORE, OMNIVORE AND HERBIVORE ANIMALS");
lineGenerator();
forestNotebook.getCarnivores().forEach(System.out::println);
forestNotebook.getOmnivores().forEach(System.out::println);
forestNotebook.getHerbivores().forEach(System.out::println);
lineGenerator();
System.out.println("LIST OF PLANTS AND ANIMALS SORTED BY NAME");
lineGenerator();
forestNotebook.sortAnimalsByName();
forestNotebook.sortPlantsByName();
forestNotebook.printNotebook();
// Ik heb alle metingen omgezet naar meters om correct te kunnen sorteren.
lineGenerator();
System.out.println("BONUS - LIST OF PLANTS AND ANIMALS SORTED BY HEIGHT");
lineGenerator();
forestNotebook.sortAnimalsByHeight();
forestNotebook.sortPlantsHeight();
forestNotebook.printNotebook();
}
public static void lineGenerator() {
System.out.println("-".repeat(100));
}
}
| Gabe-Alvess/ForestNoteBook | src/be/intecbrussel/the_notebook/app/NatureApp.java | 1,805 | // Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurig cijfer daarin geplaatst. | line_comment | nl | package be.intecbrussel.the_notebook.app;
import be.intecbrussel.the_notebook.entities.animal_entities.Animal;
import be.intecbrussel.the_notebook.entities.animal_entities.Carnivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Herbivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Omnivore;
import be.intecbrussel.the_notebook.entities.plant_entities.*;
import be.intecbrussel.the_notebook.service.ForestNotebook;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class NatureApp {
public static void main(String[] args) {
lineGenerator();
System.out.println("FOREST NOTEBOOK TEST");
lineGenerator();
ForestNotebook forestNotebook = new ForestNotebook();
Plant plant = new Plant("Orchid", 0.55);
Tree tree = new Tree("Pine tree", 40.5);
tree.setLeafType(LeafType.NEEDLE);
Flower flower = new Flower("Rose", 0.15);
flower.setSmell(Scent.SWEET);
Weed weed = new Weed("Dandelion", 0.05);
// Geen idee<SUF>
weed.setArea(10.5);
Bush bush = new Bush("Blueberry bush", 3.5);
bush.setLeafType(LeafType.SPEAR);
bush.setFruit("Blueberry");
forestNotebook.addPlant(plant);
forestNotebook.addPlant(tree);
forestNotebook.addPlant(flower);
forestNotebook.addPlant(weed);
forestNotebook.addPlant(bush);
forestNotebook.addPlant(plant);
List<Carnivore> carnivoreList = new ArrayList<>();
List<Herbivore> herbivoreList = new ArrayList<>();
List<Omnivore> omnivoreList = new ArrayList<>();
Carnivore lion = new Carnivore("Lion", 190, 1.2, 2.1);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurige maat daarin geplaatst.
lion.setMaxFoodSize(1.5);
carnivoreList.add(lion);
forestNotebook.setCarnivores(carnivoreList);
Herbivore elephant = new Herbivore("Elephant", 6000, 3.2, 6.5);
Set<Plant> elephantDiet = new LinkedHashSet<>();
Plant plant1 = new Plant("Grasses");
Plant plant2 = new Plant("Leaves");
Plant plant3 = new Plant("Fruits");
Plant plant4 = new Plant("Roots");
elephantDiet.add(plant1);
elephantDiet.add(plant2);
elephantDiet.add(plant3);
elephant.setPlantDiet(elephantDiet);
elephant.addPlantToDiet(plant4);
herbivoreList.add(elephant);
forestNotebook.setHerbivores(herbivoreList);
Omnivore bear = new Omnivore("Bear", 500, 1.5, 2.8);
bear.setMaxFoodSize(1.5);
Set<Plant> bearDiet = new LinkedHashSet<>();
bearDiet.add(new Plant("Berries"));
bearDiet.add(plant1);
bear.setPlantDiet(bearDiet);
bear.addPlantToDiet(plant4);
omnivoreList.add(bear);
forestNotebook.setOmnivores(omnivoreList);
Animal animal1 = new Animal("Gorilla", 270, 1.8, 1.7);
Animal animal2 = new Animal("Anaconda", 250, 0.3, 8.5);
Animal animal3 = new Animal("Red fox", 14, 0.5, 0.85);
Animal animal4 = new Animal("Rabbit", 2, 0.22, 0.45);
Animal animal5 = new Animal("Wolf", 80, 0.85, 1.6);
Animal animal6 = new Animal("Eagle", 6, 0.61, 0.90);
forestNotebook.addAnimal(lion);
forestNotebook.addAnimal(elephant);
forestNotebook.addAnimal(bear);
forestNotebook.addAnimal(animal1);
forestNotebook.addAnimal(animal2);
forestNotebook.addAnimal(animal3);
forestNotebook.addAnimal(animal4);
forestNotebook.addAnimal(animal5);
forestNotebook.addAnimal(animal6);
forestNotebook.addAnimal(lion);
lineGenerator();
System.out.println("TOTAL PLANTS AND ANIMALS");
lineGenerator();
System.out.println("Plants -> " + forestNotebook.getPlantCount());
System.out.println("Animals -> " + forestNotebook.getAnimalCount());
lineGenerator();
System.out.println("UNSORTED LIST OF PLANTS AND ANIMALS");
lineGenerator();
forestNotebook.printNotebook();
lineGenerator();
System.out.println("LIST OF CARNIVORE, OMNIVORE AND HERBIVORE ANIMALS");
lineGenerator();
forestNotebook.getCarnivores().forEach(System.out::println);
forestNotebook.getOmnivores().forEach(System.out::println);
forestNotebook.getHerbivores().forEach(System.out::println);
lineGenerator();
System.out.println("LIST OF PLANTS AND ANIMALS SORTED BY NAME");
lineGenerator();
forestNotebook.sortAnimalsByName();
forestNotebook.sortPlantsByName();
forestNotebook.printNotebook();
// Ik heb alle metingen omgezet naar meters om correct te kunnen sorteren.
lineGenerator();
System.out.println("BONUS - LIST OF PLANTS AND ANIMALS SORTED BY HEIGHT");
lineGenerator();
forestNotebook.sortAnimalsByHeight();
forestNotebook.sortPlantsHeight();
forestNotebook.printNotebook();
}
public static void lineGenerator() {
System.out.println("-".repeat(100));
}
}
|
169752_11 | package be.intecbrussel.Opdrachten;
import java.time.LocalTime;
import java.util.Comparator;
import java.util.Random;
import java.util.function.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class MainApp {
public static void main(String[] args) {
System.out.println("---- Opdracht - 1 ----\n");
// Doe de voorbeeldjes na van de Consumer, Supplier, Function en Runnable.
// Consumer:
Consumer<String> function = (String food) -> System.out.println("Eating a " + food);
function.accept("cookie");
// Supplier:
Supplier<String> function1 = () -> {
String time = LocalTime.now().toString();
return "The time right now is: " + time;
};
System.out.println(function1.get());
// Function:
Function<String, Integer> function2 = (a) -> a.length();
System.out.println(function2.apply("cookie"));
// Runnable:
Runnable function3 = () -> System.out.println("Hello");
function3.run();
System.out.println("---- Opdracht - 2 ----\n");
// Maak een Consumer Object waarbij dat je de leeftijd van de gebruiker moet vragen.
// Als die jonger is dan 18 jaar, dan print de functie: “You’re too young!”
// Als die ouder is dan 17 jaar, dant print de functie: “You’re too old.
Consumer<Integer> leeftijd = (Integer age) -> {
if (age < 18) {
System.out.println("You're too young.");
} else if (age > 18) {
System.out.println("You're too old.");
} else {
System.out.println("Invalid age!");
}
};
leeftijd.accept(20);
System.out.println("---- Opdracht - 3 ----\n");
// Maak Een Supplier die een randomNumber tussen 1 en 4 genereert.
// Die randomNumber wordt gebruikt in een Function.
// Deze functie geeft je dan de correcte percentage waarde terug in een Sysout.
// Bvb.: 1 -> 25%. 4-> 100%
Supplier<Integer> randomNumber = () -> new Random().nextInt(1, 5);
Function<Integer, String> percentage = (number) -> number * 25 + "%";
System.out.println(percentage.apply(randomNumber.get()));
System.out.println("---- Opdracht - 4 ----\n");
// Zoek een manier om 2 waarden mee te geven aan een Consumer en een Function.
// Je gaat hiervoor moeten googlen.
System.out.println("BiConsumer");
// BiConsumer
BiConsumer<Integer, Double> biConsumer = (n, n2) -> System.out.println(n + n2);
biConsumer.accept(2, 5.5);
System.out.println("\nBiFunction");
// BiFunction
BiFunction<Integer, Double, Double> biFunction = (intNumber, doubleNumber) -> intNumber * doubleNumber;
System.out.println(biFunction.apply(5,3.0));
System.out.println("---- Opdracht - 5 ----\n");
// We gaan lambda’s nu toepassen op Streams.
// Copy-paste volgende lijn, en vul de Stream aan met lambdas.
// Je gaat enkel de getallen afprinten die deelbaar zijn door 8, nadat je ze gedeeld hebt door 4:
// IntStream.of(5,8,640,1111,27,16).
IntStream.of(5,8,640,1111,27,16)
.map(value -> value / 4)
.filter(value -> value % 8 == 0)
.forEach(value -> System.out.println("Numbers divisible by 8:\n" + value));
System.out.println("---- Opdracht - 6 ----\n");
// Onderstaande Array kopieer je.
//
// String [] animals = {"Cow","ShaRk", "DOg","PirAnha", "MouSE", "CaT","ParRoT","DOLphin"};
//
// Plaats deze array in een nieuwe array(Gebruik toArray).
// Alle dieren moeten in lowercase staan, En je houdt enkel de dieren die de letter ‘a’ in hun naam hebben.
// Bonus: Je gaat nu ook de array moeten sorteren op basis van de lengte van het woord. (Hint: Comparator.)
String[] animals = {"Cow", "ShaRk", "DOg", "PirAnha", "MouSE", "CaT", "ParRoT", "DOLphin"};
String[] newAnimals = Stream.of(animals).toArray(String[]::new);
Stream.of(newAnimals)
.map(animal -> animal.toLowerCase())
.filter(animal -> animal.contains("a"))
.sorted(Comparator.comparing(animal -> animal.length()))
.forEach(animal -> System.out.println(animal));
System.out.println("---- Opdracht - 7 ----\n");
// Deze opdracht heb je al eens gedaan.
// Doe deze nu eens opnieuw, maar dit keer gebruik je streams om de resultaten af te printen:
ShoePair nike = new ShoePair("Nike", false, "white", 41, 69.99);
ShoePair timberLand = new ShoePair("Timberland", true, "brown", 41, 219.99);
ShoePair balenciaga = new ShoePair("Balenciaga",true,"black", 45, 429.99);
ShoePair nike2 = new ShoePair("Nike",true,"white", 42,29.99);
ShoePair timberLand2 = new ShoePair("TimberLand",true,"black", 39, 170);
ShoePair balenciaga2 = new ShoePair("Balenciaga",false,"black", 45, 50);
ShoePair nike3 = new ShoePair("Nike",true,"white", 41, 79.99);
ShoePair timberLand3 = new ShoePair("TimberLand",true,"yellow", 41, 80);
ShoePair balenciaga3 = new ShoePair("Balenciaga",false,"black", 37, 349.99);
ShoePair [] shoePairs = {nike,timberLand,balenciaga,nike2,timberLand2,balenciaga2,nike3,timberLand3,balenciaga3};
Stream.of(shoePairs)
.filter(shoes -> shoes.getSize() == 41)
.filter(shoes -> shoes.isComplete())
.forEach(shoes -> System.out.println(shoes));
}
}
| Gabe-Alvess/Lambda | src/be/intecbrussel/Opdrachten/MainApp.java | 1,805 | // Copy-paste volgende lijn, en vul de Stream aan met lambdas. | line_comment | nl | package be.intecbrussel.Opdrachten;
import java.time.LocalTime;
import java.util.Comparator;
import java.util.Random;
import java.util.function.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class MainApp {
public static void main(String[] args) {
System.out.println("---- Opdracht - 1 ----\n");
// Doe de voorbeeldjes na van de Consumer, Supplier, Function en Runnable.
// Consumer:
Consumer<String> function = (String food) -> System.out.println("Eating a " + food);
function.accept("cookie");
// Supplier:
Supplier<String> function1 = () -> {
String time = LocalTime.now().toString();
return "The time right now is: " + time;
};
System.out.println(function1.get());
// Function:
Function<String, Integer> function2 = (a) -> a.length();
System.out.println(function2.apply("cookie"));
// Runnable:
Runnable function3 = () -> System.out.println("Hello");
function3.run();
System.out.println("---- Opdracht - 2 ----\n");
// Maak een Consumer Object waarbij dat je de leeftijd van de gebruiker moet vragen.
// Als die jonger is dan 18 jaar, dan print de functie: “You’re too young!”
// Als die ouder is dan 17 jaar, dant print de functie: “You’re too old.
Consumer<Integer> leeftijd = (Integer age) -> {
if (age < 18) {
System.out.println("You're too young.");
} else if (age > 18) {
System.out.println("You're too old.");
} else {
System.out.println("Invalid age!");
}
};
leeftijd.accept(20);
System.out.println("---- Opdracht - 3 ----\n");
// Maak Een Supplier die een randomNumber tussen 1 en 4 genereert.
// Die randomNumber wordt gebruikt in een Function.
// Deze functie geeft je dan de correcte percentage waarde terug in een Sysout.
// Bvb.: 1 -> 25%. 4-> 100%
Supplier<Integer> randomNumber = () -> new Random().nextInt(1, 5);
Function<Integer, String> percentage = (number) -> number * 25 + "%";
System.out.println(percentage.apply(randomNumber.get()));
System.out.println("---- Opdracht - 4 ----\n");
// Zoek een manier om 2 waarden mee te geven aan een Consumer en een Function.
// Je gaat hiervoor moeten googlen.
System.out.println("BiConsumer");
// BiConsumer
BiConsumer<Integer, Double> biConsumer = (n, n2) -> System.out.println(n + n2);
biConsumer.accept(2, 5.5);
System.out.println("\nBiFunction");
// BiFunction
BiFunction<Integer, Double, Double> biFunction = (intNumber, doubleNumber) -> intNumber * doubleNumber;
System.out.println(biFunction.apply(5,3.0));
System.out.println("---- Opdracht - 5 ----\n");
// We gaan lambda’s nu toepassen op Streams.
// Copy-paste volgende<SUF>
// Je gaat enkel de getallen afprinten die deelbaar zijn door 8, nadat je ze gedeeld hebt door 4:
// IntStream.of(5,8,640,1111,27,16).
IntStream.of(5,8,640,1111,27,16)
.map(value -> value / 4)
.filter(value -> value % 8 == 0)
.forEach(value -> System.out.println("Numbers divisible by 8:\n" + value));
System.out.println("---- Opdracht - 6 ----\n");
// Onderstaande Array kopieer je.
//
// String [] animals = {"Cow","ShaRk", "DOg","PirAnha", "MouSE", "CaT","ParRoT","DOLphin"};
//
// Plaats deze array in een nieuwe array(Gebruik toArray).
// Alle dieren moeten in lowercase staan, En je houdt enkel de dieren die de letter ‘a’ in hun naam hebben.
// Bonus: Je gaat nu ook de array moeten sorteren op basis van de lengte van het woord. (Hint: Comparator.)
String[] animals = {"Cow", "ShaRk", "DOg", "PirAnha", "MouSE", "CaT", "ParRoT", "DOLphin"};
String[] newAnimals = Stream.of(animals).toArray(String[]::new);
Stream.of(newAnimals)
.map(animal -> animal.toLowerCase())
.filter(animal -> animal.contains("a"))
.sorted(Comparator.comparing(animal -> animal.length()))
.forEach(animal -> System.out.println(animal));
System.out.println("---- Opdracht - 7 ----\n");
// Deze opdracht heb je al eens gedaan.
// Doe deze nu eens opnieuw, maar dit keer gebruik je streams om de resultaten af te printen:
ShoePair nike = new ShoePair("Nike", false, "white", 41, 69.99);
ShoePair timberLand = new ShoePair("Timberland", true, "brown", 41, 219.99);
ShoePair balenciaga = new ShoePair("Balenciaga",true,"black", 45, 429.99);
ShoePair nike2 = new ShoePair("Nike",true,"white", 42,29.99);
ShoePair timberLand2 = new ShoePair("TimberLand",true,"black", 39, 170);
ShoePair balenciaga2 = new ShoePair("Balenciaga",false,"black", 45, 50);
ShoePair nike3 = new ShoePair("Nike",true,"white", 41, 79.99);
ShoePair timberLand3 = new ShoePair("TimberLand",true,"yellow", 41, 80);
ShoePair balenciaga3 = new ShoePair("Balenciaga",false,"black", 37, 349.99);
ShoePair [] shoePairs = {nike,timberLand,balenciaga,nike2,timberLand2,balenciaga2,nike3,timberLand3,balenciaga3};
Stream.of(shoePairs)
.filter(shoes -> shoes.getSize() == 41)
.filter(shoes -> shoes.isComplete())
.forEach(shoes -> System.out.println(shoes));
}
}
|
31684_4 | package be.intecbrussel;
public class GithubArrayOef {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening - 1 ----");
// Creëer op 2 manieren een array.
int[] myArr = new int[10];
myArr[5] = 10;
System.out.println("Eerste manier -> " + myArr[5]);
String[] strArr = {"Jos", "Bob", "Mark", "Jules"};
System.out.println("Tweede manier -> " + strArr[0]);
// Met datatype van double en char.
double[] doubleArr = {15.5, 20.5, 35.5};
char[] charArr = {'a', 'b', 'c', 'd'};
// Druk 1 element van beide array's af in de command lijn.
System.out.println("data type double -> " + doubleArr[1] + "\n" + "data type char -> " + charArr[3]);
System.out.println("---- Oefening - 2 ----");
// 1. Creëer een String array met 5 elementen.
String[] strArray = {"ferrari", "lambhorgni", "bugatti", "mercerdes", "audi"};
// 2. Druk 1 element af in de commando lijn.
System.out.println("One element of the array -> " + strArray[2]);
// 3. Druk de lengte van je array af.
System.out.println("Array lenght -> " + strArray.length);
System.out.println("---- Oefening - 3 ----");
// 1. Schrijf een programma om de even en oneven nummer te vinden in een int array.
int[] numArray = {1,2,3,4,5,6,7,8,9,10,11};
int evenCounter = 0;
int oddCounter = 0;
for (int evenOrOdd : numArray) {
if (evenOrOdd % 2 == 0) {
evenCounter++;
} else {
oddCounter++;
}
}
System.out.println("Number of even numbers -> " + evenCounter + "\n" + "number of odd numbers -> " + oddCounter);
}
}
| Gabe-Alvess/LesArrays | src/be/intecbrussel/GithubArrayOef.java | 595 | // 2. Druk 1 element af in de commando lijn. | line_comment | nl | package be.intecbrussel;
public class GithubArrayOef {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening - 1 ----");
// Creëer op 2 manieren een array.
int[] myArr = new int[10];
myArr[5] = 10;
System.out.println("Eerste manier -> " + myArr[5]);
String[] strArr = {"Jos", "Bob", "Mark", "Jules"};
System.out.println("Tweede manier -> " + strArr[0]);
// Met datatype van double en char.
double[] doubleArr = {15.5, 20.5, 35.5};
char[] charArr = {'a', 'b', 'c', 'd'};
// Druk 1 element van beide array's af in de command lijn.
System.out.println("data type double -> " + doubleArr[1] + "\n" + "data type char -> " + charArr[3]);
System.out.println("---- Oefening - 2 ----");
// 1. Creëer een String array met 5 elementen.
String[] strArray = {"ferrari", "lambhorgni", "bugatti", "mercerdes", "audi"};
// 2. Druk<SUF>
System.out.println("One element of the array -> " + strArray[2]);
// 3. Druk de lengte van je array af.
System.out.println("Array lenght -> " + strArray.length);
System.out.println("---- Oefening - 3 ----");
// 1. Schrijf een programma om de even en oneven nummer te vinden in een int array.
int[] numArray = {1,2,3,4,5,6,7,8,9,10,11};
int evenCounter = 0;
int oddCounter = 0;
for (int evenOrOdd : numArray) {
if (evenOrOdd % 2 == 0) {
evenCounter++;
} else {
oddCounter++;
}
}
System.out.println("Number of even numbers -> " + evenCounter + "\n" + "number of odd numbers -> " + oddCounter);
}
}
|
11567_5 | package be.intecbrussel;
public class Person {
/*
Access Modifiers:
* Public -> Overal toegankelijk, vanuit elke klas, package of buiten de package.
* Private -> Toegankelijk binnen de klassen waar deze gedefinieerd is. Niet toegankelijk van buiten uit de klas.
* Protected -> Alleen toegankelijk voor klassen binnen het huidige pakket en buiten de package door subclasses.
* Default or Package -> Alleen toegankelijk binnenin de package. Wanneer er geen access modifiers is opgegeven is dit de standaard.
*/
private String name; // -> Property. Private = Access Modifier
private int age; // -> Property
// Constructors
// No-args constructor
public Person() {
}
// Constructor met 1 parameter
public Person(String name) {
setName(name);
}
// All-args constructor
public Person(String name, int age) {
setName(name);
setAge(age);
}
// Methods
// Void is een return type maar, het geeft niks terug. Void betekent gewoon dat dit gaat een waarde vragen en dan opslagen of een functie uitvoeren.
// Dat is het. Hij gaat die waarde niet terug geven aan iets anders. Hij gaat gewoon zijn taak doen.
// Het gaat dit waarde niet terug geven. VB: setter.
public void presentYourself() {
String sentence = buildPresentationSentence();
System.out.println(sentence);
}
private String buildPresentationSentence() { // private hulpmethode
return "I am " + name + " and I am " + age + " years old.";
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Setters
// public void setAge(int age) {
// age = age;
// } -> probleem
// public void setAge(int ageToSet) {
// age = ageToSet;
// } -> oplossing 1
// public void setAge(int age) { // -> parameter
// this.age = age;
// } -> oplossing 2 -> this.age verwijst naar de property van de class en niet naar de parameter van de setter
// public void setAge(int age) { // -> parameter
// if (age >= 0) {
// this.age = age;
// } else {
// this.age = -age;
// }
// }
// public void setAge(int age) { // -> parameter
// if (age >= 0) {
// this.age = age;
// } else {
// this.age = Math.abs(age); geen else if nodig
// }
// }
public void setAge(int age) { // -> parameter
this.age = Math.abs(age);
} // -> beste oplossing!!!
public void setName(String name) {
// if (!name.isBlank() && name.length() > 0) {
// this.name = name.trim();
// } -> oplossing 1
// if (name.trim().length() > 0) {
// this.name = name.trim();
// } -> oplossing 2
String trimmedName = name.trim();
if (trimmedName.length() > 0) {
this.name = trimmedName;
} else {
this.name = "NO NAME";
} // -> Dry -> Don't repeat yourself. Beste oplossing!!!!
}
// Static methodes
/*
Het verschil tussen static methodes en instance methodes
INSTANCE METHODES:
* Heeft een object van een klas nodig.
* Heeft toegang tot alle fields in een klas.
* De methode is alleen maar toegankelijk door een object referentie.
* Syntax: ObjectName.methodName()
STATIC METHODES:
* Heeft geen object van een klas nodig.
* Heeft alleen toegang tot alle static fields in een klas.
* De methode is alleen toegankelijk door de klas naam.
* Syntax: className.methodName()
*/
// Een non-static method
public void messageNonStatic() {
System.out.println("Hi, from non-static method");
}
// Een static method
public static void messageStatic() {
System.out.println("Hi, from static method");
}
}
| Gabe-Alvess/LesClassesManuel | src/be/intecbrussel/Person.java | 1,170 | // Het gaat dit waarde niet terug geven. VB: setter. | line_comment | nl | package be.intecbrussel;
public class Person {
/*
Access Modifiers:
* Public -> Overal toegankelijk, vanuit elke klas, package of buiten de package.
* Private -> Toegankelijk binnen de klassen waar deze gedefinieerd is. Niet toegankelijk van buiten uit de klas.
* Protected -> Alleen toegankelijk voor klassen binnen het huidige pakket en buiten de package door subclasses.
* Default or Package -> Alleen toegankelijk binnenin de package. Wanneer er geen access modifiers is opgegeven is dit de standaard.
*/
private String name; // -> Property. Private = Access Modifier
private int age; // -> Property
// Constructors
// No-args constructor
public Person() {
}
// Constructor met 1 parameter
public Person(String name) {
setName(name);
}
// All-args constructor
public Person(String name, int age) {
setName(name);
setAge(age);
}
// Methods
// Void is een return type maar, het geeft niks terug. Void betekent gewoon dat dit gaat een waarde vragen en dan opslagen of een functie uitvoeren.
// Dat is het. Hij gaat die waarde niet terug geven aan iets anders. Hij gaat gewoon zijn taak doen.
// Het gaat<SUF>
public void presentYourself() {
String sentence = buildPresentationSentence();
System.out.println(sentence);
}
private String buildPresentationSentence() { // private hulpmethode
return "I am " + name + " and I am " + age + " years old.";
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Setters
// public void setAge(int age) {
// age = age;
// } -> probleem
// public void setAge(int ageToSet) {
// age = ageToSet;
// } -> oplossing 1
// public void setAge(int age) { // -> parameter
// this.age = age;
// } -> oplossing 2 -> this.age verwijst naar de property van de class en niet naar de parameter van de setter
// public void setAge(int age) { // -> parameter
// if (age >= 0) {
// this.age = age;
// } else {
// this.age = -age;
// }
// }
// public void setAge(int age) { // -> parameter
// if (age >= 0) {
// this.age = age;
// } else {
// this.age = Math.abs(age); geen else if nodig
// }
// }
public void setAge(int age) { // -> parameter
this.age = Math.abs(age);
} // -> beste oplossing!!!
public void setName(String name) {
// if (!name.isBlank() && name.length() > 0) {
// this.name = name.trim();
// } -> oplossing 1
// if (name.trim().length() > 0) {
// this.name = name.trim();
// } -> oplossing 2
String trimmedName = name.trim();
if (trimmedName.length() > 0) {
this.name = trimmedName;
} else {
this.name = "NO NAME";
} // -> Dry -> Don't repeat yourself. Beste oplossing!!!!
}
// Static methodes
/*
Het verschil tussen static methodes en instance methodes
INSTANCE METHODES:
* Heeft een object van een klas nodig.
* Heeft toegang tot alle fields in een klas.
* De methode is alleen maar toegankelijk door een object referentie.
* Syntax: ObjectName.methodName()
STATIC METHODES:
* Heeft geen object van een klas nodig.
* Heeft alleen toegang tot alle static fields in een klas.
* De methode is alleen toegankelijk door de klas naam.
* Syntax: className.methodName()
*/
// Een non-static method
public void messageNonStatic() {
System.out.println("Hi, from non-static method");
}
// Een static method
public static void messageStatic() {
System.out.println("Hi, from static method");
}
}
|
199360_10 | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
// for loop
System.out.println(" ---- For loop ---- ");
System.out.println(" ---- example 1 ---- ");
for (int i = 0; i < 10; i++) {
System.out.println("for loop - sit up: " + i);
}
System.out.println(" ---- example 2 ---- ");
for (int index = 1; index <= 5; index++) {
System.out.println("Hello World");
}
System.out.println(" ---- example 3 ---- ");
for (int index = 10; index >= 0; index--) {
System.out.println("The index is: " + index);
}
// while
System.out.println(" ---- while loop ----");
System.out.println(" ---- example 1 ---- ");
int x = 0;
while (x < 10) {
System.out.println("while loop - sit up: " + x);
x++;
}
System.out.println(" ---- example 2 ---- ");
x = 1;
int sum = 0;
// Exit when x becomes greater than 4
while (x <= 10) {
// summing up x
sum = sum + x;
// Increment the value of x for next iteration
x++;
}
System.out.println("Summation: " + sum);
System.out.println(" ---- example 3 ---- ");
boolean hungry = true;
int count = 0;
System.out.println("Take flour");
System.out.println("Add milk");
System.out.println("Add eggs");
System.out.println("Mix ingredients");
while (hungry) {
++count;
System.out.println("Bake pancake " + count);
System.out.println("Eat pancake " + count);
if(count == 4 ) {
hungry = false;
}
}
// do-while
System.out.println(" --- do while loop --- ");
System.out.println(" ---- example 1 ---- ");
// wordt minstens 1 keer uitgevoerd
int y = 0;
do {
System.out.println("do while loop - sit up: " + y);
y++;
} while (y < 10);
System.out.println(" ---- example 2 ---- ");
int index = 10;
do {
// Body of do-while loop
System.out.println("Hello World");
// Update expression
index++;
// Test expression
}while (index < 6);
System.out.println(" ---- example 3 ---- ");
x = 21;
sum = 0;
do {
// Execution statements(Body of loop)
// Here, the line will be printed even if the condition is false
sum += x;
x--;
// Now checking condition
} while (x > 10);
// Summing up
System.out.println("Summation: " + sum);
// break keyword
System.out.println(" ---- break ---- ");
for (int i = 0; i < 10; i++) {
System.out.println("i = " + i);
for (int j = 0; j < 10; j++) {
if (j == 5) {
break; // break zal de eerste loop stoppen
}
}
if (i == 5) {
break;
}
}
//label
System.out.println("--- break with label ---");
search: for (int i = 0; i < 10; i++) {
System.out.println("i = " + i);
for (int j = 0; j < 10; j++) {
if (j == 5){
i = 100; // zal eerste loop stoppen
// of
break search; // zal eerste loop stoppen
}
}
}
// continue keyword
System.out.println(" ---- continue ---- ");
for (int i = 0; i < 10; i++) {
if (i % 2 == 0){
continue; // ga terug naar start, i wordt nog steeds verhoogt
}
System.out.println("Odd number: " + i);
}
// label
System.out.println("--- continue with label ---");
start: for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
// if (j == 5){
// continue start;
// }
System.out.println("j = " + j);
}
System.out.println("i = " + i);
}
// infinite loop - danger
// int z = 0;
// while(z < 10){
// System.out.println("infinite loop");
// }
}
}
| Gabe-Alvess/Loops | src/be/intecbrussel/MainApp.java | 1,293 | // zal eerste loop stoppen | line_comment | nl | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
// for loop
System.out.println(" ---- For loop ---- ");
System.out.println(" ---- example 1 ---- ");
for (int i = 0; i < 10; i++) {
System.out.println("for loop - sit up: " + i);
}
System.out.println(" ---- example 2 ---- ");
for (int index = 1; index <= 5; index++) {
System.out.println("Hello World");
}
System.out.println(" ---- example 3 ---- ");
for (int index = 10; index >= 0; index--) {
System.out.println("The index is: " + index);
}
// while
System.out.println(" ---- while loop ----");
System.out.println(" ---- example 1 ---- ");
int x = 0;
while (x < 10) {
System.out.println("while loop - sit up: " + x);
x++;
}
System.out.println(" ---- example 2 ---- ");
x = 1;
int sum = 0;
// Exit when x becomes greater than 4
while (x <= 10) {
// summing up x
sum = sum + x;
// Increment the value of x for next iteration
x++;
}
System.out.println("Summation: " + sum);
System.out.println(" ---- example 3 ---- ");
boolean hungry = true;
int count = 0;
System.out.println("Take flour");
System.out.println("Add milk");
System.out.println("Add eggs");
System.out.println("Mix ingredients");
while (hungry) {
++count;
System.out.println("Bake pancake " + count);
System.out.println("Eat pancake " + count);
if(count == 4 ) {
hungry = false;
}
}
// do-while
System.out.println(" --- do while loop --- ");
System.out.println(" ---- example 1 ---- ");
// wordt minstens 1 keer uitgevoerd
int y = 0;
do {
System.out.println("do while loop - sit up: " + y);
y++;
} while (y < 10);
System.out.println(" ---- example 2 ---- ");
int index = 10;
do {
// Body of do-while loop
System.out.println("Hello World");
// Update expression
index++;
// Test expression
}while (index < 6);
System.out.println(" ---- example 3 ---- ");
x = 21;
sum = 0;
do {
// Execution statements(Body of loop)
// Here, the line will be printed even if the condition is false
sum += x;
x--;
// Now checking condition
} while (x > 10);
// Summing up
System.out.println("Summation: " + sum);
// break keyword
System.out.println(" ---- break ---- ");
for (int i = 0; i < 10; i++) {
System.out.println("i = " + i);
for (int j = 0; j < 10; j++) {
if (j == 5) {
break; // break zal de eerste loop stoppen
}
}
if (i == 5) {
break;
}
}
//label
System.out.println("--- break with label ---");
search: for (int i = 0; i < 10; i++) {
System.out.println("i = " + i);
for (int j = 0; j < 10; j++) {
if (j == 5){
i = 100; // zal eerste loop stoppen
// of
break search; // zal eerste<SUF>
}
}
}
// continue keyword
System.out.println(" ---- continue ---- ");
for (int i = 0; i < 10; i++) {
if (i % 2 == 0){
continue; // ga terug naar start, i wordt nog steeds verhoogt
}
System.out.println("Odd number: " + i);
}
// label
System.out.println("--- continue with label ---");
start: for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
// if (j == 5){
// continue start;
// }
System.out.println("j = " + j);
}
System.out.println("i = " + i);
}
// infinite loop - danger
// int z = 0;
// while(z < 10){
// System.out.println("infinite loop");
// }
}
}
|
58855_1 | package be.intecbrussel;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;
public class Opdrachten {
public static void main(String[] args) {
System.out.println("---- Opdracht 1 - Random integers ----" + "\n");
// - Maak een Random generator en vraag verschillende integers op.
// - Zorg ervoor dat je alleen maar getallen kunt genereren tussen 0 en 99.
// - Maak nu een applicatie die maar 6 getallen opvraagt.
Random random = new Random();
int maxRandomNum = 0;
while (maxRandomNum < 6) {
int randomNumber = random.nextInt(100);
maxRandomNum++;
System.out.println("Random number: " + randomNumber + "\n");
}
// Opdracht 2
// Zelfstudie
System.out.println("---- Opdracht 3 ----" + "\n");
// - Maak een nieuwe Scanner die een String opvraagt.
Scanner scanner = new Scanner(System.in);
System.out.println("Schrijf een word!");
String answer1 = scanner.nextLine().toLowerCase();
// - druk de tekst af in grote letters
String upperCase = answer1.toUpperCase();
System.out.println("Grote letters: " + upperCase + "\n");
// - druk de tekst af in kleine letters
String lowerCase = answer1.toLowerCase();
System.out.println("Kleine letters: " + lowerCase + "\n");
// - Vervang alle ‘e’ door ‘u’
String replacedLetters = answer1.replaceAll("e", "u");
if (answer1.contains("e")) {
System.out.println("Alle letters 'e' vervangen door 'u' = " + replacedLetters + "\n");
} else {
System.out.println("Geen letters (e) gevonden in het word " + answer1 + "\n");
}
// - Druk af hoeveel keer de letter ‘r’ in je String voorkomt
int count = 0;
for (int i = 0; i < answer1.length(); i++ ) {
if (answer1.charAt(i) == 'r') {
count++;
}
}
if (answer1.contains("r")) {
System.out.println("De letter r is " + count + " keer voor gekomen bij het word " + answer1.toLowerCase() + "." + "\n");
} else {
System.out.println("Geen letters (r) gevonden in het word " + answer1 + "\n");
}
// - Maak twee strings en vergelijk ze met elkaar met een String methode.
String string1 = "Tekst";
String string2 = "tekst";
boolean comparison = string1.equalsIgnoreCase(string2);
if (comparison) {
System.out.println("Het word " + string1 + " is gelijk aan het word " + string2 + "\n");
} else {
System.out.println("Het word " + string1 + " is niet gelijk aan aan het word " + string2 + "\n");
}
// - Vergelijk twee Strings alfabetisch, en druk ze allebei af. De String die eerst alfabetisch komt, moet eerst afgedrukt worden.
String string3 = "zebra";
String string4 = "aap";
int firstCodePoint = string3.codePointAt(0);
int secondCodePoint = string4.codePointAt(0);
System.out.println("Strings op alfabetisch volgorde -> 1ste manier " + "\n");
if (firstCodePoint < secondCodePoint) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// Of
int compareResult = string3.compareToIgnoreCase(string4);
System.out.println("Strings op alfabetisch volgorde -> 2de manier " + "\n");
if (compareResult < 0) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// - Maak een string met extra spaties vooraan en achteraan. Druk de string dan af zonder de spaties.
String string5 = " Hello, my name is Gabriel ";
System.out.println("String met spaties: " + "\n" + string5 + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.strip() + " 'met strip()'" + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.trim() + " 'met trim()'" + "\n");
System.out.println("---- Opdracht 4 ----" + "\n");
// - Maak een programma dat twee Strings opvraagt met StringBuilder
System.out.println("Schrijf eerste string");
String input1 = scanner.nextLine();
System.out.println("Schrijf tweede string");
String input2 = scanner.nextLine();
StringBuilder sb1 = new StringBuilder(input1);
StringBuilder sb2 = new StringBuilder(input2);
// - Voeg extra tekst toe aan de eerste StringBuilder
sb1.append(" -> extra text");
System.out.println("1ste StringBuilder met extra tekst: " + sb1 + "\n");
// - Draai de tekst van de 2de StringBuilder om
sb2.reverse();
System.out.println("Tekst van 2de StringBuilder omgedraaid: " + sb2 + "\n");
// - Verwijder alle spaties van de eerste StringBuilder
int i = 0;
while (i < sb1.length()) {
if (sb1.charAt(i) == ' ') {
sb1.deleteCharAt(i);
} else {
i++;
}
}
System.out.println("1ste StringBuilder zonder spaties -> " + sb1 + "\n");
// - Verdubbel iedere letter 't' in de tweede StringBuilder
i = 0;
while (i < sb2.length()) {
if (sb2.charAt(i) == 't') {
sb2.insert(i + 1, 't');
i += 2;
} else {
i++;
}
}
System.out.println("2de StringBuilder met verdubbelde 't': " + sb2 + "\n");
// - Verwijder bij de tweede StringBuilder 2 worden
int firstSpace = sb2.indexOf(" ");
int secondSpace = sb2.indexOf(" ", firstSpace + 1);
sb2.delete(0, secondSpace + 1);
System.out.println("2de StringBuilder zonder 2 woorden: " + sb2 + "\n");
System.out.println("---- Opdracht - 5 ----" + "\n");
// - Maak een programma dat de eenheid ‘meter’ omzet naar de eenheid ‘voet’.
// Toon de waarden van 1 meter tot en met 20 meter (je doet telkens +0.5meter).
// Je mag maar twee cijfers na de komma hebben, en alle getallen moeten mooi naast elkaar gaan.
// Je gaat hier formatting voor moeten gebruiken.
for (double meter = 1.0; meter <= 20.0; meter += 0.5) {
double feet = meter * 3.28;
System.out.println(String.format("%,.2f", meter) + " meter" + " = " + String.format("%,.2f", feet) + " feet" + "\n");
}
}
}
| Gabe-Alvess/OopOpdracht | src/be/intecbrussel/Opdrachten.java | 2,014 | // - Zorg ervoor dat je alleen maar getallen kunt genereren tussen 0 en 99. | line_comment | nl | package be.intecbrussel;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;
public class Opdrachten {
public static void main(String[] args) {
System.out.println("---- Opdracht 1 - Random integers ----" + "\n");
// - Maak een Random generator en vraag verschillende integers op.
// - Zorg<SUF>
// - Maak nu een applicatie die maar 6 getallen opvraagt.
Random random = new Random();
int maxRandomNum = 0;
while (maxRandomNum < 6) {
int randomNumber = random.nextInt(100);
maxRandomNum++;
System.out.println("Random number: " + randomNumber + "\n");
}
// Opdracht 2
// Zelfstudie
System.out.println("---- Opdracht 3 ----" + "\n");
// - Maak een nieuwe Scanner die een String opvraagt.
Scanner scanner = new Scanner(System.in);
System.out.println("Schrijf een word!");
String answer1 = scanner.nextLine().toLowerCase();
// - druk de tekst af in grote letters
String upperCase = answer1.toUpperCase();
System.out.println("Grote letters: " + upperCase + "\n");
// - druk de tekst af in kleine letters
String lowerCase = answer1.toLowerCase();
System.out.println("Kleine letters: " + lowerCase + "\n");
// - Vervang alle ‘e’ door ‘u’
String replacedLetters = answer1.replaceAll("e", "u");
if (answer1.contains("e")) {
System.out.println("Alle letters 'e' vervangen door 'u' = " + replacedLetters + "\n");
} else {
System.out.println("Geen letters (e) gevonden in het word " + answer1 + "\n");
}
// - Druk af hoeveel keer de letter ‘r’ in je String voorkomt
int count = 0;
for (int i = 0; i < answer1.length(); i++ ) {
if (answer1.charAt(i) == 'r') {
count++;
}
}
if (answer1.contains("r")) {
System.out.println("De letter r is " + count + " keer voor gekomen bij het word " + answer1.toLowerCase() + "." + "\n");
} else {
System.out.println("Geen letters (r) gevonden in het word " + answer1 + "\n");
}
// - Maak twee strings en vergelijk ze met elkaar met een String methode.
String string1 = "Tekst";
String string2 = "tekst";
boolean comparison = string1.equalsIgnoreCase(string2);
if (comparison) {
System.out.println("Het word " + string1 + " is gelijk aan het word " + string2 + "\n");
} else {
System.out.println("Het word " + string1 + " is niet gelijk aan aan het word " + string2 + "\n");
}
// - Vergelijk twee Strings alfabetisch, en druk ze allebei af. De String die eerst alfabetisch komt, moet eerst afgedrukt worden.
String string3 = "zebra";
String string4 = "aap";
int firstCodePoint = string3.codePointAt(0);
int secondCodePoint = string4.codePointAt(0);
System.out.println("Strings op alfabetisch volgorde -> 1ste manier " + "\n");
if (firstCodePoint < secondCodePoint) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// Of
int compareResult = string3.compareToIgnoreCase(string4);
System.out.println("Strings op alfabetisch volgorde -> 2de manier " + "\n");
if (compareResult < 0) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// - Maak een string met extra spaties vooraan en achteraan. Druk de string dan af zonder de spaties.
String string5 = " Hello, my name is Gabriel ";
System.out.println("String met spaties: " + "\n" + string5 + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.strip() + " 'met strip()'" + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.trim() + " 'met trim()'" + "\n");
System.out.println("---- Opdracht 4 ----" + "\n");
// - Maak een programma dat twee Strings opvraagt met StringBuilder
System.out.println("Schrijf eerste string");
String input1 = scanner.nextLine();
System.out.println("Schrijf tweede string");
String input2 = scanner.nextLine();
StringBuilder sb1 = new StringBuilder(input1);
StringBuilder sb2 = new StringBuilder(input2);
// - Voeg extra tekst toe aan de eerste StringBuilder
sb1.append(" -> extra text");
System.out.println("1ste StringBuilder met extra tekst: " + sb1 + "\n");
// - Draai de tekst van de 2de StringBuilder om
sb2.reverse();
System.out.println("Tekst van 2de StringBuilder omgedraaid: " + sb2 + "\n");
// - Verwijder alle spaties van de eerste StringBuilder
int i = 0;
while (i < sb1.length()) {
if (sb1.charAt(i) == ' ') {
sb1.deleteCharAt(i);
} else {
i++;
}
}
System.out.println("1ste StringBuilder zonder spaties -> " + sb1 + "\n");
// - Verdubbel iedere letter 't' in de tweede StringBuilder
i = 0;
while (i < sb2.length()) {
if (sb2.charAt(i) == 't') {
sb2.insert(i + 1, 't');
i += 2;
} else {
i++;
}
}
System.out.println("2de StringBuilder met verdubbelde 't': " + sb2 + "\n");
// - Verwijder bij de tweede StringBuilder 2 worden
int firstSpace = sb2.indexOf(" ");
int secondSpace = sb2.indexOf(" ", firstSpace + 1);
sb2.delete(0, secondSpace + 1);
System.out.println("2de StringBuilder zonder 2 woorden: " + sb2 + "\n");
System.out.println("---- Opdracht - 5 ----" + "\n");
// - Maak een programma dat de eenheid ‘meter’ omzet naar de eenheid ‘voet’.
// Toon de waarden van 1 meter tot en met 20 meter (je doet telkens +0.5meter).
// Je mag maar twee cijfers na de komma hebben, en alle getallen moeten mooi naast elkaar gaan.
// Je gaat hier formatting voor moeten gebruiken.
for (double meter = 1.0; meter <= 20.0; meter += 0.5) {
double feet = meter * 3.28;
System.out.println(String.format("%,.2f", meter) + " meter" + " = " + String.format("%,.2f", feet) + " feet" + "\n");
}
}
}
|
186805_2 | package be.intecbrussel;
import be.intecbrussel.DO_NOT_TOUCH.ErrorSystem;
import be.intecbrussel.DO_NOT_TOUCH.InternalApp;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new InternalApp().start(); // DO NOT TOUCH
// Hieronder plaats je de code.
// Met de methode getError(), krijg je een error,
// Met de methode fixError(String error, level), kan je de behandelde error opslaan.
//---------------------------------------------------
Scanner scanner = new Scanner(System.in);
int i = 0;
int input;
String error = "";
System.out.println("\nPlease enter the priority level for all the errors below!\nLevels: 1.LOW - 2.MEDIUM - 3.HIGH - 4.NO_ISSUE ");
while (true) {
i++;
error = getError();
if (error == null) {
break;
}
System.out.println("\n" + i + " - " + error);
input = scanner.nextInt();
while (input < 1 || input > 4) {
System.out.println("Invalid level! Please enter 1, 2, 3, or 4 to give a priority level to the error.");
input = scanner.nextInt();
}
String result = "";
switch (input) {
case 1:
result = "LOW - " + error;
fixError(result, PriorityLevel.LOW.getDescription());
break;
case 2:
result = "MEDIUM - " + error;
fixError(result, PriorityLevel.MEDIUM.getDescription());
break;
case 3:
result = "HIGH - " + error;
fixError(result, PriorityLevel.HIGH.getDescription());
break;
case 4:
result = "NO ISSUE - " + PriorityLevel.NO_ISSUE.getDescription();
System.out.println(result);
break;
}
}
//---------------------------------------------------
printOverview();
}
// ---------------------------
// DO NOT TOUCH ANYTHING BELOW
// ---------------------------
private static String getError() {
return ErrorSystem.pollError();
}
private static void fixError(String error, Object level) {
ErrorSystem.handledError(error, level);
}
private static void printOverview(){
System.out.println("---------------------------\n");
System.out.println(" HANDLED ERROR \n");
System.out.println("---------------------------\n");
for (String handledError : ErrorSystem.getHandledErrors()) {
System.out.println(handledError);
}
System.out.println("---------------------------\n");
System.out.println(" UNHANDLED ERROR \n");
System.out.println("---------------------------\n");
for (String unHandledError : ErrorSystem.getUnHandledErrors()) {
System.out.println(unHandledError);
}
}
} | Gabe-Alvess/Opdracht_ErrorSystem | src/be/intecbrussel/Main.java | 837 | // Met de methode getError(), krijg je een error, | line_comment | nl | package be.intecbrussel;
import be.intecbrussel.DO_NOT_TOUCH.ErrorSystem;
import be.intecbrussel.DO_NOT_TOUCH.InternalApp;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new InternalApp().start(); // DO NOT TOUCH
// Hieronder plaats je de code.
// Met de<SUF>
// Met de methode fixError(String error, level), kan je de behandelde error opslaan.
//---------------------------------------------------
Scanner scanner = new Scanner(System.in);
int i = 0;
int input;
String error = "";
System.out.println("\nPlease enter the priority level for all the errors below!\nLevels: 1.LOW - 2.MEDIUM - 3.HIGH - 4.NO_ISSUE ");
while (true) {
i++;
error = getError();
if (error == null) {
break;
}
System.out.println("\n" + i + " - " + error);
input = scanner.nextInt();
while (input < 1 || input > 4) {
System.out.println("Invalid level! Please enter 1, 2, 3, or 4 to give a priority level to the error.");
input = scanner.nextInt();
}
String result = "";
switch (input) {
case 1:
result = "LOW - " + error;
fixError(result, PriorityLevel.LOW.getDescription());
break;
case 2:
result = "MEDIUM - " + error;
fixError(result, PriorityLevel.MEDIUM.getDescription());
break;
case 3:
result = "HIGH - " + error;
fixError(result, PriorityLevel.HIGH.getDescription());
break;
case 4:
result = "NO ISSUE - " + PriorityLevel.NO_ISSUE.getDescription();
System.out.println(result);
break;
}
}
//---------------------------------------------------
printOverview();
}
// ---------------------------
// DO NOT TOUCH ANYTHING BELOW
// ---------------------------
private static String getError() {
return ErrorSystem.pollError();
}
private static void fixError(String error, Object level) {
ErrorSystem.handledError(error, level);
}
private static void printOverview(){
System.out.println("---------------------------\n");
System.out.println(" HANDLED ERROR \n");
System.out.println("---------------------------\n");
for (String handledError : ErrorSystem.getHandledErrors()) {
System.out.println(handledError);
}
System.out.println("---------------------------\n");
System.out.println(" UNHANDLED ERROR \n");
System.out.println("---------------------------\n");
for (String unHandledError : ErrorSystem.getUnHandledErrors()) {
System.out.println(unHandledError);
}
}
} |
126690_6 | package be.intectbrussel;
public class Oefenreeks1 {
public static void main(String[] args) {
System.out.println("Operators - Oefenreeks - 1");
System.out.println("---- Oefening - 1 ----");
// 1. Declareer twee integer variabelen, "a" en "b", en geef ze de waarden 5 en 10.
int a = 5;
int b = 10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de plus operator (+) om de som van "a" en "b" te berekenen en print het resultaat.
int res = a + b;
System.out.println("Som resultaat = " + res);
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de min operator (-) om het verschil tussen "a" en "b" te berekenen en print het resultaat.
res = a - b;
System.out.println("Aftrekking resultaat = " + res);
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de maal operator (*) om het product van "a" en "b" te berekenen en print het resultaat.
res = a * b;
System.out.println("Vermenigvuldiging resultaat = " + res);
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de gedeeld door operator (/) om het quotient van "a" en "b" te berekenen en print het resultaat.
res = a / b;
System.out.println("Deling resultaat = " + res);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de modulo operator (%) om de rest van "a" gedeeld door "b" te berekenen en print het resultaat.
res = a % b;
System.out.println("Rest resultaat = " + res);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik de increment operator (++) om de waarde van "a" te verhogen met 1 en print het resultaat.
int inc = ++a;
System.out.println("Verhoogde resultaat = " + inc);
System.out.println("---- Oefening - 8 ----");
// 8. Gebruik de decrement operator (--) om de waarde van "a" te verlagen met 1 en print het resultaat.
int dec = --a;
System.out.println("Verlaagde resultaat = " + dec);
System.out.println("---- Oefening - 9 ----");
// 9. Gebruik de gelijk aan vergelijkingsoperator (==) om te controleren of "a" gelijk is aan "b" en print het resultaat.
Boolean boolRes = a == b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
System.out.println("---- Oefening - 10 ----");
// 10. Gebruik de niet gelijk aan vergelijkingsoperator (!=) om te controleren of "a" ongelijk is aan "b" en print het resultaat.
boolRes = a != b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
}
}
| Gabe-Alvess/OperatorsOefening | src/be/intectbrussel/Oefenreeks1.java | 888 | // 7. Gebruik de increment operator (++) om de waarde van "a" te verhogen met 1 en print het resultaat. | line_comment | nl | package be.intectbrussel;
public class Oefenreeks1 {
public static void main(String[] args) {
System.out.println("Operators - Oefenreeks - 1");
System.out.println("---- Oefening - 1 ----");
// 1. Declareer twee integer variabelen, "a" en "b", en geef ze de waarden 5 en 10.
int a = 5;
int b = 10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de plus operator (+) om de som van "a" en "b" te berekenen en print het resultaat.
int res = a + b;
System.out.println("Som resultaat = " + res);
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de min operator (-) om het verschil tussen "a" en "b" te berekenen en print het resultaat.
res = a - b;
System.out.println("Aftrekking resultaat = " + res);
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de maal operator (*) om het product van "a" en "b" te berekenen en print het resultaat.
res = a * b;
System.out.println("Vermenigvuldiging resultaat = " + res);
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de gedeeld door operator (/) om het quotient van "a" en "b" te berekenen en print het resultaat.
res = a / b;
System.out.println("Deling resultaat = " + res);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de modulo operator (%) om de rest van "a" gedeeld door "b" te berekenen en print het resultaat.
res = a % b;
System.out.println("Rest resultaat = " + res);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik<SUF>
int inc = ++a;
System.out.println("Verhoogde resultaat = " + inc);
System.out.println("---- Oefening - 8 ----");
// 8. Gebruik de decrement operator (--) om de waarde van "a" te verlagen met 1 en print het resultaat.
int dec = --a;
System.out.println("Verlaagde resultaat = " + dec);
System.out.println("---- Oefening - 9 ----");
// 9. Gebruik de gelijk aan vergelijkingsoperator (==) om te controleren of "a" gelijk is aan "b" en print het resultaat.
Boolean boolRes = a == b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
System.out.println("---- Oefening - 10 ----");
// 10. Gebruik de niet gelijk aan vergelijkingsoperator (!=) om te controleren of "a" ongelijk is aan "b" en print het resultaat.
boolRes = a != b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
}
}
|
52524_1 | package be.intecbrussel;
import java.util.Random;
import java.util.Scanner; // package importeren !!!!!!
public class MainApp {
public static void main(String[] args) {
// maak instantie van de Scanner class, genaamd myScanner
// Scanner myScanner = new Scanner(System.in);
// System.out.print("Vul hier je naam in: ");
// String name = myScanner.nextLine();
//
// System.out.print("Vul uw familienaam in: ");
// String achternaam = myScanner.nextLine();
//
// System.out.print("Vul uw leeftijd in: ");
// int age = myScanner.nextInt();
//
// System.out.print("Ben je een man: ");
// boolean isMale = myScanner.nextBoolean();
//
// System.out.print("Wat is uw lengte in meters: ");
// double lenght = myScanner.nextDouble();
//
// System.out.print("Vul een long waarde in: ");
// long largeNumber = myScanner.nextLong();
// Math clas -> static class = altijd aanwezig
// abs methode
double x = -10.5;
double res = Math.abs(x);
System.out.println("Absolute waarde van x is: " + res);
// min max
double i = 10;
double j = 20;
double min = Math.min(i, j);
double max = Math.max(i, j);
System.out.println("de grootste waarde is: " + max);
System.out.println("de kleinste waarde is: " + min);
// round
x = 10.5;
res = Math.round(x);
System.out.println("Afgerond naar het dichtsbijzijnde gehele getal: " + res);
// ceil -> gaat altijd naar boven afronden
x = 10.1;
res = Math.ceil(x);
System.out.println("Afgerond naar boven : " + res);
// floor -> afronden naar beneden
x = 10.9;
res = Math.floor(x);
System.out.println("Afgerond naar benenden: " + res);
// random
Random random = new Random();
// int tussen 0 tot 100(exclusief)System.out.println("Random number: " + randonNumber);
int randonNumber = 0;
while (randonNumber != 1) {
randonNumber = random.nextInt(101);
System.out.println(randonNumber);
}
// random double
double randomDecimalNumber = random.nextDouble(10, 20);
System.out.println("Random decimal number: " + randomDecimalNumber);
// random float
float randonFloatNumber = random.nextFloat(5, 10);
System.out.println("Random float number: " + randonFloatNumber);
// random boolean
boolean randomBoolean = random.nextBoolean();
System.out.println("Random boolean: " + randomBoolean);
}
}
| Gabe-Alvess/ScannerMathRandom | src/be/intecbrussel/MainApp.java | 809 | // maak instantie van de Scanner class, genaamd myScanner | line_comment | nl | package be.intecbrussel;
import java.util.Random;
import java.util.Scanner; // package importeren !!!!!!
public class MainApp {
public static void main(String[] args) {
// maak instantie<SUF>
// Scanner myScanner = new Scanner(System.in);
// System.out.print("Vul hier je naam in: ");
// String name = myScanner.nextLine();
//
// System.out.print("Vul uw familienaam in: ");
// String achternaam = myScanner.nextLine();
//
// System.out.print("Vul uw leeftijd in: ");
// int age = myScanner.nextInt();
//
// System.out.print("Ben je een man: ");
// boolean isMale = myScanner.nextBoolean();
//
// System.out.print("Wat is uw lengte in meters: ");
// double lenght = myScanner.nextDouble();
//
// System.out.print("Vul een long waarde in: ");
// long largeNumber = myScanner.nextLong();
// Math clas -> static class = altijd aanwezig
// abs methode
double x = -10.5;
double res = Math.abs(x);
System.out.println("Absolute waarde van x is: " + res);
// min max
double i = 10;
double j = 20;
double min = Math.min(i, j);
double max = Math.max(i, j);
System.out.println("de grootste waarde is: " + max);
System.out.println("de kleinste waarde is: " + min);
// round
x = 10.5;
res = Math.round(x);
System.out.println("Afgerond naar het dichtsbijzijnde gehele getal: " + res);
// ceil -> gaat altijd naar boven afronden
x = 10.1;
res = Math.ceil(x);
System.out.println("Afgerond naar boven : " + res);
// floor -> afronden naar beneden
x = 10.9;
res = Math.floor(x);
System.out.println("Afgerond naar benenden: " + res);
// random
Random random = new Random();
// int tussen 0 tot 100(exclusief)System.out.println("Random number: " + randonNumber);
int randonNumber = 0;
while (randonNumber != 1) {
randonNumber = random.nextInt(101);
System.out.println(randonNumber);
}
// random double
double randomDecimalNumber = random.nextDouble(10, 20);
System.out.println("Random decimal number: " + randomDecimalNumber);
// random float
float randonFloatNumber = random.nextFloat(5, 10);
System.out.println("Random float number: " + randonFloatNumber);
// random boolean
boolean randomBoolean = random.nextBoolean();
System.out.println("Random boolean: " + randomBoolean);
}
}
|
169655_1 | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
System.out.println("Github");
System.out.println(" ---- Oefening 1 ---- ");
// 1. Ken volgende waarde aan een string toe Java Exercises!,
// gebruik nu een functie van de String class en druk
// enkel het volgende woord Exercises af van de variabele.
String les = "Java Exercises!";
System.out.println(les.substring(4, 14));
System.out.println(" ---- Oefening 2 ---- ");
// 2. Maak een string met volgende waarde walter, edwin, mike
// controlleer of de naam edwin voorkomt in de string.
String ListOfNames = "walter, edwin, mike";
System.out.println(ListOfNames.contains("edwin"));
System.out.println("---- Oefening 3 ---- ");
// 3. Maak een string met de volgende waarde hello world maak nu een algoritme dat van de huidige waarde het
// volgende maakt HeLlO WoRlD. Bekijk voor deze oefening zeker de documentatie
// van Class String van oracle en de vorige hoofdstukken.
String sentence = "hello world";
String res = "";
for (int i = 0; i < sentence.length(); i++) {
char indexChar = sentence.charAt(i);
if (i % 2 == 0) {
res += Character.toUpperCase(indexChar);
} else {
res += Character.toLowerCase(indexChar);
}
}
System.out.println(res);
System.out.println("---- String - Oefenreeks 1 ----");
System.out.println("---- Oefening - 1 ----");
// 1. Maak een string aan en print deze naar de console.
String str = "Hello";
System.out.println(str);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de ".length()" eigenschap om de lengte van een string of stringBuilder te bepalen.
String str1 = "Hello World";
System.out.println(str1.length());
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de .substring() methode om een deel van een string of stringBuilder
// te selecteren en print dit naar de console.
String str2 = "Hello World";
System.out.println(str2.substring(6, 11));
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de + operator of de concat() methode om twee strings samen te voegen.
String str3 = "Hello ";
String str4 = "There!";
String strConcat = str3.concat(str4);
System.out.println(strConcat + " -> met .concat()");
System.out.println(str3 + str4 + " -> met + operator");
System.out.println("---- Oefening - 5 ----");
// 5. Maak een programma dat controleert of een String een geldige email address is.
// (email address moet minstens een @ en een . bevatten, de . moet na de @ komen).
String email = "[email protected]";
int atPosition = email.indexOf("@");
int dotPosition = email.indexOf(".");
boolean containsAt = email.contains("@");
boolean containsDot = email.contains(".");
boolean atSmallerThanDot = atPosition < dotPosition;
boolean minAtPosition = atPosition >= 3;
boolean minDotPosition = dotPosition >= 6;
if (containsAt && containsDot && atSmallerThanDot && minAtPosition && minDotPosition) {
System.out.println(email + " ->" + " Is een geldige email address!");
} else {
System.out.println(email + " ->" + " Is een ongeldige email address!");
}
}
}
| Gabe-Alvess/StringOefeningen | src/be/intecbrussel/MainApp.java | 1,045 | // gebruik nu een functie van de String class en druk | line_comment | nl | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
System.out.println("Github");
System.out.println(" ---- Oefening 1 ---- ");
// 1. Ken volgende waarde aan een string toe Java Exercises!,
// gebruik nu<SUF>
// enkel het volgende woord Exercises af van de variabele.
String les = "Java Exercises!";
System.out.println(les.substring(4, 14));
System.out.println(" ---- Oefening 2 ---- ");
// 2. Maak een string met volgende waarde walter, edwin, mike
// controlleer of de naam edwin voorkomt in de string.
String ListOfNames = "walter, edwin, mike";
System.out.println(ListOfNames.contains("edwin"));
System.out.println("---- Oefening 3 ---- ");
// 3. Maak een string met de volgende waarde hello world maak nu een algoritme dat van de huidige waarde het
// volgende maakt HeLlO WoRlD. Bekijk voor deze oefening zeker de documentatie
// van Class String van oracle en de vorige hoofdstukken.
String sentence = "hello world";
String res = "";
for (int i = 0; i < sentence.length(); i++) {
char indexChar = sentence.charAt(i);
if (i % 2 == 0) {
res += Character.toUpperCase(indexChar);
} else {
res += Character.toLowerCase(indexChar);
}
}
System.out.println(res);
System.out.println("---- String - Oefenreeks 1 ----");
System.out.println("---- Oefening - 1 ----");
// 1. Maak een string aan en print deze naar de console.
String str = "Hello";
System.out.println(str);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de ".length()" eigenschap om de lengte van een string of stringBuilder te bepalen.
String str1 = "Hello World";
System.out.println(str1.length());
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de .substring() methode om een deel van een string of stringBuilder
// te selecteren en print dit naar de console.
String str2 = "Hello World";
System.out.println(str2.substring(6, 11));
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de + operator of de concat() methode om twee strings samen te voegen.
String str3 = "Hello ";
String str4 = "There!";
String strConcat = str3.concat(str4);
System.out.println(strConcat + " -> met .concat()");
System.out.println(str3 + str4 + " -> met + operator");
System.out.println("---- Oefening - 5 ----");
// 5. Maak een programma dat controleert of een String een geldige email address is.
// (email address moet minstens een @ en een . bevatten, de . moet na de @ komen).
String email = "[email protected]";
int atPosition = email.indexOf("@");
int dotPosition = email.indexOf(".");
boolean containsAt = email.contains("@");
boolean containsDot = email.contains(".");
boolean atSmallerThanDot = atPosition < dotPosition;
boolean minAtPosition = atPosition >= 3;
boolean minDotPosition = dotPosition >= 6;
if (containsAt && containsDot && atSmallerThanDot && minAtPosition && minDotPosition) {
System.out.println(email + " ->" + " Is een geldige email address!");
} else {
System.out.println(email + " ->" + " Is een ongeldige email address!");
}
}
}
|
50612_2 | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
int x = 10; // stack memory
// literal
String name = "Gabriel"; // heap -> string pool
String name2 = "Gabriel";
name2 = "Alves";
name2 = "Vieira";
// true -> verwijst naar dezelfde plaats in het geheugen
System.out.println(name == name2);
// Object
String name3 = new String("Gabriel");
String name4 = new String("Gabriel");
// vergelijk objecten
System.out.println(name3.equals(name4));
// string methods
// uppercase
name = "Gabriel Alves";
System.out.println(name.toUpperCase());
// lowercase
name = "GABRIEL ALVES";
System.out.println(name.toLowerCase());
// length
name = "Gabriel Alves";
System.out.println(name.length());
// isblank
name = " ";
System.out.println(name.isBlank());
// empty
System.out.println(name.isEmpty());
// replace
name = "Gabriel Alves";
System.out.println(name.replace("G", "g"));
// strip -> verwijder alle spatie voor en achter, geen impact op spaties tussen woorden
name = " Gabriel Alves ";
System.out.println(name.strip());
// stripleading -> spaties vooraan verwijderen
name = " Gabriel Alves ";
System.out.println(name.stripLeading());
// striptrailing -> spaties achteraan verwijderen
name = " Gabriel Alves ";
System.out.println(name.stripTrailing());
// indexOf
name = "Gabriel Alves";
System.out.println(name.indexOf("Alves"));
// contains -> hoofdletter gevolig
String text = "Hello World";
System.out.println(text.contains("world"));
System.out.println(text.toLowerCase().contains("world"));
// substring
System.out.println(text.substring(0, 6));
}
}
| Gabe-Alvess/StringStringMethods | src/be/intecbrussel/MainApp.java | 578 | // strip -> verwijder alle spatie voor en achter, geen impact op spaties tussen woorden | line_comment | nl | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
int x = 10; // stack memory
// literal
String name = "Gabriel"; // heap -> string pool
String name2 = "Gabriel";
name2 = "Alves";
name2 = "Vieira";
// true -> verwijst naar dezelfde plaats in het geheugen
System.out.println(name == name2);
// Object
String name3 = new String("Gabriel");
String name4 = new String("Gabriel");
// vergelijk objecten
System.out.println(name3.equals(name4));
// string methods
// uppercase
name = "Gabriel Alves";
System.out.println(name.toUpperCase());
// lowercase
name = "GABRIEL ALVES";
System.out.println(name.toLowerCase());
// length
name = "Gabriel Alves";
System.out.println(name.length());
// isblank
name = " ";
System.out.println(name.isBlank());
// empty
System.out.println(name.isEmpty());
// replace
name = "Gabriel Alves";
System.out.println(name.replace("G", "g"));
// strip -><SUF>
name = " Gabriel Alves ";
System.out.println(name.strip());
// stripleading -> spaties vooraan verwijderen
name = " Gabriel Alves ";
System.out.println(name.stripLeading());
// striptrailing -> spaties achteraan verwijderen
name = " Gabriel Alves ";
System.out.println(name.stripTrailing());
// indexOf
name = "Gabriel Alves";
System.out.println(name.indexOf("Alves"));
// contains -> hoofdletter gevolig
String text = "Hello World";
System.out.println(text.contains("world"));
System.out.println(text.toLowerCase().contains("world"));
// substring
System.out.println(text.substring(0, 6));
}
}
|
28782_8 | package be.intecbrussel;
import java.util.Random;
public class MainApp {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening 1 ----");
// Maak een applicatie die kan controleren of een bepaald woord een palindroom is.
String word = "meetsysteem";
String wordReverse = "";
StringBuilder str = new StringBuilder(word);
wordReverse = str.reverse().toString();
if (word.equals(wordReverse)) {
System.out.println(word + " = " + wordReverse + ".");
System.out.println(word + " is wel een palindroom!");
} else {
System.out.println(word + " != " + wordReverse + ".");
System.out.println(word + " is geen palindroom!");
}
System.out.println("---- Oefening 2 ----");
// Maak een applicatie die volgende tekst The Quick BroWn FoX!
// Omzet naar enkel kleine letters.
String text = "The Quick BroWn FoX!";
StringBuilder lowercase = new StringBuilder(text.toLowerCase());
System.out.println(lowercase);
System.out.println("---- StringBuilder - oefenreeks 1 ----");
System.out.println("---- Oefening - 1 ----");
// 1. Maak een stringBuilder aan en voeg een string toe. Print de stringBuilder naar de console.
StringBuilder str1 = new StringBuilder("Hello World!");
System.out.println(str1);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de .length() eigenschap om de lengte van een string of stringBuilder te bepalen.
StringBuilder str2 = new StringBuilder("Hello World");
System.out.println(str2.length());
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de .substring() methode om een deel van een string of stringBuilder
// te selecteren en print dit naar de console.
StringBuilder str3 = new StringBuilder("Hello World");
System.out.println(str3.substring(6, 11));
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de .delete() methode om een deel van een stringBuilder te verwijderen.
StringBuilder str4 = new StringBuilder("Hello World Wold");
System.out.println(str4.delete(12,17));
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de .insert() methode om een string toe te voegen aan een specifieke index in een stringBuilder.
StringBuilder str5 = new StringBuilder("Let's");
str5.insert(5, " go");
System.out.println(str5);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de .replace() methode om een specifieke string te vervangen door een andere string in een stringBuilder.
StringBuilder strReplace = new StringBuilder("Hello world!");
strReplace.replace(0,12, "Hallo wereld!");
System.out.println(strReplace);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik de .toString() methode om de inhoud van een stringBuilder om te zetten naar een string.
StringBuilder str6 = new StringBuilder("Hello, my name is Gabriel.");
String str7 = str6.toString();
System.out.println(str7);
System.out.println("---- Oefening - 7 ----");
// 8. Gebruik de .append() methode om een string toe te voegen aan een stringBuilder.
StringBuilder str8 = new StringBuilder("Hi,");
String endOfSentence = " my name is Jos";
str8.append(endOfSentence);
System.out.println(str8);
}
}
| Gabe-Alvess/StringbuilderOefeningen | src/be/intecbrussel/MainApp.java | 1,037 | // 5. Gebruik de .insert() methode om een string toe te voegen aan een specifieke index in een stringBuilder. | line_comment | nl | package be.intecbrussel;
import java.util.Random;
public class MainApp {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening 1 ----");
// Maak een applicatie die kan controleren of een bepaald woord een palindroom is.
String word = "meetsysteem";
String wordReverse = "";
StringBuilder str = new StringBuilder(word);
wordReverse = str.reverse().toString();
if (word.equals(wordReverse)) {
System.out.println(word + " = " + wordReverse + ".");
System.out.println(word + " is wel een palindroom!");
} else {
System.out.println(word + " != " + wordReverse + ".");
System.out.println(word + " is geen palindroom!");
}
System.out.println("---- Oefening 2 ----");
// Maak een applicatie die volgende tekst The Quick BroWn FoX!
// Omzet naar enkel kleine letters.
String text = "The Quick BroWn FoX!";
StringBuilder lowercase = new StringBuilder(text.toLowerCase());
System.out.println(lowercase);
System.out.println("---- StringBuilder - oefenreeks 1 ----");
System.out.println("---- Oefening - 1 ----");
// 1. Maak een stringBuilder aan en voeg een string toe. Print de stringBuilder naar de console.
StringBuilder str1 = new StringBuilder("Hello World!");
System.out.println(str1);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de .length() eigenschap om de lengte van een string of stringBuilder te bepalen.
StringBuilder str2 = new StringBuilder("Hello World");
System.out.println(str2.length());
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de .substring() methode om een deel van een string of stringBuilder
// te selecteren en print dit naar de console.
StringBuilder str3 = new StringBuilder("Hello World");
System.out.println(str3.substring(6, 11));
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de .delete() methode om een deel van een stringBuilder te verwijderen.
StringBuilder str4 = new StringBuilder("Hello World Wold");
System.out.println(str4.delete(12,17));
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik<SUF>
StringBuilder str5 = new StringBuilder("Let's");
str5.insert(5, " go");
System.out.println(str5);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de .replace() methode om een specifieke string te vervangen door een andere string in een stringBuilder.
StringBuilder strReplace = new StringBuilder("Hello world!");
strReplace.replace(0,12, "Hallo wereld!");
System.out.println(strReplace);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik de .toString() methode om de inhoud van een stringBuilder om te zetten naar een string.
StringBuilder str6 = new StringBuilder("Hello, my name is Gabriel.");
String str7 = str6.toString();
System.out.println(str7);
System.out.println("---- Oefening - 7 ----");
// 8. Gebruik de .append() methode om een string toe te voegen aan een stringBuilder.
StringBuilder str8 = new StringBuilder("Hi,");
String endOfSentence = " my name is Jos";
str8.append(endOfSentence);
System.out.println(str8);
}
}
|
19808_1 | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
// Type casting is wanneer je een waarde toewijst van een primitieve datatype naar een ander datatype.
//We kennen 2 manieren om een type casting te doen:
System.out.println(" ---- Widening casting ---- ");
// Widening Casting - omzetten van een kleinere type naar een grotere type.
int myInt = 9;
// Automatische casting: int naar double
double myDouble = myInt;
System.out.println("Integer = " + myInt);
System.out.println("Double = " + myDouble);
// De conversie tussen numeriek datatype naar char of Boolean gebeurt niet automatisch.
// Ook zijn de gegevenstypen char en Boolean niet compatibel met elkaar.
char myChar = 'q';
// compileer fout "incompatible types: char cannot be converted to boolean"
// boolean myBoolean = myChar;
// System.out.println(myChar);
// System.out.println(myBoolean);
System.out.println(" ---- Narrowing casting ---- ");
// Narrowing Casting (handmatig) - een groter type omzetten naar een kleiner formaat type.
double Double = 9.78d;
// Manueel casting: double naar int
int myInteger = (int) Double;
System.out.println("Double = " + Double);
System.out.println("Integer = " + myInteger);
}
}
| Gabe-Alvess/Typecasting | src/be/intecbrussel/MainApp.java | 389 | //We kennen 2 manieren om een type casting te doen: | line_comment | nl | package be.intecbrussel;
public class MainApp {
public static void main(String[] args) {
// Type casting is wanneer je een waarde toewijst van een primitieve datatype naar een ander datatype.
//We kennen<SUF>
System.out.println(" ---- Widening casting ---- ");
// Widening Casting - omzetten van een kleinere type naar een grotere type.
int myInt = 9;
// Automatische casting: int naar double
double myDouble = myInt;
System.out.println("Integer = " + myInt);
System.out.println("Double = " + myDouble);
// De conversie tussen numeriek datatype naar char of Boolean gebeurt niet automatisch.
// Ook zijn de gegevenstypen char en Boolean niet compatibel met elkaar.
char myChar = 'q';
// compileer fout "incompatible types: char cannot be converted to boolean"
// boolean myBoolean = myChar;
// System.out.println(myChar);
// System.out.println(myBoolean);
System.out.println(" ---- Narrowing casting ---- ");
// Narrowing Casting (handmatig) - een groter type omzetten naar een kleiner formaat type.
double Double = 9.78d;
// Manueel casting: double naar int
int myInteger = (int) Double;
System.out.println("Double = " + Double);
System.out.println("Integer = " + myInteger);
}
}
|
45572_20 | /* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.kml;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.geoserver.ows.URLMangler.URLType;
import org.geoserver.ows.util.ResponseUtils;
import org.geoserver.wms.GetMapRequest;
import org.geoserver.wms.MapLayerInfo;
import org.geoserver.wms.WMS;
import org.geoserver.wms.WMSMapContent;
import org.geoserver.wms.WMSRequests;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.feature.FeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.Layer;
import org.geotools.referencing.CRS;
import org.geotools.styling.Style;
import org.geotools.xml.transform.TransformerBase;
import org.geotools.xml.transform.Translator;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.xml.sax.ContentHandler;
import com.vividsolutions.jts.geom.Envelope;
/**
* Encodes a KML document contianing a network link.
* <p>
* This transformer transforms a {@link GetMapRequest} object.
* </p>
*
* @author Justin Deoliveira, The Open Planning Project, [email protected]
*
*/
public class KMLNetworkLinkTransformer extends TransformerBase {
/**
* logger
*/
static Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geoserver.kml");
/**
* flag controlling whether the network link should be a super overlay.
*/
boolean encodeAsRegion = false;
/**
* flag controlling whether the network link should be a direct GWC one when possible
*/
boolean cachedMode = false;
private boolean standalone;
/**
* @see #setInline
*/
private boolean inline;
/**
* The map context
*/
private final WMSMapContent mapContent;
private WMS wms;
public KMLNetworkLinkTransformer(WMS wms, WMSMapContent mapContent) {
this.wms = wms;
this.mapContent = mapContent;
standalone = true;
}
public void setStandalone(boolean standalone){
this.standalone = standalone;
}
public boolean isStandalone(){
return standalone;
}
/**
* @return {@code true} if the document is to be generated inline (i.e. without an enclosing
* Folder element). Defaults to {@code false}
*/
public boolean isInline() {
return inline;
}
/**
* @param inline if {@code true} network links won't be enclosed inside a Folder element
*/
public void setInline(boolean inline) {
this.inline = inline;
}
public void setCachedMode(boolean cachedMode) {
this.cachedMode = cachedMode;
}
public Translator createTranslator(ContentHandler handler) {
return new KMLNetworkLinkTranslator(handler);
}
public void setEncodeAsRegion(boolean encodeAsRegion) {
this.encodeAsRegion = encodeAsRegion;
}
class KMLNetworkLinkTranslator extends TranslatorSupport {
public KMLNetworkLinkTranslator(ContentHandler contentHandler) {
super(contentHandler, null, null);
}
public void encode(Object o) throws IllegalArgumentException {
final WMSMapContent context = (WMSMapContent) o;
final GetMapRequest request = context.getRequest();
// restore target mime type for the network links
if (NetworkLinkMapOutputFormat.KML_MIME_TYPE.equals(request.getFormat())) {
request.setFormat(KMLMapOutputFormat.MIME_TYPE);
} else {
request.setFormat(KMZMapOutputFormat.MIME_TYPE);
}
if(standalone){
start("kml");
}
if (!inline) {
start("Folder");
if (standalone) {
String kmltitle = (String) mapContent.getRequest().getFormatOptions().get("kmltitle");
element("name", (kmltitle != null ? kmltitle : ""));
}
}
final List<MapLayerInfo> layers = request.getLayers();
final KMLLookAt lookAt = parseLookAtOptions(request);
ReferencedEnvelope aggregatedBounds;
List<ReferencedEnvelope> layerBounds;
layerBounds = new ArrayList<ReferencedEnvelope>(layers.size());
aggregatedBounds = computePerLayerQueryBounds(context, layerBounds, lookAt);
if (encodeAsRegion) {
encodeAsSuperOverlay(request, lookAt, layerBounds);
} else {
encodeAsOverlay(request, lookAt, layerBounds);
}
// look at
encodeLookAt(aggregatedBounds, lookAt);
if (!inline) {
end("Folder");
}
if (standalone) {
end("kml");
}
}
/**
* @return the aggregated bounds for all the requested layers, taking into account whether
* the whole layer or filtered bounds is used for each layer
*/
private ReferencedEnvelope computePerLayerQueryBounds(final WMSMapContent context,
final List<ReferencedEnvelope> target, final KMLLookAt lookAt) {
// no need to compute queried bounds if request explicitly specified the view area
final boolean computeQueryBounds = lookAt.getLookAt() == null;
ReferencedEnvelope aggregatedBounds;
try {
boolean longitudeFirst = true;
aggregatedBounds = new ReferencedEnvelope(CRS.decode("EPSG:4326", longitudeFirst));
} catch (Exception e) {
throw new RuntimeException(e);
}
aggregatedBounds.setToNull();
final List<Layer> mapLayers = context.layers();
final List<MapLayerInfo> layerInfos = context.getRequest().getLayers();
for (int i = 0; i < mapLayers.size(); i++) {
final Layer Layer = mapLayers.get(i);
final MapLayerInfo layerInfo = layerInfos.get(i);
ReferencedEnvelope layerLatLongBbox;
layerLatLongBbox = computeLayerBounds(Layer, layerInfo, computeQueryBounds);
try {
layerLatLongBbox = layerLatLongBbox.transform(aggregatedBounds.getCoordinateReferenceSystem(), true);
} catch (Exception e) {
throw new RuntimeException(e);
}
target.add(layerLatLongBbox);
aggregatedBounds.expandToInclude(layerLatLongBbox);
}
return aggregatedBounds;
}
@SuppressWarnings("rawtypes")
private ReferencedEnvelope computeLayerBounds(Layer layer, MapLayerInfo layerInfo,
boolean computeQueryBounds) {
final Query layerQuery = layer.getQuery();
// make sure if layer is gonna be filtered, the resulting bounds are obtained instead of
// the whole bounds
final Filter filter = layerQuery.getFilter();
if (layerQuery.getFilter() == null || Filter.INCLUDE.equals(filter)) {
computeQueryBounds = false;
}
if (!computeQueryBounds && !layerQuery.isMaxFeaturesUnlimited()) {
computeQueryBounds = true;
}
ReferencedEnvelope layerLatLongBbox = null;
if (computeQueryBounds) {
FeatureSource featureSource = layer.getFeatureSource();
try {
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
FeatureCollection features = featureSource.getFeatures(layerQuery);
layerLatLongBbox = features.getBounds();
layerLatLongBbox = layerLatLongBbox.transform(targetCRS, true);
} catch (Exception e) {
LOGGER.info("Error computing bounds for " + featureSource.getName() + " with "
+ layerQuery);
}
}
if (layerLatLongBbox == null) {
try {
layerLatLongBbox = layerInfo.getLatLongBoundingBox();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return layerLatLongBbox;
}
@SuppressWarnings("unchecked")
private KMLLookAt parseLookAtOptions(final GetMapRequest request) {
final KMLLookAt lookAt;
if (request.getFormatOptions() == null) {
// use a default LookAt properties
lookAt = new KMLLookAt();
} else {
// use the requested LookAt properties
Map<String, Object> formatOptions;
formatOptions = new HashMap<String, Object>(request.getFormatOptions());
lookAt = new KMLLookAt(formatOptions);
/*
* remove LOOKATBBOX and LOOKATGEOM from format options so KMLUtils.getMapRequest
* does not include them in the network links, but do include the other options such
* as tilt, range, etc.
*/
request.getFormatOptions().remove("LOOKATBBOX");
request.getFormatOptions().remove("LOOKATGEOM");
}
return lookAt;
}
protected void encodeAsSuperOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
List<MapLayerInfo> layers = request.getLayers();
List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layer = layers.get(i);
if ("cached".equals(KMLUtils.getSuperoverlayMode(request, wms))
&& KMLUtils.isRequestGWCCompatible(request, i, wms)) {
encodeGWCLink(request, layer);
} else {
String styleName = i < styles.size() ? styles.get(i).getName() : null;
ReferencedEnvelope bounds = layerBounds.get(i);
encodeLayerSuperOverlay(request, layer, styleName, i, bounds, lookAt);
}
}
}
public void encodeGWCLink(GetMapRequest request, MapLayerInfo layer) {
start("NetworkLink");
String prefixedName = layer.getResource().getPrefixedName();
element("name", "GWC-" + prefixedName);
start("Link");
String type = layer.getType() == MapLayerInfo.TYPE_RASTER ? "png" : "kml";
String url = ResponseUtils.buildURL(request.getBaseUrl(), "gwc/service/kml/" +
prefixedName + "." + type + ".kml", null, URLType.SERVICE);
element("href", url);
element("viewRefreshMode", "never");
end("Link");
end("NetworkLink");
}
private void encodeLayerSuperOverlay(GetMapRequest request, MapLayerInfo layer,
String styleName, int layerIndex, ReferencedEnvelope bounds, KMLLookAt lookAt) {
start("NetworkLink");
element("name", layer.getName());
element("open", "1");
element("visibility", "1");
// look at for the network link for this single layer
if (bounds != null) {
encodeLookAt(bounds, lookAt);
}
// region
start("Region");
Envelope bbox = request.getBbox();
start("LatLonAltBox");
element("north", "" + bbox.getMaxY());
element("south", "" + bbox.getMinY());
element("east", "" + bbox.getMaxX());
element("west", "" + bbox.getMinX());
end("LatLonAltBox");
start("Lod");
element("minLodPixels", "128");
element("maxLodPixels", "-1");
end("Lod");
end("Region");
// link
start("Link");
String href = WMSRequests.getGetMapUrl(request, layer.getName(), layerIndex, styleName,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
// element( "viewRefreshMode", "onRegion" );
end("Link");
end("NetworkLink");
}
protected void encodeAsOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
final List<MapLayerInfo> layers = request.getLayers();
final List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layerInfo = layers.get(i);
start("NetworkLink");
element("name", layerInfo.getName());
element("visibility", "1");
element("open", "1");
// look at for the network link for this single layer
ReferencedEnvelope latLongBoundingBox = layerBounds.get(i);
if (latLongBoundingBox != null) {
encodeLookAt(latLongBoundingBox, lookAt);
}
start("Url");
// set bbox to null so its not included in the request, google
// earth will append it for us
request.setBbox(null);
String style = i < styles.size() ? styles.get(i).getName() : null;
String href = WMSRequests.getGetMapUrl(request, layers.get(i).getName(), i, style,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
element("viewRefreshMode", "onStop");
element("viewRefreshTime", "1");
end("Url");
end("NetworkLink");
}
}
private void encodeLookAt(Envelope bounds, KMLLookAt lookAt) {
Envelope lookAtEnvelope = null;
if (lookAt.getLookAt() == null) {
lookAtEnvelope = bounds;
}
KMLLookAtTransformer tr;
tr = new KMLLookAtTransformer(lookAtEnvelope, getIndentation(), getEncoding());
Translator translator = tr.createTranslator(contentHandler);
translator.encode(lookAt);
}
}
}
| Gaia3D/GeoServerForKaosG | src/community/kml-old/src/main/java/org/geoserver/kml/KMLNetworkLinkTransformer.java | 4,115 | // element( "viewRefreshMode", "onRegion" ); | line_comment | nl | /* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.kml;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.geoserver.ows.URLMangler.URLType;
import org.geoserver.ows.util.ResponseUtils;
import org.geoserver.wms.GetMapRequest;
import org.geoserver.wms.MapLayerInfo;
import org.geoserver.wms.WMS;
import org.geoserver.wms.WMSMapContent;
import org.geoserver.wms.WMSRequests;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.feature.FeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.Layer;
import org.geotools.referencing.CRS;
import org.geotools.styling.Style;
import org.geotools.xml.transform.TransformerBase;
import org.geotools.xml.transform.Translator;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.xml.sax.ContentHandler;
import com.vividsolutions.jts.geom.Envelope;
/**
* Encodes a KML document contianing a network link.
* <p>
* This transformer transforms a {@link GetMapRequest} object.
* </p>
*
* @author Justin Deoliveira, The Open Planning Project, [email protected]
*
*/
public class KMLNetworkLinkTransformer extends TransformerBase {
/**
* logger
*/
static Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geoserver.kml");
/**
* flag controlling whether the network link should be a super overlay.
*/
boolean encodeAsRegion = false;
/**
* flag controlling whether the network link should be a direct GWC one when possible
*/
boolean cachedMode = false;
private boolean standalone;
/**
* @see #setInline
*/
private boolean inline;
/**
* The map context
*/
private final WMSMapContent mapContent;
private WMS wms;
public KMLNetworkLinkTransformer(WMS wms, WMSMapContent mapContent) {
this.wms = wms;
this.mapContent = mapContent;
standalone = true;
}
public void setStandalone(boolean standalone){
this.standalone = standalone;
}
public boolean isStandalone(){
return standalone;
}
/**
* @return {@code true} if the document is to be generated inline (i.e. without an enclosing
* Folder element). Defaults to {@code false}
*/
public boolean isInline() {
return inline;
}
/**
* @param inline if {@code true} network links won't be enclosed inside a Folder element
*/
public void setInline(boolean inline) {
this.inline = inline;
}
public void setCachedMode(boolean cachedMode) {
this.cachedMode = cachedMode;
}
public Translator createTranslator(ContentHandler handler) {
return new KMLNetworkLinkTranslator(handler);
}
public void setEncodeAsRegion(boolean encodeAsRegion) {
this.encodeAsRegion = encodeAsRegion;
}
class KMLNetworkLinkTranslator extends TranslatorSupport {
public KMLNetworkLinkTranslator(ContentHandler contentHandler) {
super(contentHandler, null, null);
}
public void encode(Object o) throws IllegalArgumentException {
final WMSMapContent context = (WMSMapContent) o;
final GetMapRequest request = context.getRequest();
// restore target mime type for the network links
if (NetworkLinkMapOutputFormat.KML_MIME_TYPE.equals(request.getFormat())) {
request.setFormat(KMLMapOutputFormat.MIME_TYPE);
} else {
request.setFormat(KMZMapOutputFormat.MIME_TYPE);
}
if(standalone){
start("kml");
}
if (!inline) {
start("Folder");
if (standalone) {
String kmltitle = (String) mapContent.getRequest().getFormatOptions().get("kmltitle");
element("name", (kmltitle != null ? kmltitle : ""));
}
}
final List<MapLayerInfo> layers = request.getLayers();
final KMLLookAt lookAt = parseLookAtOptions(request);
ReferencedEnvelope aggregatedBounds;
List<ReferencedEnvelope> layerBounds;
layerBounds = new ArrayList<ReferencedEnvelope>(layers.size());
aggregatedBounds = computePerLayerQueryBounds(context, layerBounds, lookAt);
if (encodeAsRegion) {
encodeAsSuperOverlay(request, lookAt, layerBounds);
} else {
encodeAsOverlay(request, lookAt, layerBounds);
}
// look at
encodeLookAt(aggregatedBounds, lookAt);
if (!inline) {
end("Folder");
}
if (standalone) {
end("kml");
}
}
/**
* @return the aggregated bounds for all the requested layers, taking into account whether
* the whole layer or filtered bounds is used for each layer
*/
private ReferencedEnvelope computePerLayerQueryBounds(final WMSMapContent context,
final List<ReferencedEnvelope> target, final KMLLookAt lookAt) {
// no need to compute queried bounds if request explicitly specified the view area
final boolean computeQueryBounds = lookAt.getLookAt() == null;
ReferencedEnvelope aggregatedBounds;
try {
boolean longitudeFirst = true;
aggregatedBounds = new ReferencedEnvelope(CRS.decode("EPSG:4326", longitudeFirst));
} catch (Exception e) {
throw new RuntimeException(e);
}
aggregatedBounds.setToNull();
final List<Layer> mapLayers = context.layers();
final List<MapLayerInfo> layerInfos = context.getRequest().getLayers();
for (int i = 0; i < mapLayers.size(); i++) {
final Layer Layer = mapLayers.get(i);
final MapLayerInfo layerInfo = layerInfos.get(i);
ReferencedEnvelope layerLatLongBbox;
layerLatLongBbox = computeLayerBounds(Layer, layerInfo, computeQueryBounds);
try {
layerLatLongBbox = layerLatLongBbox.transform(aggregatedBounds.getCoordinateReferenceSystem(), true);
} catch (Exception e) {
throw new RuntimeException(e);
}
target.add(layerLatLongBbox);
aggregatedBounds.expandToInclude(layerLatLongBbox);
}
return aggregatedBounds;
}
@SuppressWarnings("rawtypes")
private ReferencedEnvelope computeLayerBounds(Layer layer, MapLayerInfo layerInfo,
boolean computeQueryBounds) {
final Query layerQuery = layer.getQuery();
// make sure if layer is gonna be filtered, the resulting bounds are obtained instead of
// the whole bounds
final Filter filter = layerQuery.getFilter();
if (layerQuery.getFilter() == null || Filter.INCLUDE.equals(filter)) {
computeQueryBounds = false;
}
if (!computeQueryBounds && !layerQuery.isMaxFeaturesUnlimited()) {
computeQueryBounds = true;
}
ReferencedEnvelope layerLatLongBbox = null;
if (computeQueryBounds) {
FeatureSource featureSource = layer.getFeatureSource();
try {
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
FeatureCollection features = featureSource.getFeatures(layerQuery);
layerLatLongBbox = features.getBounds();
layerLatLongBbox = layerLatLongBbox.transform(targetCRS, true);
} catch (Exception e) {
LOGGER.info("Error computing bounds for " + featureSource.getName() + " with "
+ layerQuery);
}
}
if (layerLatLongBbox == null) {
try {
layerLatLongBbox = layerInfo.getLatLongBoundingBox();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return layerLatLongBbox;
}
@SuppressWarnings("unchecked")
private KMLLookAt parseLookAtOptions(final GetMapRequest request) {
final KMLLookAt lookAt;
if (request.getFormatOptions() == null) {
// use a default LookAt properties
lookAt = new KMLLookAt();
} else {
// use the requested LookAt properties
Map<String, Object> formatOptions;
formatOptions = new HashMap<String, Object>(request.getFormatOptions());
lookAt = new KMLLookAt(formatOptions);
/*
* remove LOOKATBBOX and LOOKATGEOM from format options so KMLUtils.getMapRequest
* does not include them in the network links, but do include the other options such
* as tilt, range, etc.
*/
request.getFormatOptions().remove("LOOKATBBOX");
request.getFormatOptions().remove("LOOKATGEOM");
}
return lookAt;
}
protected void encodeAsSuperOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
List<MapLayerInfo> layers = request.getLayers();
List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layer = layers.get(i);
if ("cached".equals(KMLUtils.getSuperoverlayMode(request, wms))
&& KMLUtils.isRequestGWCCompatible(request, i, wms)) {
encodeGWCLink(request, layer);
} else {
String styleName = i < styles.size() ? styles.get(i).getName() : null;
ReferencedEnvelope bounds = layerBounds.get(i);
encodeLayerSuperOverlay(request, layer, styleName, i, bounds, lookAt);
}
}
}
public void encodeGWCLink(GetMapRequest request, MapLayerInfo layer) {
start("NetworkLink");
String prefixedName = layer.getResource().getPrefixedName();
element("name", "GWC-" + prefixedName);
start("Link");
String type = layer.getType() == MapLayerInfo.TYPE_RASTER ? "png" : "kml";
String url = ResponseUtils.buildURL(request.getBaseUrl(), "gwc/service/kml/" +
prefixedName + "." + type + ".kml", null, URLType.SERVICE);
element("href", url);
element("viewRefreshMode", "never");
end("Link");
end("NetworkLink");
}
private void encodeLayerSuperOverlay(GetMapRequest request, MapLayerInfo layer,
String styleName, int layerIndex, ReferencedEnvelope bounds, KMLLookAt lookAt) {
start("NetworkLink");
element("name", layer.getName());
element("open", "1");
element("visibility", "1");
// look at for the network link for this single layer
if (bounds != null) {
encodeLookAt(bounds, lookAt);
}
// region
start("Region");
Envelope bbox = request.getBbox();
start("LatLonAltBox");
element("north", "" + bbox.getMaxY());
element("south", "" + bbox.getMinY());
element("east", "" + bbox.getMaxX());
element("west", "" + bbox.getMinX());
end("LatLonAltBox");
start("Lod");
element("minLodPixels", "128");
element("maxLodPixels", "-1");
end("Lod");
end("Region");
// link
start("Link");
String href = WMSRequests.getGetMapUrl(request, layer.getName(), layerIndex, styleName,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
// element( "viewRefreshMode",<SUF>
end("Link");
end("NetworkLink");
}
protected void encodeAsOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
final List<MapLayerInfo> layers = request.getLayers();
final List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layerInfo = layers.get(i);
start("NetworkLink");
element("name", layerInfo.getName());
element("visibility", "1");
element("open", "1");
// look at for the network link for this single layer
ReferencedEnvelope latLongBoundingBox = layerBounds.get(i);
if (latLongBoundingBox != null) {
encodeLookAt(latLongBoundingBox, lookAt);
}
start("Url");
// set bbox to null so its not included in the request, google
// earth will append it for us
request.setBbox(null);
String style = i < styles.size() ? styles.get(i).getName() : null;
String href = WMSRequests.getGetMapUrl(request, layers.get(i).getName(), i, style,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
element("viewRefreshMode", "onStop");
element("viewRefreshTime", "1");
end("Url");
end("NetworkLink");
}
}
private void encodeLookAt(Envelope bounds, KMLLookAt lookAt) {
Envelope lookAtEnvelope = null;
if (lookAt.getLookAt() == null) {
lookAtEnvelope = bounds;
}
KMLLookAtTransformer tr;
tr = new KMLLookAtTransformer(lookAtEnvelope, getIndentation(), getEncoding());
Translator translator = tr.createTranslator(contentHandler);
translator.encode(lookAt);
}
}
}
|
120648_14 | package DN11;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Kraj razred
* Predstavlja eno mesto v železniški ponudbi. Vsebuje String ime kraja, String kratico (dvočrkovna kratica) ter seznam
* odhodov vlakov v sosednje kraje
*/
class Kraj {
private final String ime;
private final String kratica;
private final List<Vlak> odhodi;
public Kraj(String ime, String kratica) {
this.ime = ime;
this.kratica = kratica;
this.odhodi = new ArrayList<>();
}
public String getIme() {
return ime;
}
public String getKratica() {
return kratica;
}
public List<Vlak> getOdhodi() {
return odhodi;
}
public boolean dodajOdhod(Vlak vlak) {
if (odhodi.contains(vlak)) {
return false;
} else {
odhodi.add(vlak);
return true;
}
}
public void dodajVlak(Vlak vlak) {
odhodi.add(vlak);
}
public String toString() {
return String.format("%s (%s)", ime, kratica);
}
}
/**
* Razred Vlak
* Predstavlja vlake iz poletne ponudbe, ki povezujejo dva kraja. Vsebuje oznako vlaka(idVlak), zacetniKraj, koncniKraj
* in trajanjeVoznje.
* Vsebuje abstraktni metodi String opis() in double cenaVoznje(). Opis vrne niz ali gre za regionalni ali za ekspresni
* vlak, cenaVoznje pa izračuna in vrne končno ceno vozovnice.
*/
abstract class Vlak {
private final String idVlak;
private final Kraj zacetniKraj;
private final Kraj koncniKraj;
private final double trajanjeVoznje;
public Vlak(String idVlak, Kraj zacetniKraj, Kraj koncniKraj, double trajanjeVoznje) {
this.idVlak = idVlak;
this.zacetniKraj = zacetniKraj;
this.koncniKraj = koncniKraj;
this.trajanjeVoznje = trajanjeVoznje;
zacetniKraj.dodajVlak(this);
}
public String getIdVlak() {
return idVlak;
}
public Kraj getZacetniKraj() {
return zacetniKraj;
}
public Kraj getKoncniKraj() {
return koncniKraj;
}
public double getTrajanjeVoznje() {
return trajanjeVoznje;
}
public abstract String opis();
public abstract double cenaVoznje();
public String trajanjeVoznje() {
if(getTrajanjeVoznje() > 60) {
int ure = (int) (getTrajanjeVoznje() / 60);
int minute = (int) (getTrajanjeVoznje() % 60);
if(9 < minute) return String.format("%d.%dh", ure, minute);
else return String.format("%d.0%dh", ure,minute);
}
else return Math.round(getTrajanjeVoznje()) + "min";
}
public String toString() {
/*return String.format(
"Vlak " + idVlak + " (" + opis() + ") " + zacetniKraj + " -- " + koncniKraj + " (" + trajanjeVoznje() + ", %.2f EUR)",
cenaVoznje());*/
return String.format(
"Vlak %s (%s) %s -- %s (%s, %.2f EUR)",
idVlak, opis(), zacetniKraj, koncniKraj, trajanjeVoznje(), cenaVoznje()
);
}
}
/**
* Razred RegionalniVlak
* Regionalni vlaki vozijo s povp hitrostjo 50km/h.
* Cena na km je 0.068
* metoda cenaVoznje() vrne izračunano ceno vozovnice
*/
class RegionalniVlak extends Vlak {
private static final double HITROST = 50;
private static final double CenaNaKm = 0.068;
public RegionalniVlak(String oznaka, Kraj zacetek, Kraj konec, double trajanje) {
super(oznaka, zacetek, konec, (int) trajanje);
}
@Override
public String opis() {
return "regionalni";
}
@Override
public double cenaVoznje() {
double cena = (HITROST * super.getTrajanjeVoznje()) / 60;
return cena * CenaNaKm;
}
}
/**
* Razred EkspresniVlak
* Regionalni vlaki vozijo s povp hitrostjo 50km/h.
* Cena na km je 0.068
* metoda cenaVoznje() vrne izračunano ceno vozovnice
*/
class EkspresniVlak extends Vlak {
private static final int HITROST = 110;
private static final double CenaNaKm = 0.154;
private final double dopl;
public EkspresniVlak(String oznaka, Kraj zacetek, Kraj konec, double trajanje, double dopl) {
super(oznaka, zacetek, konec, (int) trajanje);
this.dopl = dopl;
}
public double getDopl() {
return dopl;
}
@Override
public String opis() {
return "ekspresni";
}
@Override
public double cenaVoznje() {
return HITROST * (getTrajanjeVoznje() / 60) * CenaNaKm + dopl;
}
}
/**
* Razred EuroRail
* Predstavlja celotno železniško omrežje. Vsebuje zbirko vseh krajev in zbirko vseh vlakov.
* metoda preberiKraje(String ime datoteke) prebere podatke o krajih ter jih zapiše v zbirko
* metoda preberiPovezave(String ime datoteke) prebere podatke o vlakih, ter jih zapiše v zbirko vlakov
* metoda izpisiKraje() izpiše vse prebrane kraje
* metoda izpisiPovezave() izpiše vse prebrane vlake in podatke o trajanju vožnje in o ceni
*/
class EuroRail {
private final List<Kraj1> kraji;
private final List<Vlak1> vlaki;
public EuroRail() {
kraji = new ArrayList<>();
vlaki = new ArrayList<>();
}
public void dodajKraj(Kraj1 kraj) {
kraji.add(kraj);
}
public void dodajVlak(Vlak1 vlak) {
vlaki.add(vlak);
}
public List<Kraj1> getKraji() {
return kraji;
}
public List<Vlak1> getVlaki() {
return vlaki;
}
public boolean preberiKraje(String imeDatoteke) {
try (BufferedReader br = new BufferedReader(new FileReader(imeDatoteke))) {
String vrstica;
while ((vrstica = br.readLine()) != null) {
String[] podatki = vrstica.split(";");
if (podatki.length == 2) {
String imeKraja = podatki[0].trim();
String kodaDrzave = podatki[1].trim();
boolean krajObstaja = false;
for(Kraj1 kraj : kraji) {
if(kraj.getIme().equalsIgnoreCase(imeKraja)) {
krajObstaja = true;
break;
}
}
if(!krajObstaja) {
Kraj1 kraj = new Kraj1(imeKraja, kodaDrzave);
kraji.add(kraj);
}
}
}
br.close();
return true; //Uspešno branje
} catch (IOException e) {
e.printStackTrace();
return false; //Napaka pri branju
}
}
public void izpisiKraje() {
System.out.println("Kraji, povezani z vlaki:");
for (Kraj1 kraj : kraji) {
System.out.println(kraj);
}
}
public boolean preberiPovezave(String imeDatoteke) {
try (BufferedReader br = new BufferedReader(new FileReader(imeDatoteke)))
{
String vrstica;
while ((vrstica = br.readLine()) != null) {
String[] temptab;
int temp;
String[] podatki = vrstica.split(";");
if(podatki.length >= 4) {
String oznakaVlaka = podatki[0].trim();
String zacetniKraj = podatki[1].trim();
String koncniKraj = podatki[2].trim();
if(podatki[3].contains(".")) {
temptab = podatki[3].split("\\.");
temp = Integer.parseInt(temptab[0]) * 60 + Integer.parseInt(temptab[1]);
}
else temp = Integer.parseInt(podatki[3]);
Kraj1 zacetniKrajIme = null;
Kraj1 koncniKrajIme = null;
for(Kraj1 kraj : kraji) {
if(kraj.getIme().equalsIgnoreCase(zacetniKraj)) zacetniKrajIme = kraj;
else if(kraj.getIme().equalsIgnoreCase(koncniKraj)) koncniKrajIme = kraj;
if(zacetniKrajIme != null && koncniKrajIme != null) break;
}
if(zacetniKrajIme != null && koncniKrajIme != null) {
int trajanjeVoznje = temp;
Vlak1 vlak;
if(podatki.length == 5) {
double doplacanZnesek = Double.parseDouble(podatki[4].trim());
vlak = new EkspresniVlak1(oznakaVlaka, zacetniKrajIme, koncniKrajIme, trajanjeVoznje, doplacanZnesek);
}
else {
vlak = new RegionalniVlak1(oznakaVlaka, zacetniKrajIme, koncniKrajIme, trajanjeVoznje);
}
vlaki.add(vlak);
}
}
}
br.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void izpisiPovezave() {
System.out.println();
System.out.println("Vlaki, ki povezujejo kraje:");
for (Vlak1 vlak : vlaki) {
System.out.println(vlak.toString());
}
}
}
/**
* Metoda main izvede ustrezen del programa. V primeru da pokličemo nalogo, ki ne obstaja izpiše sporočilo o napaki
*/
public class DN11 {
public static void main(String[] args) {
//EuroRail euroRail;
// Kraj ljubljana = new Kraj("Ljubljana", "SI");
// Kraj maribor = new Kraj("Maribor", "SI");
// Kraj celje = new Kraj("Celje", "SI");
//
// euroRail.dodajKraj(ljubljana);
// euroRail.dodajKraj(maribor);
// euroRail.dodajKraj(celje);
//
// Vlak vlak1 = new RegionalniVlak("RG123", ljubljana, maribor, 120);
// Vlak vlak2 = new EkspresniVlak("EK456", ljubljana, celje, 90, 5.0);
//
// euroRail.dodajVlak(vlak1);
// euroRail.dodajVlak(vlak2);
// Preverjanje podatkov
// for (Kraj kraj : euroRail.getKraji()) {
// System.out.println(kraj);
// }
//
// System.out.println();
//
// System.out.println("Seznam vlakov:");
// for (Vlak vlak : euroRail.getVlaki()) {
// System.out.println(vlak);
// }
// boolean uspesnoBranje = euroRail.preberiKraje("src/DN11/kraji.txt");
// if (uspesnoBranje) {
// System.out.println("Kraji so bili uspešno prebrani.");
// } else {
// System.out.println("Prišlo je do napake pri branju krajev.");
// }
// euroRail = new EuroRail();
// boolean uspesnoBranjeKrajev = euroRail.preberiKraje("src/DN11/kraji.txt");
// boolean uspesnoBranjePovezav = euroRail.preberiPovezave("src/DN11/povezave.txt");
// if (uspesnoBranjeKrajev && uspesnoBranjePovezav) {
// euroRail.izpisiKraje();
// euroRail.izpisiPovezave();
// } else {
// System.out.println("Prišlo je do napake pri branju krajev in/ali povezav.");
// }
int naloga = Integer.parseInt(args[0]);
String krajiDatoteka = args[1];
String povezaveDatoteka = args[2];
EuroRail1 euroRail = new EuroRail1();
boolean uspesnoBranjeKrajev;
boolean uspesnoBranjePovezav;
if (naloga == 1) {
uspesnoBranjeKrajev = euroRail.preberiKraje(krajiDatoteka);
uspesnoBranjePovezav = euroRail.preberiPovezave(povezaveDatoteka);
if (uspesnoBranjeKrajev && uspesnoBranjePovezav) {
euroRail.izpisiKraje();
euroRail.izpisiPovezave();
} else {
System.out.println("Prišlo je do napake pri branju krajev in/ali povezav.");
}
}
else {
System.out.println("Napaka: Neveljavna naloga.");
}
}
} | GameExplorer/DomaceNaloge | src/DN11/DN11.java | 4,388 | // for (Vlak vlak : euroRail.getVlaki()) { | line_comment | nl | package DN11;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Kraj razred
* Predstavlja eno mesto v železniški ponudbi. Vsebuje String ime kraja, String kratico (dvočrkovna kratica) ter seznam
* odhodov vlakov v sosednje kraje
*/
class Kraj {
private final String ime;
private final String kratica;
private final List<Vlak> odhodi;
public Kraj(String ime, String kratica) {
this.ime = ime;
this.kratica = kratica;
this.odhodi = new ArrayList<>();
}
public String getIme() {
return ime;
}
public String getKratica() {
return kratica;
}
public List<Vlak> getOdhodi() {
return odhodi;
}
public boolean dodajOdhod(Vlak vlak) {
if (odhodi.contains(vlak)) {
return false;
} else {
odhodi.add(vlak);
return true;
}
}
public void dodajVlak(Vlak vlak) {
odhodi.add(vlak);
}
public String toString() {
return String.format("%s (%s)", ime, kratica);
}
}
/**
* Razred Vlak
* Predstavlja vlake iz poletne ponudbe, ki povezujejo dva kraja. Vsebuje oznako vlaka(idVlak), zacetniKraj, koncniKraj
* in trajanjeVoznje.
* Vsebuje abstraktni metodi String opis() in double cenaVoznje(). Opis vrne niz ali gre za regionalni ali za ekspresni
* vlak, cenaVoznje pa izračuna in vrne končno ceno vozovnice.
*/
abstract class Vlak {
private final String idVlak;
private final Kraj zacetniKraj;
private final Kraj koncniKraj;
private final double trajanjeVoznje;
public Vlak(String idVlak, Kraj zacetniKraj, Kraj koncniKraj, double trajanjeVoznje) {
this.idVlak = idVlak;
this.zacetniKraj = zacetniKraj;
this.koncniKraj = koncniKraj;
this.trajanjeVoznje = trajanjeVoznje;
zacetniKraj.dodajVlak(this);
}
public String getIdVlak() {
return idVlak;
}
public Kraj getZacetniKraj() {
return zacetniKraj;
}
public Kraj getKoncniKraj() {
return koncniKraj;
}
public double getTrajanjeVoznje() {
return trajanjeVoznje;
}
public abstract String opis();
public abstract double cenaVoznje();
public String trajanjeVoznje() {
if(getTrajanjeVoznje() > 60) {
int ure = (int) (getTrajanjeVoznje() / 60);
int minute = (int) (getTrajanjeVoznje() % 60);
if(9 < minute) return String.format("%d.%dh", ure, minute);
else return String.format("%d.0%dh", ure,minute);
}
else return Math.round(getTrajanjeVoznje()) + "min";
}
public String toString() {
/*return String.format(
"Vlak " + idVlak + " (" + opis() + ") " + zacetniKraj + " -- " + koncniKraj + " (" + trajanjeVoznje() + ", %.2f EUR)",
cenaVoznje());*/
return String.format(
"Vlak %s (%s) %s -- %s (%s, %.2f EUR)",
idVlak, opis(), zacetniKraj, koncniKraj, trajanjeVoznje(), cenaVoznje()
);
}
}
/**
* Razred RegionalniVlak
* Regionalni vlaki vozijo s povp hitrostjo 50km/h.
* Cena na km je 0.068
* metoda cenaVoznje() vrne izračunano ceno vozovnice
*/
class RegionalniVlak extends Vlak {
private static final double HITROST = 50;
private static final double CenaNaKm = 0.068;
public RegionalniVlak(String oznaka, Kraj zacetek, Kraj konec, double trajanje) {
super(oznaka, zacetek, konec, (int) trajanje);
}
@Override
public String opis() {
return "regionalni";
}
@Override
public double cenaVoznje() {
double cena = (HITROST * super.getTrajanjeVoznje()) / 60;
return cena * CenaNaKm;
}
}
/**
* Razred EkspresniVlak
* Regionalni vlaki vozijo s povp hitrostjo 50km/h.
* Cena na km je 0.068
* metoda cenaVoznje() vrne izračunano ceno vozovnice
*/
class EkspresniVlak extends Vlak {
private static final int HITROST = 110;
private static final double CenaNaKm = 0.154;
private final double dopl;
public EkspresniVlak(String oznaka, Kraj zacetek, Kraj konec, double trajanje, double dopl) {
super(oznaka, zacetek, konec, (int) trajanje);
this.dopl = dopl;
}
public double getDopl() {
return dopl;
}
@Override
public String opis() {
return "ekspresni";
}
@Override
public double cenaVoznje() {
return HITROST * (getTrajanjeVoznje() / 60) * CenaNaKm + dopl;
}
}
/**
* Razred EuroRail
* Predstavlja celotno železniško omrežje. Vsebuje zbirko vseh krajev in zbirko vseh vlakov.
* metoda preberiKraje(String ime datoteke) prebere podatke o krajih ter jih zapiše v zbirko
* metoda preberiPovezave(String ime datoteke) prebere podatke o vlakih, ter jih zapiše v zbirko vlakov
* metoda izpisiKraje() izpiše vse prebrane kraje
* metoda izpisiPovezave() izpiše vse prebrane vlake in podatke o trajanju vožnje in o ceni
*/
class EuroRail {
private final List<Kraj1> kraji;
private final List<Vlak1> vlaki;
public EuroRail() {
kraji = new ArrayList<>();
vlaki = new ArrayList<>();
}
public void dodajKraj(Kraj1 kraj) {
kraji.add(kraj);
}
public void dodajVlak(Vlak1 vlak) {
vlaki.add(vlak);
}
public List<Kraj1> getKraji() {
return kraji;
}
public List<Vlak1> getVlaki() {
return vlaki;
}
public boolean preberiKraje(String imeDatoteke) {
try (BufferedReader br = new BufferedReader(new FileReader(imeDatoteke))) {
String vrstica;
while ((vrstica = br.readLine()) != null) {
String[] podatki = vrstica.split(";");
if (podatki.length == 2) {
String imeKraja = podatki[0].trim();
String kodaDrzave = podatki[1].trim();
boolean krajObstaja = false;
for(Kraj1 kraj : kraji) {
if(kraj.getIme().equalsIgnoreCase(imeKraja)) {
krajObstaja = true;
break;
}
}
if(!krajObstaja) {
Kraj1 kraj = new Kraj1(imeKraja, kodaDrzave);
kraji.add(kraj);
}
}
}
br.close();
return true; //Uspešno branje
} catch (IOException e) {
e.printStackTrace();
return false; //Napaka pri branju
}
}
public void izpisiKraje() {
System.out.println("Kraji, povezani z vlaki:");
for (Kraj1 kraj : kraji) {
System.out.println(kraj);
}
}
public boolean preberiPovezave(String imeDatoteke) {
try (BufferedReader br = new BufferedReader(new FileReader(imeDatoteke)))
{
String vrstica;
while ((vrstica = br.readLine()) != null) {
String[] temptab;
int temp;
String[] podatki = vrstica.split(";");
if(podatki.length >= 4) {
String oznakaVlaka = podatki[0].trim();
String zacetniKraj = podatki[1].trim();
String koncniKraj = podatki[2].trim();
if(podatki[3].contains(".")) {
temptab = podatki[3].split("\\.");
temp = Integer.parseInt(temptab[0]) * 60 + Integer.parseInt(temptab[1]);
}
else temp = Integer.parseInt(podatki[3]);
Kraj1 zacetniKrajIme = null;
Kraj1 koncniKrajIme = null;
for(Kraj1 kraj : kraji) {
if(kraj.getIme().equalsIgnoreCase(zacetniKraj)) zacetniKrajIme = kraj;
else if(kraj.getIme().equalsIgnoreCase(koncniKraj)) koncniKrajIme = kraj;
if(zacetniKrajIme != null && koncniKrajIme != null) break;
}
if(zacetniKrajIme != null && koncniKrajIme != null) {
int trajanjeVoznje = temp;
Vlak1 vlak;
if(podatki.length == 5) {
double doplacanZnesek = Double.parseDouble(podatki[4].trim());
vlak = new EkspresniVlak1(oznakaVlaka, zacetniKrajIme, koncniKrajIme, trajanjeVoznje, doplacanZnesek);
}
else {
vlak = new RegionalniVlak1(oznakaVlaka, zacetniKrajIme, koncniKrajIme, trajanjeVoznje);
}
vlaki.add(vlak);
}
}
}
br.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void izpisiPovezave() {
System.out.println();
System.out.println("Vlaki, ki povezujejo kraje:");
for (Vlak1 vlak : vlaki) {
System.out.println(vlak.toString());
}
}
}
/**
* Metoda main izvede ustrezen del programa. V primeru da pokličemo nalogo, ki ne obstaja izpiše sporočilo o napaki
*/
public class DN11 {
public static void main(String[] args) {
//EuroRail euroRail;
// Kraj ljubljana = new Kraj("Ljubljana", "SI");
// Kraj maribor = new Kraj("Maribor", "SI");
// Kraj celje = new Kraj("Celje", "SI");
//
// euroRail.dodajKraj(ljubljana);
// euroRail.dodajKraj(maribor);
// euroRail.dodajKraj(celje);
//
// Vlak vlak1 = new RegionalniVlak("RG123", ljubljana, maribor, 120);
// Vlak vlak2 = new EkspresniVlak("EK456", ljubljana, celje, 90, 5.0);
//
// euroRail.dodajVlak(vlak1);
// euroRail.dodajVlak(vlak2);
// Preverjanje podatkov
// for (Kraj kraj : euroRail.getKraji()) {
// System.out.println(kraj);
// }
//
// System.out.println();
//
// System.out.println("Seznam vlakov:");
// for (Vlak<SUF>
// System.out.println(vlak);
// }
// boolean uspesnoBranje = euroRail.preberiKraje("src/DN11/kraji.txt");
// if (uspesnoBranje) {
// System.out.println("Kraji so bili uspešno prebrani.");
// } else {
// System.out.println("Prišlo je do napake pri branju krajev.");
// }
// euroRail = new EuroRail();
// boolean uspesnoBranjeKrajev = euroRail.preberiKraje("src/DN11/kraji.txt");
// boolean uspesnoBranjePovezav = euroRail.preberiPovezave("src/DN11/povezave.txt");
// if (uspesnoBranjeKrajev && uspesnoBranjePovezav) {
// euroRail.izpisiKraje();
// euroRail.izpisiPovezave();
// } else {
// System.out.println("Prišlo je do napake pri branju krajev in/ali povezav.");
// }
int naloga = Integer.parseInt(args[0]);
String krajiDatoteka = args[1];
String povezaveDatoteka = args[2];
EuroRail1 euroRail = new EuroRail1();
boolean uspesnoBranjeKrajev;
boolean uspesnoBranjePovezav;
if (naloga == 1) {
uspesnoBranjeKrajev = euroRail.preberiKraje(krajiDatoteka);
uspesnoBranjePovezav = euroRail.preberiPovezave(povezaveDatoteka);
if (uspesnoBranjeKrajev && uspesnoBranjePovezav) {
euroRail.izpisiKraje();
euroRail.izpisiPovezave();
} else {
System.out.println("Prišlo je do napake pri branju krajev in/ali povezav.");
}
}
else {
System.out.println("Napaka: Neveljavna naloga.");
}
}
} |
139384_10 | package siheynde.bachelorproefmod.structure.functions;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import siheynde.bachelorproefmod.BachelorProef;
import siheynde.bachelorproefmod.networking.ModPackets;
import siheynde.bachelorproefmod.structure.shrine.Shrine;
import siheynde.bachelorproefmod.util.PlayerMixinInterface;
import java.util.*;
//This will always be executed server side
public class StrictComparisonBubbleSort implements SubTopic {
public ArrayList<BlockPos> blocksPredict = new ArrayList<>();
public List<Block> blocksPredictOrder = Arrays.asList(
Blocks.BLACK_STAINED_GLASS,
Blocks.GRAY_STAINED_GLASS,
Blocks.BLACK_STAINED_GLASS,
Blocks.WHITE_STAINED_GLASS);
@Override
public String runPredict(PlayerEntity player) {
World world = player.getWorld();
BachelorProef.LOGGER.info("Running predict");
BachelorProef.LOGGER.info("Blocks: " + blocksPredict);
List<Block> blocksPredictCurrentOrder = new ArrayList<>();
blocksPredict.forEach(blockpos -> {
BachelorProef.LOGGER.info("Block: " + blockpos);
Block block = world.getBlockState(blockpos).getBlock();
BachelorProef.LOGGER.info("Block: " + block);
blocksPredictCurrentOrder.add(block);
});
Collections.reverse(blocksPredictCurrentOrder);
BachelorProef.LOGGER.info("Blocks current order: " + blocksPredictCurrentOrder);
if(blocksPredictCurrentOrder.equals(blocksPredictOrder)){
String prediction = "You predicted the correct outcome! :)";
Text message = Text.of(prediction);
player.sendMessage(message);
return "ok";
} else {
String prediction = "You predicted the wrong outcome, but I know you can do better!";
Text message = Text.of(prediction);
player.sendMessage(message);
return "try again";
}
//TODO: check if the blocks are in the right order
}
@Override
public void addBlock(String whereToAdd, Block block, BlockPos pos){
BachelorProef.LOGGER.info("Adding block to " + whereToAdd);
BachelorProef.LOGGER.info(this.toString());
if(whereToAdd.equals("Predict")){
BlockPos newPos = new BlockPos(pos.getX(), pos.getY() + 1, pos.getZ()); //needs to be above the other block
blocksPredict.add(newPos);
}
}
@Override
public BlockPos getPosition(Integer Position) {
BachelorProef.LOGGER.info("BlockPositions: " + blocksPredict);
BachelorProef.LOGGER.info("Blocks: " + blocksPredictOrder);
Collections.reverse(blocksPredict);
BlockPos pos = blocksPredict.get(Position);
Collections.reverse(blocksPredict);
return pos;
}
@Override
public void runRun(PlayerEntity player) {
//TODO: place te input blocks in the right order
ArrayList<Integer> counter = new ArrayList<>();
blocksPredictOrder.forEach(block -> {
//BachelorProef.LOGGER.info("Block: " + block);
BlockPos pos = blocksPredict.get(blocksPredictOrder.size() - 1 - counter.size());
player.getWorld().setBlockState(pos, block.getDefaultState());
counter.add(1);
});
//packet to client to run scheme code on client side -> file is on client side
BachelorProef.LOGGER.info("PLAYER WHEN RUNNING RUN: " + player.toString());
//TODO: send to client to open terminal and save window to control
ServerPlayNetworking.send((ServerPlayerEntity) player, ModPackets.OPEN_TERMINAL, PacketByteBufs.empty());
//send actions back to the server
PlayerMixinInterface playerInterface = (PlayerMixinInterface) player;
Shrine shrine = playerInterface.getShrine();
String answer = shrine.runCode(blocksPredictOrder, "insertion-sort", player);
BachelorProef.LOGGER.info("Answer: " + answer);
//jsint.Pair pair = (jsint.Pair) shrine.predictModify();
BachelorProef.LOGGER.info("Running run");
}
@Override
public void runInvestigate() {
BachelorProef.LOGGER.info("Running investigate");
}
@Override
public void runModify() {
//Dit moet op client side gerund worden om de edits van de client te kunnen ontvangen
BachelorProef.LOGGER.info("Running modify");
}
@Override
public void runMake() {
//Dit moet ook op client side gerund worden om de edits van de client te kunnen ontvangen
BachelorProef.LOGGER.info("Running make");
}
}
| GamerCatGirl/BachelorProefMod | src/main/java/siheynde/bachelorproefmod/structure/functions/StrictComparisonBubbleSort.java | 1,435 | //Dit moet ook op client side gerund worden om de edits van de client te kunnen ontvangen | line_comment | nl | package siheynde.bachelorproefmod.structure.functions;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import siheynde.bachelorproefmod.BachelorProef;
import siheynde.bachelorproefmod.networking.ModPackets;
import siheynde.bachelorproefmod.structure.shrine.Shrine;
import siheynde.bachelorproefmod.util.PlayerMixinInterface;
import java.util.*;
//This will always be executed server side
public class StrictComparisonBubbleSort implements SubTopic {
public ArrayList<BlockPos> blocksPredict = new ArrayList<>();
public List<Block> blocksPredictOrder = Arrays.asList(
Blocks.BLACK_STAINED_GLASS,
Blocks.GRAY_STAINED_GLASS,
Blocks.BLACK_STAINED_GLASS,
Blocks.WHITE_STAINED_GLASS);
@Override
public String runPredict(PlayerEntity player) {
World world = player.getWorld();
BachelorProef.LOGGER.info("Running predict");
BachelorProef.LOGGER.info("Blocks: " + blocksPredict);
List<Block> blocksPredictCurrentOrder = new ArrayList<>();
blocksPredict.forEach(blockpos -> {
BachelorProef.LOGGER.info("Block: " + blockpos);
Block block = world.getBlockState(blockpos).getBlock();
BachelorProef.LOGGER.info("Block: " + block);
blocksPredictCurrentOrder.add(block);
});
Collections.reverse(blocksPredictCurrentOrder);
BachelorProef.LOGGER.info("Blocks current order: " + blocksPredictCurrentOrder);
if(blocksPredictCurrentOrder.equals(blocksPredictOrder)){
String prediction = "You predicted the correct outcome! :)";
Text message = Text.of(prediction);
player.sendMessage(message);
return "ok";
} else {
String prediction = "You predicted the wrong outcome, but I know you can do better!";
Text message = Text.of(prediction);
player.sendMessage(message);
return "try again";
}
//TODO: check if the blocks are in the right order
}
@Override
public void addBlock(String whereToAdd, Block block, BlockPos pos){
BachelorProef.LOGGER.info("Adding block to " + whereToAdd);
BachelorProef.LOGGER.info(this.toString());
if(whereToAdd.equals("Predict")){
BlockPos newPos = new BlockPos(pos.getX(), pos.getY() + 1, pos.getZ()); //needs to be above the other block
blocksPredict.add(newPos);
}
}
@Override
public BlockPos getPosition(Integer Position) {
BachelorProef.LOGGER.info("BlockPositions: " + blocksPredict);
BachelorProef.LOGGER.info("Blocks: " + blocksPredictOrder);
Collections.reverse(blocksPredict);
BlockPos pos = blocksPredict.get(Position);
Collections.reverse(blocksPredict);
return pos;
}
@Override
public void runRun(PlayerEntity player) {
//TODO: place te input blocks in the right order
ArrayList<Integer> counter = new ArrayList<>();
blocksPredictOrder.forEach(block -> {
//BachelorProef.LOGGER.info("Block: " + block);
BlockPos pos = blocksPredict.get(blocksPredictOrder.size() - 1 - counter.size());
player.getWorld().setBlockState(pos, block.getDefaultState());
counter.add(1);
});
//packet to client to run scheme code on client side -> file is on client side
BachelorProef.LOGGER.info("PLAYER WHEN RUNNING RUN: " + player.toString());
//TODO: send to client to open terminal and save window to control
ServerPlayNetworking.send((ServerPlayerEntity) player, ModPackets.OPEN_TERMINAL, PacketByteBufs.empty());
//send actions back to the server
PlayerMixinInterface playerInterface = (PlayerMixinInterface) player;
Shrine shrine = playerInterface.getShrine();
String answer = shrine.runCode(blocksPredictOrder, "insertion-sort", player);
BachelorProef.LOGGER.info("Answer: " + answer);
//jsint.Pair pair = (jsint.Pair) shrine.predictModify();
BachelorProef.LOGGER.info("Running run");
}
@Override
public void runInvestigate() {
BachelorProef.LOGGER.info("Running investigate");
}
@Override
public void runModify() {
//Dit moet op client side gerund worden om de edits van de client te kunnen ontvangen
BachelorProef.LOGGER.info("Running modify");
}
@Override
public void runMake() {
//Dit moet<SUF>
BachelorProef.LOGGER.info("Running make");
}
}
|
113755_6 | package org.xdemo.app.xutils.j2se;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
/**
* @author Goofy [email protected] <a href="http://www.xdemo.org">www.xdemo.org</a>
* @Date 2017年8月21日 下午7:03:16
*/
public class GeoUtils {
/**
* 判断某个点,是否在某个区域内 java.awt.geom 提供用于在与二维几何形状相关的对象上定义和执行操作的 Java 2D 类。
*
* @param point
* 目标点
* @param points
* 点集合,形成闭合区域
* @return
*/
public static boolean isInPolygon(Double[] point, Double[]... points) {
if (point.length != 2)
return false;
if (points.length < 3)
return false;
Point2D.Double _point = new Point2D.Double(point[0], point[1]);
List<Point2D.Double> _points = new ArrayList<Point2D.Double>();
for (Double[] _p : points) {
if (_p.length != 2)
return false;
_points.add(new Point2D.Double(_p[0], _p[1]));
}
return isInPolygon(_point, _points);
}
/**
* 判断某个点,是否在某个区域内 java.awt.geom 提供用于在与二维几何形状相关的对象上定义和执行操作的 Java 2D 类。
*
* @param point
* 目标点
* @param points
* 点集合,形成闭合区域
* @return
*/
public static boolean isInPolygon(Point2D.Double point, List<Point2D.Double> points) {
int N = points.size();
boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0;// cross points count of x
double precision = 2e-10; // 浮点类型计算时候与0比较时候的容差
Point2D.Double p1, p2;// neighbour bound vertices
Point2D.Double p = point; // 当前点
p1 = points.get(0);// left vertex
for (int i = 1; i <= N; ++i) {// check all rays
if (p.equals(p1)) {
return boundOrVertex;// p is an vertex
}
p2 = points.get(i % N);// right vertex
if (p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)) {// ray
// is
// outside
// of
// our
// interests
p1 = p2;
continue;// next ray left point
}
if (p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)) {// ray
// is
// crossing
// over
// by
// the
// algorithm
// (common
// part
// of)
if (p.y <= Math.max(p1.y, p2.y)) {// x is before of ray
if (p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)) {// overlies
// on a
// horizontal
// ray
return boundOrVertex;
}
if (p1.y == p2.y) {// ray is vertical
if (p1.y == p.y) {// overlies on a vertical ray
return boundOrVertex;
} else {// before ray
++intersectCount;
}
} else {// cross point on the left side
double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;// cross
// point
// of
// y
if (Math.abs(p.y - xinters) < precision) {// overlies on
// a ray
return boundOrVertex;
}
if (p.y < xinters) {// before ray
++intersectCount;
}
}
}
} else {// special case when ray is crossing through the vertex
if (p.x == p2.x && p.y <= p2.y) {// p crossing over p2
Point2D.Double p3 = points.get((i + 1) % N); // next vertex
if (p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)) {// p.x
// lies
// between
// p1.x
// &
// p3.x
++intersectCount;
} else {
intersectCount += 2;
}
}
}
p1 = p2;// next ray left point
}
if (intersectCount % 2 == 0) {// 偶数在多边形外
return false;
} else { // 奇数在多边形内
return true;
}
}
/**
* 地球的半径有以下三个常用值:
* 极半径
* 从地心到北极或南极的距离,大约6356.公里(两极的差极小,可以忽略).
* 赤道半径
* 是从地心到赤道的距离,大约6378公里.
* 平均半径
* 大约6371..这个数字是地心到地球表面所有各点距离的平均值.
*/
private static double EARTH_RADIUS = 6378.137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* 根据两个位置的经纬度,来计算两地的距离(单位为KM) 参数为String类型
*
* @param lat1
* 第一个点经度
* @param lng1
* 第一个点纬度
* @param lat2
* 第二个点经度
* @param lng2
* 第二个点纬
* @return
*/
public static Double getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
Double lat1 = Double.parseDouble(lat1Str);
Double lng1 = Double.parseDouble(lng1Str);
Double lat2 = Double.parseDouble(lat2Str);
Double lng2 = Double.parseDouble(lng2Str);
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double difference = radLat1 - radLat2;
double mdifference = rad(lng1) - rad(lng2);
double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2)));
distance = distance * EARTH_RADIUS;
distance = Math.round(distance * 10000) / 10000;
return distance;
}}
| GaoFeiGit/xutils | src/org/xdemo/app/xutils/j2se/GeoUtils.java | 2,204 | // p is an vertex
| line_comment | nl | package org.xdemo.app.xutils.j2se;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
/**
* @author Goofy [email protected] <a href="http://www.xdemo.org">www.xdemo.org</a>
* @Date 2017年8月21日 下午7:03:16
*/
public class GeoUtils {
/**
* 判断某个点,是否在某个区域内 java.awt.geom 提供用于在与二维几何形状相关的对象上定义和执行操作的 Java 2D 类。
*
* @param point
* 目标点
* @param points
* 点集合,形成闭合区域
* @return
*/
public static boolean isInPolygon(Double[] point, Double[]... points) {
if (point.length != 2)
return false;
if (points.length < 3)
return false;
Point2D.Double _point = new Point2D.Double(point[0], point[1]);
List<Point2D.Double> _points = new ArrayList<Point2D.Double>();
for (Double[] _p : points) {
if (_p.length != 2)
return false;
_points.add(new Point2D.Double(_p[0], _p[1]));
}
return isInPolygon(_point, _points);
}
/**
* 判断某个点,是否在某个区域内 java.awt.geom 提供用于在与二维几何形状相关的对象上定义和执行操作的 Java 2D 类。
*
* @param point
* 目标点
* @param points
* 点集合,形成闭合区域
* @return
*/
public static boolean isInPolygon(Point2D.Double point, List<Point2D.Double> points) {
int N = points.size();
boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0;// cross points count of x
double precision = 2e-10; // 浮点类型计算时候与0比较时候的容差
Point2D.Double p1, p2;// neighbour bound vertices
Point2D.Double p = point; // 当前点
p1 = points.get(0);// left vertex
for (int i = 1; i <= N; ++i) {// check all rays
if (p.equals(p1)) {
return boundOrVertex;// p is<SUF>
}
p2 = points.get(i % N);// right vertex
if (p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)) {// ray
// is
// outside
// of
// our
// interests
p1 = p2;
continue;// next ray left point
}
if (p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)) {// ray
// is
// crossing
// over
// by
// the
// algorithm
// (common
// part
// of)
if (p.y <= Math.max(p1.y, p2.y)) {// x is before of ray
if (p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)) {// overlies
// on a
// horizontal
// ray
return boundOrVertex;
}
if (p1.y == p2.y) {// ray is vertical
if (p1.y == p.y) {// overlies on a vertical ray
return boundOrVertex;
} else {// before ray
++intersectCount;
}
} else {// cross point on the left side
double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;// cross
// point
// of
// y
if (Math.abs(p.y - xinters) < precision) {// overlies on
// a ray
return boundOrVertex;
}
if (p.y < xinters) {// before ray
++intersectCount;
}
}
}
} else {// special case when ray is crossing through the vertex
if (p.x == p2.x && p.y <= p2.y) {// p crossing over p2
Point2D.Double p3 = points.get((i + 1) % N); // next vertex
if (p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)) {// p.x
// lies
// between
// p1.x
// &
// p3.x
++intersectCount;
} else {
intersectCount += 2;
}
}
}
p1 = p2;// next ray left point
}
if (intersectCount % 2 == 0) {// 偶数在多边形外
return false;
} else { // 奇数在多边形内
return true;
}
}
/**
* 地球的半径有以下三个常用值:
* 极半径
* 从地心到北极或南极的距离,大约6356.公里(两极的差极小,可以忽略).
* 赤道半径
* 是从地心到赤道的距离,大约6378公里.
* 平均半径
* 大约6371..这个数字是地心到地球表面所有各点距离的平均值.
*/
private static double EARTH_RADIUS = 6378.137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* 根据两个位置的经纬度,来计算两地的距离(单位为KM) 参数为String类型
*
* @param lat1
* 第一个点经度
* @param lng1
* 第一个点纬度
* @param lat2
* 第二个点经度
* @param lng2
* 第二个点纬
* @return
*/
public static Double getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
Double lat1 = Double.parseDouble(lat1Str);
Double lng1 = Double.parseDouble(lng1Str);
Double lat2 = Double.parseDouble(lat2Str);
Double lng2 = Double.parseDouble(lng2Str);
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double difference = radLat1 - radLat2;
double mdifference = rad(lng1) - rad(lng2);
double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2)));
distance = distance * EARTH_RADIUS;
distance = Math.round(distance * 10000) / 10000;
return distance;
}}
|
45931_3 | import com.jaunt.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Semaphore;
/**
* http://jaunt-api.com/jaunt-tutorial.htm
*/
public class Main {
private static PrintWriter writer;
private static Semaphore semaphore;
private static Semaphore semaphore2;
private static int curr;
private static int count;
public static void main(String[] args) {
semaphore = new Semaphore(1);
semaphore2 = new Semaphore(1);
try {
writer = new PrintWriter("output.csv", "UTF-8");
for (int i = 1; i < 2399; i++) {
semaphore2.acquire();
curr = i;
new Thread(() -> {
try {
int curr2 = curr;
semaphore2.release();
UserAgent userAgent = new UserAgent(); //create new userAgent (headless browser).
boolean success = false;
while (!success) {
try {
userAgent.visit("https://www.zorgkaartnederland.nl/zorginstelling/pagina" + curr2 + "?sort=naam-asc");
success = true;
} catch (JauntException e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}
userAgent.visit("https://www.zorgkaartnederland.nl/zorginstelling/pagina" + curr2 + "?sort=naam-asc");
Elements divs = userAgent.doc.findEach("<div class=\"media-body\">");
for (Element div : divs) {
Element p = div.findFirst("<p class=\"description\">");
writer.print(p.getChildText() + ",");
// get url link
Element h = div.getFirst("<h4 class=\"media-heading title orange\">");
Element href = h.getFirst("<a href");
String url = href.toString();
url = url.substring(9, url.length() - 2);
Element company = h.getFirst("<a href=\"" + url + "\">");
semaphore.acquire();
writer.print(company.getChildText() + ",");
semaphore.release();
// Adress url info
UserAgent userAgent2 = new UserAgent();
success = false;
while (!success) {
try {
userAgent2.visit(url);
success = true;
} catch (JauntException e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}
Element div2 = userAgent2.doc.findEach("<div class=\"address_row\">");
Element div3 = div2.findFirst("<span class=\"address_content\">");
semaphore.acquire();
writer.print(div3.getChildText().trim() + ",");
semaphore.release();
Element span = div2.getElement(1);
Element span2 = span.getFirst("<span>");
Elements spans = span2.getEach("<span>");
semaphore.acquire();
writer.println(spans.getElement(0).getChildText() + "," + spans.getElement(1).getChildText());
semaphore.release();
userAgent2.close();
count++;
}
} catch (JauntException | IOException | InterruptedException e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}).start();
}
new Thread(() -> {
while (count < 2399) {
writer.close();
}
}).start();
} catch (Exception e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}
}
| GarciaSiego/ScrubbingWithNiels | src/Main.java | 1,128 | //www.zorgkaartnederland.nl/zorginstelling/pagina" + curr2 + "?sort=naam-asc"); | line_comment | nl | import com.jaunt.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Semaphore;
/**
* http://jaunt-api.com/jaunt-tutorial.htm
*/
public class Main {
private static PrintWriter writer;
private static Semaphore semaphore;
private static Semaphore semaphore2;
private static int curr;
private static int count;
public static void main(String[] args) {
semaphore = new Semaphore(1);
semaphore2 = new Semaphore(1);
try {
writer = new PrintWriter("output.csv", "UTF-8");
for (int i = 1; i < 2399; i++) {
semaphore2.acquire();
curr = i;
new Thread(() -> {
try {
int curr2 = curr;
semaphore2.release();
UserAgent userAgent = new UserAgent(); //create new userAgent (headless browser).
boolean success = false;
while (!success) {
try {
userAgent.visit("https://www.zorgkaartnederland.nl/zorginstelling/pagina" + curr2 + "?sort=naam-asc");
success = true;
} catch (JauntException e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}
userAgent.visit("https://www.zorgkaartnederland.nl/zorginstelling/pagina" +<SUF>
Elements divs = userAgent.doc.findEach("<div class=\"media-body\">");
for (Element div : divs) {
Element p = div.findFirst("<p class=\"description\">");
writer.print(p.getChildText() + ",");
// get url link
Element h = div.getFirst("<h4 class=\"media-heading title orange\">");
Element href = h.getFirst("<a href");
String url = href.toString();
url = url.substring(9, url.length() - 2);
Element company = h.getFirst("<a href=\"" + url + "\">");
semaphore.acquire();
writer.print(company.getChildText() + ",");
semaphore.release();
// Adress url info
UserAgent userAgent2 = new UserAgent();
success = false;
while (!success) {
try {
userAgent2.visit(url);
success = true;
} catch (JauntException e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}
Element div2 = userAgent2.doc.findEach("<div class=\"address_row\">");
Element div3 = div2.findFirst("<span class=\"address_content\">");
semaphore.acquire();
writer.print(div3.getChildText().trim() + ",");
semaphore.release();
Element span = div2.getElement(1);
Element span2 = span.getFirst("<span>");
Elements spans = span2.getEach("<span>");
semaphore.acquire();
writer.println(spans.getElement(0).getChildText() + "," + spans.getElement(1).getChildText());
semaphore.release();
userAgent2.close();
count++;
}
} catch (JauntException | IOException | InterruptedException e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}).start();
}
new Thread(() -> {
while (count < 2399) {
writer.close();
}
}).start();
} catch (Exception e) { //if an HTTP/connection error occurs, handle JauntException.
System.err.println(e.getMessage());
}
}
}
|
47662_54 | /*
* RepositioningInfo.java
*
* Copyright (c) 1995-2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* Angel Kirilov, 04/January/2002
*
* $Id: RepositioningInfo.java 18950 2015-10-15 12:37:29Z ian_roberts $
*/
package gate.corpora;
import gate.corpora.RepositioningInfo.PositionInfo;
import gate.util.Out;
import java.io.Serializable;
import java.util.ArrayList;
/**
* RepositioningInfo keep information about correspondence of positions
* between the original and extracted document content. With this information
* this class could be used for computing of this correspondence in the strict
* way (return -1 where is no correspondence)
* or in "flow" way (return near computable position)
*/
public class RepositioningInfo extends ArrayList<PositionInfo> {
/** Freeze the serialization UID. */
static final long serialVersionUID = -2895662600168468559L;
/** Debug flag */
private static final boolean DEBUG = false;
/**
* Just information keeper inner class. No significant functionality.
*/
public class PositionInfo implements Serializable {
/** Freeze the serialization UID. */
static final long serialVersionUID = -7747351720249898499L;
/** Data members for one peace of text information */
private long m_origPos, m_origLength, m_currPos, m_currLength;
/** The only constructor. We haven't set methods for data members. */
public PositionInfo(long orig, long origLen, long curr, long currLen) {
m_origPos = orig;
m_origLength = origLen;
m_currPos = curr;
m_currLength = currLen;
} // PositionInfo
/** Position in the extracted (and probably changed) content */
public long getCurrentPosition() {
return m_currPos;
} // getCurrentPosition
/** Position in the original content */
public long getOriginalPosition() {
return m_origPos;
} // getOriginalPosition
/** Length of peace of text in the original content */
public long getOriginalLength() {
return m_origLength;
} // getOriginalLength
/** Length of peace of text in the extracted content */
public long getCurrentLength() {
return m_currLength;
} // getCurrentLength
/** For debug purposes */
@Override
public String toString() {
return "("+m_origPos+","+m_origLength+","
+m_currPos+","+m_currLength+")";
} // toString
} // class PositionInfo
/** Default constructor */
public RepositioningInfo() {
super();
} // RepositioningInfo
/** Create a new position information record. */
public void addPositionInfo(long origPos, long origLength,
long currPos, long currLength) {
// sorted add of new position
int insertPos = 0;
PositionInfo lastPI;
for(int i = size(); i>0; i--) {
lastPI = get(i-1);
if(lastPI.getOriginalPosition() < origPos) {
insertPos = i;
break;
} // if - sort key
} // for
add(insertPos, new PositionInfo(origPos, origLength, currPos, currLength));
} // addPositionInfo
/** Compute position in extracted content by position in the original content.
* If there is no correspondence return -1.
*/
public long getExtractedPos(long absPos) {
long result = absPos;
PositionInfo currPI = null;
int size = size();
if(size != 0) {
long origPos, origLen;
boolean found = false;
for(int i=0; i<size; ++i) {
currPI = get(i);
origPos = currPI.getOriginalPosition();
origLen = currPI.getOriginalLength();
if(absPos <= origPos+origLen) {
if(absPos < origPos) {
// outside the range of information
result = -1;
}
else {
if(absPos == origPos+origLen) {
// special case for boundaries - if absPos is the end boundary of
// this PositionInfo record (origPos+origLen) then result should
// always be the end boundary too (extracted pos + extracted len).
// Without this check we may get the wrong position when the "orig"
// length is shorter than the "extracted" length.
result = currPI.getCurrentPosition() + currPI.getCurrentLength();
} else {
// current position + offset in this PositionInfo record
result = currPI.getCurrentPosition() + absPos - origPos;
}
// but don't go beyond the extracted length
if(result > currPI.getCurrentPosition() + currPI.getCurrentLength()) {
result = currPI.getCurrentPosition() + currPI.getCurrentLength();
}
} // if
found = true;
break;
} // if
} // for
if(!found) {
// after the last repositioning info
result = -1;
} // if - !found
} // if
return result;
} // getExtractedPos
public long getOriginalPos(long relPos) {
return getOriginalPos(relPos, false);
} // getOriginalPos
/** Compute position in original content by position in the extracted content.
* If there is no correspondence return -1.
*/
public long getOriginalPos(long relPos, boolean afterChar) {
long result = relPos;
PositionInfo currPI = null;
int size = size();
if(size != 0) {
long currPos, currLen;
boolean found = false;
for(int i=0; i<size; ++i) {
currPI = get(i);
currPos = currPI.getCurrentPosition();
currLen = currPI.getCurrentLength();
if((afterChar || i == size-1) && relPos == currPos+currLen) {
result = currPI.getOriginalPosition() + currPI.getOriginalLength();
found = true;
break;
} // if
if(relPos < currPos+currLen) {
if(relPos < currPos) {
// outside the range of information
result = -1;
}
else {
// current position + offset in this PositionInfo record
result = currPI.getOriginalPosition() + relPos - currPos;
} // if
found = true;
break;
} // if
} // for
if(!found) {
// after the last repositioning info
result = -1;
} // if - !found
} // if
return result;
} // getOriginalPos
/** Not finished yet */
public long getExtractedPosFlow(long absPos) {
long result = -1;
return result;
} // getExtractedPosFlow
/** Not finished yet */
public long getOriginalPosFlow(long relPos) {
long result = -1;
return result;
} // getOriginalPosFlow
/**
* Return the position info index containing <B>@param absPos</B>
* If there is no such position info return -1.
*/
public int getIndexByOriginalPosition(long absPos) {
PositionInfo currPI = null;
int result = -1;
int size = size();
long origPos, origLen;
// Find with the liniear algorithm. Could be extended to binary search.
for(int i=0; i<size; ++i) {
currPI = get(i);
origPos = currPI.getOriginalPosition();
origLen = currPI.getOriginalLength();
if(absPos <= origPos+origLen) {
if(absPos >= origPos) {
result = i;
} // if
break;
} // if
} // for
return result;
} // getItemByOriginalPosition
/**
* Return the position info index containing <B>@param absPos</B>
* or the index of record before this position.
* Result is -1 if the position is before the first record.
* Rezult is size() if the position is after the last record.
*/
public int getIndexByOriginalPositionFlow(long absPos) {
PositionInfo currPI = null;
int size = size();
int result = size;
long origPos, origLen;
// Find with the liniear algorithm. Could be extended to binary search.
for(int i=0; i<size; ++i) {
currPI = get(i);
origPos = currPI.getOriginalPosition();
origLen = currPI.getOriginalLength();
if(absPos <= origPos+origLen) {
// is inside of current record
if(absPos >= origPos) {
result = i;
}
else {
// not inside the current recort - return previous
result = i-1;
} // if
break;
} // if
} // for
return result;
} // getItemByOriginalPositionFlow
/**
* Correct the RepositioningInfo structure for shrink/expand changes.
* <br>
*
* Normaly the text peaces have same sizes in both original text and
* extracted text. But in some cases there are nonlinear substitutions.
* For example the sequence "&lt;" is converted to "<".
* <br>
*
* The correction will split the corresponding PositionInfo structure to
* 3 new records - before correction, correction record and after correction.
* Front and end records are the same maner like the original record -
* m_origLength == m_currLength, since the middle record has different
* values because of shrink/expand changes. All records after this middle
* record should be corrected with the difference between these values.
* <br>
*
* All m_currPos above the current information record should be corrected
* with (origLen - newLen) i.e.
* <code> m_currPos -= origLen - newLen; </code>
* <br>
*
* @param originalPos Position of changed text in the original content.
* @param origLen Length of changed peace of text in the original content.
* @param newLen Length of new peace of text substiting the original peace.
*/
public void correctInformation(long originalPos, long origLen, long newLen) {
PositionInfo currPI;
PositionInfo frontPI, correctPI, endPI;
int index = getIndexByOriginalPositionFlow(originalPos);
// correct the index when the originalPos precede all records
if(index == -1) {
index = 0;
} // if
// correction of all other information records
// All m_currPos above the current record should be corrected with
// (origLen - newLen) i.e. <code> m_currPos -= origLen - newLen; </code>
for(int i=index; i<size(); ++i) {
currPI = get(i);
currPI.m_currPos -= origLen - newLen;
} // for
currPI = get(index);
if(originalPos >= currPI.m_origPos
&& currPI.m_origPos + currPI.m_origLength >= originalPos + origLen) {
long frontLen = originalPos - currPI.m_origPos;
frontPI = new PositionInfo(currPI.m_origPos,
frontLen,
currPI.m_currPos,
frontLen);
correctPI = new PositionInfo(originalPos,
origLen,
currPI.m_currPos + frontLen,
newLen);
long endLen = currPI.m_origLength - frontLen - origLen;
endPI = new PositionInfo(originalPos + origLen,
endLen,
currPI.m_currPos + frontLen + newLen,
endLen);
set(index, frontPI); // substitute old element
if(endPI.m_origLength > 0) {
add(index+1, endPI); // insert new end element
} // if
if(correctPI.m_origLength > 0) {
add(index+1, correctPI); // insert middle new element
} // if
} // if - substitution range check
} // correctInformation
/**
* Correct the original position information in the records. When some text
* is shrinked/expanded by the parser. With this method is corrected the
* substitution of "\r\n" with "\n".
*/
public void correctInformationOriginalMove(long originalPos, long moveLen) {
PositionInfo currPI;
if(DEBUG) {
if(originalPos < 380) // debug information restriction
Out.println("Before correction: "+this);
} // DEBUG
int index = getIndexByOriginalPositionFlow(originalPos);
// correct the index when the originalPos precede all records
if(index == -1) {
index = 0;
} // if
// position is after all records in list
if(index == size()) {
return;
} // if
for(int i = index+1; i<size(); ++i) {
currPI = get(i);
currPI.m_origPos += moveLen;
} // for
currPI = get(index);
// should we split this record to two new records (inside the record)
if(originalPos > currPI.m_origPos) {
if(originalPos < currPI.m_origPos + currPI.m_origLength) {
PositionInfo frontPI, endPI;
long frontLen = originalPos - currPI.m_origPos;
frontPI = new PositionInfo(currPI.m_origPos,
frontLen,
currPI.m_currPos,
frontLen);
long endLen = currPI.m_origLength - frontLen;
endPI = new PositionInfo(originalPos + moveLen,
endLen,
currPI.m_currPos + frontLen,
endLen);
set(index, frontPI); // substitute old element
if(endPI.m_origLength != 0) {
add(index+1, endPI); // insert new end element
} // if - should add this record
if(DEBUG) {
if(originalPos < 380) { // debug information restriction
Out.println("Point 2. Current: "+currPI);
Out.println("Point 2. frontPI: "+frontPI);
Out.println("Point 2. endPI: "+endPI);
}
} // DEBUG
} // if - inside the record
} // if
else {
// correction if the position is before the current record
currPI.m_origPos += moveLen;
}
if(DEBUG) {
if(originalPos < 380) {
Out.println("Correction move: "+originalPos+", "+moveLen);
Out.println("Corrected: "+this);
Out.println("index: "+index);
/*
Exception ex = new Exception();
Out.println("Call point: ");
ex.printStackTrace();
*/
}
} // DEBUG
} // correctInformationOriginalMove
} // class RepositioningInfo | GateNLP/gate-core | src/main/java/gate/corpora/RepositioningInfo.java | 4,200 | // insert new end element | line_comment | nl | /*
* RepositioningInfo.java
*
* Copyright (c) 1995-2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* Angel Kirilov, 04/January/2002
*
* $Id: RepositioningInfo.java 18950 2015-10-15 12:37:29Z ian_roberts $
*/
package gate.corpora;
import gate.corpora.RepositioningInfo.PositionInfo;
import gate.util.Out;
import java.io.Serializable;
import java.util.ArrayList;
/**
* RepositioningInfo keep information about correspondence of positions
* between the original and extracted document content. With this information
* this class could be used for computing of this correspondence in the strict
* way (return -1 where is no correspondence)
* or in "flow" way (return near computable position)
*/
public class RepositioningInfo extends ArrayList<PositionInfo> {
/** Freeze the serialization UID. */
static final long serialVersionUID = -2895662600168468559L;
/** Debug flag */
private static final boolean DEBUG = false;
/**
* Just information keeper inner class. No significant functionality.
*/
public class PositionInfo implements Serializable {
/** Freeze the serialization UID. */
static final long serialVersionUID = -7747351720249898499L;
/** Data members for one peace of text information */
private long m_origPos, m_origLength, m_currPos, m_currLength;
/** The only constructor. We haven't set methods for data members. */
public PositionInfo(long orig, long origLen, long curr, long currLen) {
m_origPos = orig;
m_origLength = origLen;
m_currPos = curr;
m_currLength = currLen;
} // PositionInfo
/** Position in the extracted (and probably changed) content */
public long getCurrentPosition() {
return m_currPos;
} // getCurrentPosition
/** Position in the original content */
public long getOriginalPosition() {
return m_origPos;
} // getOriginalPosition
/** Length of peace of text in the original content */
public long getOriginalLength() {
return m_origLength;
} // getOriginalLength
/** Length of peace of text in the extracted content */
public long getCurrentLength() {
return m_currLength;
} // getCurrentLength
/** For debug purposes */
@Override
public String toString() {
return "("+m_origPos+","+m_origLength+","
+m_currPos+","+m_currLength+")";
} // toString
} // class PositionInfo
/** Default constructor */
public RepositioningInfo() {
super();
} // RepositioningInfo
/** Create a new position information record. */
public void addPositionInfo(long origPos, long origLength,
long currPos, long currLength) {
// sorted add of new position
int insertPos = 0;
PositionInfo lastPI;
for(int i = size(); i>0; i--) {
lastPI = get(i-1);
if(lastPI.getOriginalPosition() < origPos) {
insertPos = i;
break;
} // if - sort key
} // for
add(insertPos, new PositionInfo(origPos, origLength, currPos, currLength));
} // addPositionInfo
/** Compute position in extracted content by position in the original content.
* If there is no correspondence return -1.
*/
public long getExtractedPos(long absPos) {
long result = absPos;
PositionInfo currPI = null;
int size = size();
if(size != 0) {
long origPos, origLen;
boolean found = false;
for(int i=0; i<size; ++i) {
currPI = get(i);
origPos = currPI.getOriginalPosition();
origLen = currPI.getOriginalLength();
if(absPos <= origPos+origLen) {
if(absPos < origPos) {
// outside the range of information
result = -1;
}
else {
if(absPos == origPos+origLen) {
// special case for boundaries - if absPos is the end boundary of
// this PositionInfo record (origPos+origLen) then result should
// always be the end boundary too (extracted pos + extracted len).
// Without this check we may get the wrong position when the "orig"
// length is shorter than the "extracted" length.
result = currPI.getCurrentPosition() + currPI.getCurrentLength();
} else {
// current position + offset in this PositionInfo record
result = currPI.getCurrentPosition() + absPos - origPos;
}
// but don't go beyond the extracted length
if(result > currPI.getCurrentPosition() + currPI.getCurrentLength()) {
result = currPI.getCurrentPosition() + currPI.getCurrentLength();
}
} // if
found = true;
break;
} // if
} // for
if(!found) {
// after the last repositioning info
result = -1;
} // if - !found
} // if
return result;
} // getExtractedPos
public long getOriginalPos(long relPos) {
return getOriginalPos(relPos, false);
} // getOriginalPos
/** Compute position in original content by position in the extracted content.
* If there is no correspondence return -1.
*/
public long getOriginalPos(long relPos, boolean afterChar) {
long result = relPos;
PositionInfo currPI = null;
int size = size();
if(size != 0) {
long currPos, currLen;
boolean found = false;
for(int i=0; i<size; ++i) {
currPI = get(i);
currPos = currPI.getCurrentPosition();
currLen = currPI.getCurrentLength();
if((afterChar || i == size-1) && relPos == currPos+currLen) {
result = currPI.getOriginalPosition() + currPI.getOriginalLength();
found = true;
break;
} // if
if(relPos < currPos+currLen) {
if(relPos < currPos) {
// outside the range of information
result = -1;
}
else {
// current position + offset in this PositionInfo record
result = currPI.getOriginalPosition() + relPos - currPos;
} // if
found = true;
break;
} // if
} // for
if(!found) {
// after the last repositioning info
result = -1;
} // if - !found
} // if
return result;
} // getOriginalPos
/** Not finished yet */
public long getExtractedPosFlow(long absPos) {
long result = -1;
return result;
} // getExtractedPosFlow
/** Not finished yet */
public long getOriginalPosFlow(long relPos) {
long result = -1;
return result;
} // getOriginalPosFlow
/**
* Return the position info index containing <B>@param absPos</B>
* If there is no such position info return -1.
*/
public int getIndexByOriginalPosition(long absPos) {
PositionInfo currPI = null;
int result = -1;
int size = size();
long origPos, origLen;
// Find with the liniear algorithm. Could be extended to binary search.
for(int i=0; i<size; ++i) {
currPI = get(i);
origPos = currPI.getOriginalPosition();
origLen = currPI.getOriginalLength();
if(absPos <= origPos+origLen) {
if(absPos >= origPos) {
result = i;
} // if
break;
} // if
} // for
return result;
} // getItemByOriginalPosition
/**
* Return the position info index containing <B>@param absPos</B>
* or the index of record before this position.
* Result is -1 if the position is before the first record.
* Rezult is size() if the position is after the last record.
*/
public int getIndexByOriginalPositionFlow(long absPos) {
PositionInfo currPI = null;
int size = size();
int result = size;
long origPos, origLen;
// Find with the liniear algorithm. Could be extended to binary search.
for(int i=0; i<size; ++i) {
currPI = get(i);
origPos = currPI.getOriginalPosition();
origLen = currPI.getOriginalLength();
if(absPos <= origPos+origLen) {
// is inside of current record
if(absPos >= origPos) {
result = i;
}
else {
// not inside the current recort - return previous
result = i-1;
} // if
break;
} // if
} // for
return result;
} // getItemByOriginalPositionFlow
/**
* Correct the RepositioningInfo structure for shrink/expand changes.
* <br>
*
* Normaly the text peaces have same sizes in both original text and
* extracted text. But in some cases there are nonlinear substitutions.
* For example the sequence "&lt;" is converted to "<".
* <br>
*
* The correction will split the corresponding PositionInfo structure to
* 3 new records - before correction, correction record and after correction.
* Front and end records are the same maner like the original record -
* m_origLength == m_currLength, since the middle record has different
* values because of shrink/expand changes. All records after this middle
* record should be corrected with the difference between these values.
* <br>
*
* All m_currPos above the current information record should be corrected
* with (origLen - newLen) i.e.
* <code> m_currPos -= origLen - newLen; </code>
* <br>
*
* @param originalPos Position of changed text in the original content.
* @param origLen Length of changed peace of text in the original content.
* @param newLen Length of new peace of text substiting the original peace.
*/
public void correctInformation(long originalPos, long origLen, long newLen) {
PositionInfo currPI;
PositionInfo frontPI, correctPI, endPI;
int index = getIndexByOriginalPositionFlow(originalPos);
// correct the index when the originalPos precede all records
if(index == -1) {
index = 0;
} // if
// correction of all other information records
// All m_currPos above the current record should be corrected with
// (origLen - newLen) i.e. <code> m_currPos -= origLen - newLen; </code>
for(int i=index; i<size(); ++i) {
currPI = get(i);
currPI.m_currPos -= origLen - newLen;
} // for
currPI = get(index);
if(originalPos >= currPI.m_origPos
&& currPI.m_origPos + currPI.m_origLength >= originalPos + origLen) {
long frontLen = originalPos - currPI.m_origPos;
frontPI = new PositionInfo(currPI.m_origPos,
frontLen,
currPI.m_currPos,
frontLen);
correctPI = new PositionInfo(originalPos,
origLen,
currPI.m_currPos + frontLen,
newLen);
long endLen = currPI.m_origLength - frontLen - origLen;
endPI = new PositionInfo(originalPos + origLen,
endLen,
currPI.m_currPos + frontLen + newLen,
endLen);
set(index, frontPI); // substitute old element
if(endPI.m_origLength > 0) {
add(index+1, endPI); // insert new end element
} // if
if(correctPI.m_origLength > 0) {
add(index+1, correctPI); // insert middle new element
} // if
} // if - substitution range check
} // correctInformation
/**
* Correct the original position information in the records. When some text
* is shrinked/expanded by the parser. With this method is corrected the
* substitution of "\r\n" with "\n".
*/
public void correctInformationOriginalMove(long originalPos, long moveLen) {
PositionInfo currPI;
if(DEBUG) {
if(originalPos < 380) // debug information restriction
Out.println("Before correction: "+this);
} // DEBUG
int index = getIndexByOriginalPositionFlow(originalPos);
// correct the index when the originalPos precede all records
if(index == -1) {
index = 0;
} // if
// position is after all records in list
if(index == size()) {
return;
} // if
for(int i = index+1; i<size(); ++i) {
currPI = get(i);
currPI.m_origPos += moveLen;
} // for
currPI = get(index);
// should we split this record to two new records (inside the record)
if(originalPos > currPI.m_origPos) {
if(originalPos < currPI.m_origPos + currPI.m_origLength) {
PositionInfo frontPI, endPI;
long frontLen = originalPos - currPI.m_origPos;
frontPI = new PositionInfo(currPI.m_origPos,
frontLen,
currPI.m_currPos,
frontLen);
long endLen = currPI.m_origLength - frontLen;
endPI = new PositionInfo(originalPos + moveLen,
endLen,
currPI.m_currPos + frontLen,
endLen);
set(index, frontPI); // substitute old element
if(endPI.m_origLength != 0) {
add(index+1, endPI); // insert new<SUF>
} // if - should add this record
if(DEBUG) {
if(originalPos < 380) { // debug information restriction
Out.println("Point 2. Current: "+currPI);
Out.println("Point 2. frontPI: "+frontPI);
Out.println("Point 2. endPI: "+endPI);
}
} // DEBUG
} // if - inside the record
} // if
else {
// correction if the position is before the current record
currPI.m_origPos += moveLen;
}
if(DEBUG) {
if(originalPos < 380) {
Out.println("Correction move: "+originalPos+", "+moveLen);
Out.println("Corrected: "+this);
Out.println("index: "+index);
/*
Exception ex = new Exception();
Out.println("Call point: ");
ex.printStackTrace();
*/
}
} // DEBUG
} // correctInformationOriginalMove
} // class RepositioningInfo |
204410_44 | /*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jts.operation.buffer;
import com.vividsolutions.jts.algorithm.Angle;
import com.vividsolutions.jts.algorithm.CGAlgorithms;
import com.vividsolutions.jts.algorithm.HCoordinate;
import com.vividsolutions.jts.algorithm.LineIntersector;
import com.vividsolutions.jts.algorithm.NotRepresentableException;
import com.vividsolutions.jts.algorithm.RobustLineIntersector;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LineSegment;
import com.vividsolutions.jts.geom.PrecisionModel;
import com.vividsolutions.jts.geomgraph.Position;
/**
* Generates segments which form an offset curve.
* Supports all end cap and join options
* provided for buffering.
* This algorithm implements various heuristics to
* produce smoother, simpler curves which are
* still within a reasonable tolerance of the
* true curve.
*
* @author Martin Davis
*/
class OffsetSegmentGenerator {
/**
* Factor which controls how close offset segments can be to
* skip adding a filler or mitre.
*/
private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3;
/**
* Factor which controls how close curve vertices on inside turns can be to be snapped
*/
private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3;
/**
* Factor which controls how close curve vertices can be to be snapped
*/
private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6;
/**
* Factor which determines how short closing segs can be for round buffers
*/
private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80;
/**
* the max error of approximation (distance) between a quad segment and the true fillet curve
*/
private double maxCurveSegmentError = 0.0;
/**
* The angle quantum with which to approximate a fillet curve
* (based on the input # of quadrant segments)
*/
private double filletAngleQuantum;
/**
* The Closing Segment Length Factor controls how long
* "closing segments" are. Closing segments are added
* at the middle of inside corners to ensure a smoother
* boundary for the buffer offset curve.
* In some cases (particularly for round joins with default-or-better
* quantization) the closing segments can be made quite short.
* This substantially improves performance (due to fewer intersections being created).
* <p>
* A closingSegFactor of 0 results in lines to the corner vertex
* A closingSegFactor of 1 results in lines halfway to the corner vertex
* A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex
* (this option is reasonable for the very common default situation of round joins
* and quadrantSegs >= 8)
*/
private int closingSegLengthFactor = 1;
private OffsetSegmentString segList;
private double distance = 0.0;
private PrecisionModel precisionModel;
private BufferParameters bufParams;
private LineIntersector li;
private Coordinate s0, s1, s2;
private LineSegment seg0 = new LineSegment();
private LineSegment seg1 = new LineSegment();
private LineSegment offset0 = new LineSegment();
private LineSegment offset1 = new LineSegment();
private int side = 0;
private boolean hasNarrowConcaveAngle = false;
public OffsetSegmentGenerator(PrecisionModel precisionModel,
BufferParameters bufParams, double distance) {
this.precisionModel = precisionModel;
this.bufParams = bufParams;
// compute intersections in full precision, to provide accuracy
// the points are rounded as they are inserted into the curve line
this.li = new RobustLineIntersector();
this.filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments();
/**
* Non-round joins cause issues with short closing segments, so don't use
* them. In any case, non-round joins only really make sense for relatively
* small buffer distances.
*/
if (bufParams.getQuadrantSegments() >= 8
&& bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) {
this.closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR;
}
this.init(distance);
}
/**
* Tests whether the input has a narrow concave angle
* (relative to the offset distance).
* In this case the generated offset curve will contain self-intersections
* and heuristic closing segments.
* This is expected behaviour in the case of Buffer curves.
* For pure Offset Curves,
* the output needs to be further treated
* before it can be used.
*
* @return true if the input has a narrow concave angle
*/
public boolean hasNarrowConcaveAngle() {
return this.hasNarrowConcaveAngle;
}
private void init(double distance) {
this.distance = distance;
this.maxCurveSegmentError = distance * (1 - Math.cos(this.filletAngleQuantum / 2.0));
this.segList = new OffsetSegmentString();
this.segList.setPrecisionModel(this.precisionModel);
/**
* Choose the min vertex separation as a small fraction of the offset distance.
*/
this.segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR);
}
public void initSideSegments(Coordinate s1, Coordinate s2, int side) {
this.s1 = s1;
this.s2 = s2;
this.side = side;
this.seg1.setCoordinates(s1, s2);
this.computeOffsetSegment(this.seg1, side, this.distance, this.offset1);
}
public Coordinate[] getCoordinates() {
Coordinate[] pts = this.segList.getCoordinates();
return pts;
}
public void closeRing() {
this.segList.closeRing();
}
public void addSegments(Coordinate[] pt, boolean isForward) {
this.segList.addPts(pt, isForward);
}
public void addFirstSegment() {
this.segList.addPt(this.offset1.p0);
}
/**
* Add last offset point
*/
public void addLastSegment() {
this.segList.addPt(this.offset1.p1);
}
//private static double MAX_CLOSING_SEG_LEN = 3.0;
public void addNextSegment(Coordinate p, boolean addStartPoint) {
// s0-s1-s2 are the coordinates of the previous segment and the current one
this.s0 = this.s1;
this.s1 = this.s2;
this.s2 = p;
this.seg0.setCoordinates(this.s0, this.s1);
this.computeOffsetSegment(this.seg0, this.side, this.distance, this.offset0);
this.seg1.setCoordinates(this.s1, this.s2);
this.computeOffsetSegment(this.seg1, this.side, this.distance, this.offset1);
// do nothing if points are equal
if (this.s1.equals(this.s2)) {
return;
}
int orientation = CGAlgorithms.computeOrientation(this.s0, this.s1, this.s2);
boolean outsideTurn =
(orientation == CGAlgorithms.CLOCKWISE && this.side == Position.LEFT)
|| (orientation == CGAlgorithms.COUNTERCLOCKWISE && this.side == Position.RIGHT);
if (orientation == 0) { // lines are collinear
this.addCollinear(addStartPoint);
} else if (outsideTurn) {
this.addOutsideTurn(orientation, addStartPoint);
} else { // inside turn
this.addInsideTurn(orientation, addStartPoint);
}
}
private void addCollinear(boolean addStartPoint) {
/**
* This test could probably be done more efficiently,
* but the situation of exact collinearity should be fairly rare.
*/
this.li.computeIntersection(this.s0, this.s1, this.s1, this.s2);
int numInt = this.li.getIntersectionNum();
/**
* if numInt is < 2, the lines are parallel and in the same direction. In
* this case the point can be ignored, since the offset lines will also be
* parallel.
*/
if (numInt >= 2) {
/**
* segments are collinear but reversing.
* Add an "end-cap" fillet
* all the way around to other direction This case should ONLY happen
* for LineStrings, so the orientation is always CW. (Polygons can never
* have two consecutive segments which are parallel but reversed,
* because that would be a self intersection.
*
*/
if (this.bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL
|| this.bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) {
if (addStartPoint) {
this.segList.addPt(this.offset0.p1);
}
this.segList.addPt(this.offset1.p0);
} else {
this.addFillet(this.s1, this.offset0.p1, this.offset1.p0, CGAlgorithms.CLOCKWISE, this.distance);
}
}
}
/**
* Adds the offset points for an outside (convex) turn
*
* @param orientation
* @param addStartPoint
*/
private void addOutsideTurn(int orientation, boolean addStartPoint) {
/**
* Heuristic: If offset endpoints are very close together,
* just use one of them as the corner vertex.
* This avoids problems with computing mitre corners in the case
* where the two segments are almost parallel
* (which is hard to compute a robust intersection for).
*/
if (this.offset0.p1.distance(this.offset1.p0) < this.distance * OFFSET_SEGMENT_SEPARATION_FACTOR) {
this.segList.addPt(this.offset0.p1);
return;
}
if (this.bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) {
this.addMitreJoin(this.s1, this.offset0, this.offset1, this.distance);
} else if (this.bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL) {
this.addBevelJoin(this.offset0, this.offset1);
} else {
// add a circular fillet connecting the endpoints of the offset segments
if (addStartPoint) {
this.segList.addPt(this.offset0.p1);
}
// TESTING - comment out to produce beveled joins
this.addFillet(this.s1, this.offset0.p1, this.offset1.p0, orientation, this.distance);
this.segList.addPt(this.offset1.p0);
}
}
/**
* Adds the offset points for an inside (concave) turn.
*
* @param orientation
* @param addStartPoint
*/
private void addInsideTurn(int orientation, boolean addStartPoint) {
/**
* add intersection point of offset segments (if any)
*/
this.li.computeIntersection(this.offset0.p0, this.offset0.p1, this.offset1.p0, this.offset1.p1);
if (this.li.hasIntersection()) {
this.segList.addPt(this.li.getIntersection(0));
} else {
/**
* If no intersection is detected,
* it means the angle is so small and/or the offset so
* large that the offsets segments don't intersect.
* In this case we must
* add a "closing segment" to make sure the buffer curve is continuous,
* fairly smooth (e.g. no sharp reversals in direction)
* and tracks the buffer correctly around the corner. The curve connects
* the endpoints of the segment offsets to points
* which lie toward the centre point of the corner.
* The joining curve will not appear in the final buffer outline, since it
* is completely internal to the buffer polygon.
*
* In complex buffer cases the closing segment may cut across many other
* segments in the generated offset curve. In order to improve the
* performance of the noding, the closing segment should be kept as short as possible.
* (But not too short, since that would defeat its purpose).
* This is the purpose of the closingSegFactor heuristic value.
*/
/**
* The intersection test above is vulnerable to robustness errors; i.e. it
* may be that the offsets should intersect very close to their endpoints,
* but aren't reported as such due to rounding. To handle this situation
* appropriately, we use the following test: If the offset points are very
* close, don't add closing segments but simply use one of the offset
* points
*/
this.hasNarrowConcaveAngle = true;
//System.out.println("NARROW ANGLE - distance = " + distance);
if (this.offset0.p1.distance(this.offset1.p0) < this.distance
* INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) {
this.segList.addPt(this.offset0.p1);
} else {
// add endpoint of this segment offset
this.segList.addPt(this.offset0.p1);
/**
* Add "closing segment" of required length.
*/
if (this.closingSegLengthFactor > 0) {
Coordinate mid0 = new Coordinate((this.closingSegLengthFactor * this.offset0.p1.x + this.s1.x) / (this.closingSegLengthFactor + 1),
(this.closingSegLengthFactor * this.offset0.p1.y + this.s1.y) / (this.closingSegLengthFactor + 1));
this.segList.addPt(mid0);
Coordinate mid1 = new Coordinate((this.closingSegLengthFactor * this.offset1.p0.x + this.s1.x) / (this.closingSegLengthFactor + 1),
(this.closingSegLengthFactor * this.offset1.p0.y + this.s1.y) / (this.closingSegLengthFactor + 1));
this.segList.addPt(mid1);
} else {
/**
* This branch is not expected to be used except for testing purposes.
* It is equivalent to the JTS 1.9 logic for closing segments
* (which results in very poor performance for large buffer distances)
*/
this.segList.addPt(this.s1);
}
//*/
// add start point of next segment offset
this.segList.addPt(this.offset1.p0);
}
}
}
/**
* Compute an offset segment for an input segment on a given side and at a given distance.
* The offset points are computed in full double precision, for accuracy.
*
* @param seg the segment to offset
* @param side the side of the segment ({@link Position}) the offset lies on
* @param distance the offset distance
* @param offset the points computed for the offset segment
*/
private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) {
int sideSign = side == Position.LEFT ? 1 : -1;
double dx = seg.p1.x - seg.p0.x;
double dy = seg.p1.y - seg.p0.y;
double len = Math.sqrt(dx * dx + dy * dy);
// u is the vector that is the length of the offset, in the direction of the segment
double ux = sideSign * distance * dx / len;
double uy = sideSign * distance * dy / len;
offset.p0.x = seg.p0.x - uy;
offset.p0.y = seg.p0.y + ux;
offset.p1.x = seg.p1.x - uy;
offset.p1.y = seg.p1.y + ux;
}
/**
* Add an end cap around point p1, terminating a line segment coming from p0
*/
public void addLineEndCap(Coordinate p0, Coordinate p1) {
LineSegment seg = new LineSegment(p0, p1);
LineSegment offsetL = new LineSegment();
this.computeOffsetSegment(seg, Position.LEFT, this.distance, offsetL);
LineSegment offsetR = new LineSegment();
this.computeOffsetSegment(seg, Position.RIGHT, this.distance, offsetR);
double dx = p1.x - p0.x;
double dy = p1.y - p0.y;
double angle = Math.atan2(dy, dx);
switch (this.bufParams.getEndCapStyle()) {
case BufferParameters.CAP_ROUND:
// add offset seg points with a fillet between them
this.segList.addPt(offsetL.p1);
this.addFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, CGAlgorithms.CLOCKWISE, this.distance);
this.segList.addPt(offsetR.p1);
break;
case BufferParameters.CAP_FLAT:
// only offset segment points are added
this.segList.addPt(offsetL.p1);
this.segList.addPt(offsetR.p1);
break;
case BufferParameters.CAP_SQUARE:
// add a square defined by extensions of the offset segment endpoints
Coordinate squareCapSideOffset = new Coordinate();
squareCapSideOffset.x = Math.abs(this.distance) * Math.cos(angle);
squareCapSideOffset.y = Math.abs(this.distance) * Math.sin(angle);
Coordinate squareCapLOffset = new Coordinate(
offsetL.p1.x + squareCapSideOffset.x,
offsetL.p1.y + squareCapSideOffset.y);
Coordinate squareCapROffset = new Coordinate(
offsetR.p1.x + squareCapSideOffset.x,
offsetR.p1.y + squareCapSideOffset.y);
this.segList.addPt(squareCapLOffset);
this.segList.addPt(squareCapROffset);
break;
}
}
/**
* Adds a mitre join connecting the two reflex offset segments.
* The mitre will be beveled if it exceeds the mitre ratio limit.
*
* @param offset0 the first offset segment
* @param offset1 the second offset segment
* @param distance the offset distance
*/
private void addMitreJoin(Coordinate p,
LineSegment offset0,
LineSegment offset1,
double distance) {
boolean isMitreWithinLimit = true;
Coordinate intPt = null;
/**
* This computation is unstable if the offset segments are nearly collinear.
* Howver, this situation should have been eliminated earlier by the check for
* whether the offset segment endpoints are almost coincident
*/
try {
intPt = HCoordinate.intersection(offset0.p0,
offset0.p1, offset1.p0, offset1.p1);
double mitreRatio = distance <= 0.0 ? 1.0
: intPt.distance(p) / Math.abs(distance);
if (mitreRatio > this.bufParams.getMitreLimit()) {
isMitreWithinLimit = false;
}
} catch (NotRepresentableException ex) {
intPt = new Coordinate(0, 0);
isMitreWithinLimit = false;
}
if (isMitreWithinLimit) {
this.segList.addPt(intPt);
} else {
this.addLimitedMitreJoin(offset0, offset1, distance, this.bufParams.getMitreLimit());
// addBevelJoin(offset0, offset1);
}
}
/**
* Adds a limited mitre join connecting the two reflex offset segments.
* A limited mitre is a mitre which is beveled at the distance
* determined by the mitre ratio limit.
*
* @param offset0 the first offset segment
* @param offset1 the second offset segment
* @param distance the offset distance
* @param mitreLimit the mitre limit ratio
*/
private void addLimitedMitreJoin(
LineSegment offset0,
LineSegment offset1,
double distance,
double mitreLimit) {
Coordinate basePt = this.seg0.p1;
double ang0 = Angle.angle(basePt, this.seg0.p0);
double ang1 = Angle.angle(basePt, this.seg1.p1);
// oriented angle between segments
double angDiff = Angle.angleBetweenOriented(this.seg0.p0, basePt, this.seg1.p1);
// half of the interior angle
double angDiffHalf = angDiff / 2;
// angle for bisector of the interior angle between the segments
double midAng = Angle.normalize(ang0 + angDiffHalf);
// rotating this by PI gives the bisector of the reflex angle
double mitreMidAng = Angle.normalize(midAng + Math.PI);
// the miterLimit determines the distance to the mitre bevel
double mitreDist = mitreLimit * distance;
// the bevel delta is the difference between the buffer distance
// and half of the length of the bevel segment
double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf));
double bevelHalfLen = distance - bevelDelta;
// compute the midpoint of the bevel segment
double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng);
double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng);
Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY);
// compute the mitre midline segment from the corner point to the bevel segment midpoint
LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt);
// finally the bevel segment endpoints are computed as offsets from
// the mitre midline
Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen);
Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen);
if (this.side == Position.LEFT) {
this.segList.addPt(bevelEndLeft);
this.segList.addPt(bevelEndRight);
} else {
this.segList.addPt(bevelEndRight);
this.segList.addPt(bevelEndLeft);
}
}
/**
* Adds a bevel join connecting the two offset segments
* around a reflex corner.
*
* @param offset0 the first offset segment
* @param offset1 the second offset segment
*/
private void addBevelJoin(
LineSegment offset0,
LineSegment offset1) {
this.segList.addPt(offset0.p1);
this.segList.addPt(offset1.p0);
}
/**
* Add points for a circular fillet around a reflex corner.
* Adds the start and end points
*
* @param p base point of curve
* @param p0 start point of fillet curve
* @param p1 endpoint of fillet curve
* @param direction the orientation of the fillet
* @param radius the radius of the fillet
*/
private void addFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) {
double dx0 = p0.x - p.x;
double dy0 = p0.y - p.y;
double startAngle = Math.atan2(dy0, dx0);
double dx1 = p1.x - p.x;
double dy1 = p1.y - p.y;
double endAngle = Math.atan2(dy1, dx1);
if (direction == CGAlgorithms.CLOCKWISE) {
if (startAngle <= endAngle) {
startAngle += 2.0 * Math.PI;
}
} else { // direction == COUNTERCLOCKWISE
if (startAngle >= endAngle) {
startAngle -= 2.0 * Math.PI;
}
}
this.segList.addPt(p0);
this.addFillet(p, startAngle, endAngle, direction, radius);
this.segList.addPt(p1);
}
/**
* Adds points for a circular fillet arc
* between two specified angles.
* The start and end point for the fillet are not added -
* the caller must add them if required.
*
* @param direction is -1 for a CW angle, 1 for a CCW angle
* @param radius the radius of the fillet
*/
private void addFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) {
int directionFactor = direction == CGAlgorithms.CLOCKWISE ? -1 : 1;
double totalAngle = Math.abs(startAngle - endAngle);
int nSegs = (int) (totalAngle / this.filletAngleQuantum + 0.5);
if (nSegs < 1) {
return; // no segments because angle is less than increment - nothing to do!
}
double initAngle, currAngleInc;
// choose angle increment so that each segment has equal length
initAngle = 0.0;
currAngleInc = totalAngle / nSegs;
double currAngle = initAngle;
Coordinate pt = new Coordinate();
while (currAngle < totalAngle) {
double angle = startAngle + directionFactor * currAngle;
pt.x = p.x + radius * Math.cos(angle);
pt.y = p.y + radius * Math.sin(angle);
this.segList.addPt(pt);
currAngle += currAngleInc;
}
}
/**
* Creates a CW circle around a point
*/
public void createCircle(Coordinate p) {
// add start point
Coordinate pt = new Coordinate(p.x + this.distance, p.y);
this.segList.addPt(pt);
this.addFillet(p, 0.0, 2.0 * Math.PI, -1, this.distance);
this.segList.closeRing();
}
/**
* Creates a CW square around a point
*/
public void createSquare(Coordinate p) {
this.segList.addPt(new Coordinate(p.x + this.distance, p.y + this.distance));
this.segList.addPt(new Coordinate(p.x + this.distance, p.y - this.distance));
this.segList.addPt(new Coordinate(p.x - this.distance, p.y - this.distance));
this.segList.addPt(new Coordinate(p.x - this.distance, p.y + this.distance));
this.segList.closeRing();
}
}
| Gegy/Earth | src/main/java/com/vividsolutions/jts/operation/buffer/OffsetSegmentGenerator.java | 7,681 | // oriented angle between segments | line_comment | nl | /*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jts.operation.buffer;
import com.vividsolutions.jts.algorithm.Angle;
import com.vividsolutions.jts.algorithm.CGAlgorithms;
import com.vividsolutions.jts.algorithm.HCoordinate;
import com.vividsolutions.jts.algorithm.LineIntersector;
import com.vividsolutions.jts.algorithm.NotRepresentableException;
import com.vividsolutions.jts.algorithm.RobustLineIntersector;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LineSegment;
import com.vividsolutions.jts.geom.PrecisionModel;
import com.vividsolutions.jts.geomgraph.Position;
/**
* Generates segments which form an offset curve.
* Supports all end cap and join options
* provided for buffering.
* This algorithm implements various heuristics to
* produce smoother, simpler curves which are
* still within a reasonable tolerance of the
* true curve.
*
* @author Martin Davis
*/
class OffsetSegmentGenerator {
/**
* Factor which controls how close offset segments can be to
* skip adding a filler or mitre.
*/
private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3;
/**
* Factor which controls how close curve vertices on inside turns can be to be snapped
*/
private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3;
/**
* Factor which controls how close curve vertices can be to be snapped
*/
private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6;
/**
* Factor which determines how short closing segs can be for round buffers
*/
private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80;
/**
* the max error of approximation (distance) between a quad segment and the true fillet curve
*/
private double maxCurveSegmentError = 0.0;
/**
* The angle quantum with which to approximate a fillet curve
* (based on the input # of quadrant segments)
*/
private double filletAngleQuantum;
/**
* The Closing Segment Length Factor controls how long
* "closing segments" are. Closing segments are added
* at the middle of inside corners to ensure a smoother
* boundary for the buffer offset curve.
* In some cases (particularly for round joins with default-or-better
* quantization) the closing segments can be made quite short.
* This substantially improves performance (due to fewer intersections being created).
* <p>
* A closingSegFactor of 0 results in lines to the corner vertex
* A closingSegFactor of 1 results in lines halfway to the corner vertex
* A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex
* (this option is reasonable for the very common default situation of round joins
* and quadrantSegs >= 8)
*/
private int closingSegLengthFactor = 1;
private OffsetSegmentString segList;
private double distance = 0.0;
private PrecisionModel precisionModel;
private BufferParameters bufParams;
private LineIntersector li;
private Coordinate s0, s1, s2;
private LineSegment seg0 = new LineSegment();
private LineSegment seg1 = new LineSegment();
private LineSegment offset0 = new LineSegment();
private LineSegment offset1 = new LineSegment();
private int side = 0;
private boolean hasNarrowConcaveAngle = false;
public OffsetSegmentGenerator(PrecisionModel precisionModel,
BufferParameters bufParams, double distance) {
this.precisionModel = precisionModel;
this.bufParams = bufParams;
// compute intersections in full precision, to provide accuracy
// the points are rounded as they are inserted into the curve line
this.li = new RobustLineIntersector();
this.filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments();
/**
* Non-round joins cause issues with short closing segments, so don't use
* them. In any case, non-round joins only really make sense for relatively
* small buffer distances.
*/
if (bufParams.getQuadrantSegments() >= 8
&& bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) {
this.closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR;
}
this.init(distance);
}
/**
* Tests whether the input has a narrow concave angle
* (relative to the offset distance).
* In this case the generated offset curve will contain self-intersections
* and heuristic closing segments.
* This is expected behaviour in the case of Buffer curves.
* For pure Offset Curves,
* the output needs to be further treated
* before it can be used.
*
* @return true if the input has a narrow concave angle
*/
public boolean hasNarrowConcaveAngle() {
return this.hasNarrowConcaveAngle;
}
private void init(double distance) {
this.distance = distance;
this.maxCurveSegmentError = distance * (1 - Math.cos(this.filletAngleQuantum / 2.0));
this.segList = new OffsetSegmentString();
this.segList.setPrecisionModel(this.precisionModel);
/**
* Choose the min vertex separation as a small fraction of the offset distance.
*/
this.segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR);
}
public void initSideSegments(Coordinate s1, Coordinate s2, int side) {
this.s1 = s1;
this.s2 = s2;
this.side = side;
this.seg1.setCoordinates(s1, s2);
this.computeOffsetSegment(this.seg1, side, this.distance, this.offset1);
}
public Coordinate[] getCoordinates() {
Coordinate[] pts = this.segList.getCoordinates();
return pts;
}
public void closeRing() {
this.segList.closeRing();
}
public void addSegments(Coordinate[] pt, boolean isForward) {
this.segList.addPts(pt, isForward);
}
public void addFirstSegment() {
this.segList.addPt(this.offset1.p0);
}
/**
* Add last offset point
*/
public void addLastSegment() {
this.segList.addPt(this.offset1.p1);
}
//private static double MAX_CLOSING_SEG_LEN = 3.0;
public void addNextSegment(Coordinate p, boolean addStartPoint) {
// s0-s1-s2 are the coordinates of the previous segment and the current one
this.s0 = this.s1;
this.s1 = this.s2;
this.s2 = p;
this.seg0.setCoordinates(this.s0, this.s1);
this.computeOffsetSegment(this.seg0, this.side, this.distance, this.offset0);
this.seg1.setCoordinates(this.s1, this.s2);
this.computeOffsetSegment(this.seg1, this.side, this.distance, this.offset1);
// do nothing if points are equal
if (this.s1.equals(this.s2)) {
return;
}
int orientation = CGAlgorithms.computeOrientation(this.s0, this.s1, this.s2);
boolean outsideTurn =
(orientation == CGAlgorithms.CLOCKWISE && this.side == Position.LEFT)
|| (orientation == CGAlgorithms.COUNTERCLOCKWISE && this.side == Position.RIGHT);
if (orientation == 0) { // lines are collinear
this.addCollinear(addStartPoint);
} else if (outsideTurn) {
this.addOutsideTurn(orientation, addStartPoint);
} else { // inside turn
this.addInsideTurn(orientation, addStartPoint);
}
}
private void addCollinear(boolean addStartPoint) {
/**
* This test could probably be done more efficiently,
* but the situation of exact collinearity should be fairly rare.
*/
this.li.computeIntersection(this.s0, this.s1, this.s1, this.s2);
int numInt = this.li.getIntersectionNum();
/**
* if numInt is < 2, the lines are parallel and in the same direction. In
* this case the point can be ignored, since the offset lines will also be
* parallel.
*/
if (numInt >= 2) {
/**
* segments are collinear but reversing.
* Add an "end-cap" fillet
* all the way around to other direction This case should ONLY happen
* for LineStrings, so the orientation is always CW. (Polygons can never
* have two consecutive segments which are parallel but reversed,
* because that would be a self intersection.
*
*/
if (this.bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL
|| this.bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) {
if (addStartPoint) {
this.segList.addPt(this.offset0.p1);
}
this.segList.addPt(this.offset1.p0);
} else {
this.addFillet(this.s1, this.offset0.p1, this.offset1.p0, CGAlgorithms.CLOCKWISE, this.distance);
}
}
}
/**
* Adds the offset points for an outside (convex) turn
*
* @param orientation
* @param addStartPoint
*/
private void addOutsideTurn(int orientation, boolean addStartPoint) {
/**
* Heuristic: If offset endpoints are very close together,
* just use one of them as the corner vertex.
* This avoids problems with computing mitre corners in the case
* where the two segments are almost parallel
* (which is hard to compute a robust intersection for).
*/
if (this.offset0.p1.distance(this.offset1.p0) < this.distance * OFFSET_SEGMENT_SEPARATION_FACTOR) {
this.segList.addPt(this.offset0.p1);
return;
}
if (this.bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) {
this.addMitreJoin(this.s1, this.offset0, this.offset1, this.distance);
} else if (this.bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL) {
this.addBevelJoin(this.offset0, this.offset1);
} else {
// add a circular fillet connecting the endpoints of the offset segments
if (addStartPoint) {
this.segList.addPt(this.offset0.p1);
}
// TESTING - comment out to produce beveled joins
this.addFillet(this.s1, this.offset0.p1, this.offset1.p0, orientation, this.distance);
this.segList.addPt(this.offset1.p0);
}
}
/**
* Adds the offset points for an inside (concave) turn.
*
* @param orientation
* @param addStartPoint
*/
private void addInsideTurn(int orientation, boolean addStartPoint) {
/**
* add intersection point of offset segments (if any)
*/
this.li.computeIntersection(this.offset0.p0, this.offset0.p1, this.offset1.p0, this.offset1.p1);
if (this.li.hasIntersection()) {
this.segList.addPt(this.li.getIntersection(0));
} else {
/**
* If no intersection is detected,
* it means the angle is so small and/or the offset so
* large that the offsets segments don't intersect.
* In this case we must
* add a "closing segment" to make sure the buffer curve is continuous,
* fairly smooth (e.g. no sharp reversals in direction)
* and tracks the buffer correctly around the corner. The curve connects
* the endpoints of the segment offsets to points
* which lie toward the centre point of the corner.
* The joining curve will not appear in the final buffer outline, since it
* is completely internal to the buffer polygon.
*
* In complex buffer cases the closing segment may cut across many other
* segments in the generated offset curve. In order to improve the
* performance of the noding, the closing segment should be kept as short as possible.
* (But not too short, since that would defeat its purpose).
* This is the purpose of the closingSegFactor heuristic value.
*/
/**
* The intersection test above is vulnerable to robustness errors; i.e. it
* may be that the offsets should intersect very close to their endpoints,
* but aren't reported as such due to rounding. To handle this situation
* appropriately, we use the following test: If the offset points are very
* close, don't add closing segments but simply use one of the offset
* points
*/
this.hasNarrowConcaveAngle = true;
//System.out.println("NARROW ANGLE - distance = " + distance);
if (this.offset0.p1.distance(this.offset1.p0) < this.distance
* INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) {
this.segList.addPt(this.offset0.p1);
} else {
// add endpoint of this segment offset
this.segList.addPt(this.offset0.p1);
/**
* Add "closing segment" of required length.
*/
if (this.closingSegLengthFactor > 0) {
Coordinate mid0 = new Coordinate((this.closingSegLengthFactor * this.offset0.p1.x + this.s1.x) / (this.closingSegLengthFactor + 1),
(this.closingSegLengthFactor * this.offset0.p1.y + this.s1.y) / (this.closingSegLengthFactor + 1));
this.segList.addPt(mid0);
Coordinate mid1 = new Coordinate((this.closingSegLengthFactor * this.offset1.p0.x + this.s1.x) / (this.closingSegLengthFactor + 1),
(this.closingSegLengthFactor * this.offset1.p0.y + this.s1.y) / (this.closingSegLengthFactor + 1));
this.segList.addPt(mid1);
} else {
/**
* This branch is not expected to be used except for testing purposes.
* It is equivalent to the JTS 1.9 logic for closing segments
* (which results in very poor performance for large buffer distances)
*/
this.segList.addPt(this.s1);
}
//*/
// add start point of next segment offset
this.segList.addPt(this.offset1.p0);
}
}
}
/**
* Compute an offset segment for an input segment on a given side and at a given distance.
* The offset points are computed in full double precision, for accuracy.
*
* @param seg the segment to offset
* @param side the side of the segment ({@link Position}) the offset lies on
* @param distance the offset distance
* @param offset the points computed for the offset segment
*/
private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) {
int sideSign = side == Position.LEFT ? 1 : -1;
double dx = seg.p1.x - seg.p0.x;
double dy = seg.p1.y - seg.p0.y;
double len = Math.sqrt(dx * dx + dy * dy);
// u is the vector that is the length of the offset, in the direction of the segment
double ux = sideSign * distance * dx / len;
double uy = sideSign * distance * dy / len;
offset.p0.x = seg.p0.x - uy;
offset.p0.y = seg.p0.y + ux;
offset.p1.x = seg.p1.x - uy;
offset.p1.y = seg.p1.y + ux;
}
/**
* Add an end cap around point p1, terminating a line segment coming from p0
*/
public void addLineEndCap(Coordinate p0, Coordinate p1) {
LineSegment seg = new LineSegment(p0, p1);
LineSegment offsetL = new LineSegment();
this.computeOffsetSegment(seg, Position.LEFT, this.distance, offsetL);
LineSegment offsetR = new LineSegment();
this.computeOffsetSegment(seg, Position.RIGHT, this.distance, offsetR);
double dx = p1.x - p0.x;
double dy = p1.y - p0.y;
double angle = Math.atan2(dy, dx);
switch (this.bufParams.getEndCapStyle()) {
case BufferParameters.CAP_ROUND:
// add offset seg points with a fillet between them
this.segList.addPt(offsetL.p1);
this.addFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, CGAlgorithms.CLOCKWISE, this.distance);
this.segList.addPt(offsetR.p1);
break;
case BufferParameters.CAP_FLAT:
// only offset segment points are added
this.segList.addPt(offsetL.p1);
this.segList.addPt(offsetR.p1);
break;
case BufferParameters.CAP_SQUARE:
// add a square defined by extensions of the offset segment endpoints
Coordinate squareCapSideOffset = new Coordinate();
squareCapSideOffset.x = Math.abs(this.distance) * Math.cos(angle);
squareCapSideOffset.y = Math.abs(this.distance) * Math.sin(angle);
Coordinate squareCapLOffset = new Coordinate(
offsetL.p1.x + squareCapSideOffset.x,
offsetL.p1.y + squareCapSideOffset.y);
Coordinate squareCapROffset = new Coordinate(
offsetR.p1.x + squareCapSideOffset.x,
offsetR.p1.y + squareCapSideOffset.y);
this.segList.addPt(squareCapLOffset);
this.segList.addPt(squareCapROffset);
break;
}
}
/**
* Adds a mitre join connecting the two reflex offset segments.
* The mitre will be beveled if it exceeds the mitre ratio limit.
*
* @param offset0 the first offset segment
* @param offset1 the second offset segment
* @param distance the offset distance
*/
private void addMitreJoin(Coordinate p,
LineSegment offset0,
LineSegment offset1,
double distance) {
boolean isMitreWithinLimit = true;
Coordinate intPt = null;
/**
* This computation is unstable if the offset segments are nearly collinear.
* Howver, this situation should have been eliminated earlier by the check for
* whether the offset segment endpoints are almost coincident
*/
try {
intPt = HCoordinate.intersection(offset0.p0,
offset0.p1, offset1.p0, offset1.p1);
double mitreRatio = distance <= 0.0 ? 1.0
: intPt.distance(p) / Math.abs(distance);
if (mitreRatio > this.bufParams.getMitreLimit()) {
isMitreWithinLimit = false;
}
} catch (NotRepresentableException ex) {
intPt = new Coordinate(0, 0);
isMitreWithinLimit = false;
}
if (isMitreWithinLimit) {
this.segList.addPt(intPt);
} else {
this.addLimitedMitreJoin(offset0, offset1, distance, this.bufParams.getMitreLimit());
// addBevelJoin(offset0, offset1);
}
}
/**
* Adds a limited mitre join connecting the two reflex offset segments.
* A limited mitre is a mitre which is beveled at the distance
* determined by the mitre ratio limit.
*
* @param offset0 the first offset segment
* @param offset1 the second offset segment
* @param distance the offset distance
* @param mitreLimit the mitre limit ratio
*/
private void addLimitedMitreJoin(
LineSegment offset0,
LineSegment offset1,
double distance,
double mitreLimit) {
Coordinate basePt = this.seg0.p1;
double ang0 = Angle.angle(basePt, this.seg0.p0);
double ang1 = Angle.angle(basePt, this.seg1.p1);
// oriented angle<SUF>
double angDiff = Angle.angleBetweenOriented(this.seg0.p0, basePt, this.seg1.p1);
// half of the interior angle
double angDiffHalf = angDiff / 2;
// angle for bisector of the interior angle between the segments
double midAng = Angle.normalize(ang0 + angDiffHalf);
// rotating this by PI gives the bisector of the reflex angle
double mitreMidAng = Angle.normalize(midAng + Math.PI);
// the miterLimit determines the distance to the mitre bevel
double mitreDist = mitreLimit * distance;
// the bevel delta is the difference between the buffer distance
// and half of the length of the bevel segment
double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf));
double bevelHalfLen = distance - bevelDelta;
// compute the midpoint of the bevel segment
double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng);
double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng);
Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY);
// compute the mitre midline segment from the corner point to the bevel segment midpoint
LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt);
// finally the bevel segment endpoints are computed as offsets from
// the mitre midline
Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen);
Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen);
if (this.side == Position.LEFT) {
this.segList.addPt(bevelEndLeft);
this.segList.addPt(bevelEndRight);
} else {
this.segList.addPt(bevelEndRight);
this.segList.addPt(bevelEndLeft);
}
}
/**
* Adds a bevel join connecting the two offset segments
* around a reflex corner.
*
* @param offset0 the first offset segment
* @param offset1 the second offset segment
*/
private void addBevelJoin(
LineSegment offset0,
LineSegment offset1) {
this.segList.addPt(offset0.p1);
this.segList.addPt(offset1.p0);
}
/**
* Add points for a circular fillet around a reflex corner.
* Adds the start and end points
*
* @param p base point of curve
* @param p0 start point of fillet curve
* @param p1 endpoint of fillet curve
* @param direction the orientation of the fillet
* @param radius the radius of the fillet
*/
private void addFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) {
double dx0 = p0.x - p.x;
double dy0 = p0.y - p.y;
double startAngle = Math.atan2(dy0, dx0);
double dx1 = p1.x - p.x;
double dy1 = p1.y - p.y;
double endAngle = Math.atan2(dy1, dx1);
if (direction == CGAlgorithms.CLOCKWISE) {
if (startAngle <= endAngle) {
startAngle += 2.0 * Math.PI;
}
} else { // direction == COUNTERCLOCKWISE
if (startAngle >= endAngle) {
startAngle -= 2.0 * Math.PI;
}
}
this.segList.addPt(p0);
this.addFillet(p, startAngle, endAngle, direction, radius);
this.segList.addPt(p1);
}
/**
* Adds points for a circular fillet arc
* between two specified angles.
* The start and end point for the fillet are not added -
* the caller must add them if required.
*
* @param direction is -1 for a CW angle, 1 for a CCW angle
* @param radius the radius of the fillet
*/
private void addFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) {
int directionFactor = direction == CGAlgorithms.CLOCKWISE ? -1 : 1;
double totalAngle = Math.abs(startAngle - endAngle);
int nSegs = (int) (totalAngle / this.filletAngleQuantum + 0.5);
if (nSegs < 1) {
return; // no segments because angle is less than increment - nothing to do!
}
double initAngle, currAngleInc;
// choose angle increment so that each segment has equal length
initAngle = 0.0;
currAngleInc = totalAngle / nSegs;
double currAngle = initAngle;
Coordinate pt = new Coordinate();
while (currAngle < totalAngle) {
double angle = startAngle + directionFactor * currAngle;
pt.x = p.x + radius * Math.cos(angle);
pt.y = p.y + radius * Math.sin(angle);
this.segList.addPt(pt);
currAngle += currAngleInc;
}
}
/**
* Creates a CW circle around a point
*/
public void createCircle(Coordinate p) {
// add start point
Coordinate pt = new Coordinate(p.x + this.distance, p.y);
this.segList.addPt(pt);
this.addFillet(p, 0.0, 2.0 * Math.PI, -1, this.distance);
this.segList.closeRing();
}
/**
* Creates a CW square around a point
*/
public void createSquare(Coordinate p) {
this.segList.addPt(new Coordinate(p.x + this.distance, p.y + this.distance));
this.segList.addPt(new Coordinate(p.x + this.distance, p.y - this.distance));
this.segList.addPt(new Coordinate(p.x - this.distance, p.y - this.distance));
this.segList.addPt(new Coordinate(p.x - this.distance, p.y + this.distance));
this.segList.closeRing();
}
}
|
38470_4 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Eusebius
*/
@WebServlet(name = "servletLogin", urlPatterns = {"/servletLogin"})
public class servletLogin extends HttpServlet {
// database link, gebruikersnaam en wachtwoord
static final String DATABASE_URL = "jdbc:mysql://localhost/groep16_festivals";
static final String USERNAME = "root";
static final String PASSWORD = "";
String uName;
String uPass;
String sql;
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
try{
// checken of de opgegeven parameters juist zijn
uName = request.getParameter("uName");
uPass = request.getParameter("Password");
sql = "SELECT count(*) FROM geregistreerdegebruikers WHERE gebr_naam LIKE '" + uName + "' AND gebr_pass LIKE '"+ uPass + "'";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
rs.next();
if (rs.getInt(1) != 0){
out.println("<html>");
out.println("<head>");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/css3.css\" media=\"screen\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/forms.css\" media=\"screen\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/general.css\" media=\"screen\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/grid.css\" media=\"screen\">");
out.println("<title>Bewerk gegevens</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Bewerk gegevens</h1>");
out.println("<form action=\"servletEdit\">");
out.println("<label>Geef de naam in van de tabel die je wil bewerken<label></br>");
out.println("<input type=\"text\" name=\"table\"></br>");
out.println("<input type=\"submit\" value=\"Bewerk gegevens\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
else{
// foutmelding
out.println("<html>");
out.println("<head>");
out.println("<title>Foute login</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>De opgegeven gebruiker bestaat niet of de ingevoerde gegevens zijn fout</h1>");
out.println("</body>");
out.println("</html>");
}
conn.close();
}
catch (Exception ex){
out.println("De volgende fout is opgetreden: " + ex.getMessage());
ex.printStackTrace();
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| GeintegreerdProjectGroep16/Project | src/java/Servlets/servletLogin.java | 1,604 | // checken of de opgegeven parameters juist zijn
| line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Eusebius
*/
@WebServlet(name = "servletLogin", urlPatterns = {"/servletLogin"})
public class servletLogin extends HttpServlet {
// database link, gebruikersnaam en wachtwoord
static final String DATABASE_URL = "jdbc:mysql://localhost/groep16_festivals";
static final String USERNAME = "root";
static final String PASSWORD = "";
String uName;
String uPass;
String sql;
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
try{
// checken of<SUF>
uName = request.getParameter("uName");
uPass = request.getParameter("Password");
sql = "SELECT count(*) FROM geregistreerdegebruikers WHERE gebr_naam LIKE '" + uName + "' AND gebr_pass LIKE '"+ uPass + "'";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
rs.next();
if (rs.getInt(1) != 0){
out.println("<html>");
out.println("<head>");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/css3.css\" media=\"screen\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/forms.css\" media=\"screen\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/general.css\" media=\"screen\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/grid.css\" media=\"screen\">");
out.println("<title>Bewerk gegevens</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Bewerk gegevens</h1>");
out.println("<form action=\"servletEdit\">");
out.println("<label>Geef de naam in van de tabel die je wil bewerken<label></br>");
out.println("<input type=\"text\" name=\"table\"></br>");
out.println("<input type=\"submit\" value=\"Bewerk gegevens\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
else{
// foutmelding
out.println("<html>");
out.println("<head>");
out.println("<title>Foute login</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>De opgegeven gebruiker bestaat niet of de ingevoerde gegevens zijn fout</h1>");
out.println("</body>");
out.println("</html>");
}
conn.close();
}
catch (Exception ex){
out.println("De volgende fout is opgetreden: " + ex.getMessage());
ex.printStackTrace();
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
19753_4 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
// https://netbeans.org/kb/docs/web/hibernate-webapp.html
package Hibernate;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
/**
*
* @author Eusebius
*/
@ManagedBean
@SessionScoped
public class festivalManagedBean {
/**
* Creates a new instance of festivalManagedBean
*/
int startId;
int endId;
DataModel festivalNames;
festivalHelper helper;
private int recordCount = 2;
private int pageSize = 10;
private Festivals current;
private int selectedItemIndex;
public festivalManagedBean() {
helper = new festivalHelper();
startId = 1;
endId = 10;
}
public festivalManagedBean(int startId, int endId) {
helper = new festivalHelper();
this.startId = startId;
this.endId = endId;
}
public Festivals getSelected() {
if (current == null) {
current = new Festivals();
selectedItemIndex = -1;
}
return current;
}
public DataModel getFestivalNames() {
if (festivalNames == null) {
festivalNames = new ListDataModel(helper.getFestivalNames(startId, endId));
}
return festivalNames;
}
void recreateModel() {
festivalNames = null;
}
public boolean isHasNextPage() {
if (endId + pageSize <= recordCount) {
return true;
}
return false;
}
public boolean isHasPreviousPage() {
if (startId-pageSize > 0) {
return true;
}
return false;
}
public String next() {
startId = endId+1;
endId = endId + pageSize;
recreateModel();
return "index";
}
public String previous() {
startId = startId - pageSize;
endId = endId - pageSize;
recreateModel();
return "index";
}
public int getPageSize() {
return pageSize;
}
public String prepareView(){
current = (Festivals) getFestivalNames().getRowData();
return "browse";
}
public String prepareList(){
recreateModel();
return "index";
}
// alle bands van een bepaald festival ophalen en achter elkaar zetten
public String getBands() {
List bands = helper.getBandsByID(current.getFestId());
StringBuilder totalLineUp = new StringBuilder();
for (int i = 0; i < bands.size(); i++) {
Bands band = (Bands) bands.get(i);
totalLineUp.append(band.getBandNaam());
totalLineUp.append(" : ");
totalLineUp.append(band.getBandSoortMuziek());
totalLineUp.append("; ");
}
return totalLineUp.toString();
}
// alle tickets en hun prijs van een bepaald festival ophalen en achter elkaar zetten
public String getTicketypes() {
List tickets = helper.getTicketsByID(current.getFestId());
StringBuilder totalTickets = new StringBuilder();
for (int i = 0; i < tickets.size(); i++) {
Tickettypes ticket = (Tickettypes) tickets.get(i);
totalTickets.append(ticket.getTypOmschr());
totalTickets.append(" : €");
totalTickets.append(ticket.getTypPrijs().toString());
totalTickets.append("; ");
}
return totalTickets.toString();
}
}
| GeintegreerdProjectGroep16/ProjectDeel2 | src/java/Hibernate/festivalManagedBean.java | 1,089 | // alle tickets en hun prijs van een bepaald festival ophalen en achter elkaar zetten
| line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
// https://netbeans.org/kb/docs/web/hibernate-webapp.html
package Hibernate;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
/**
*
* @author Eusebius
*/
@ManagedBean
@SessionScoped
public class festivalManagedBean {
/**
* Creates a new instance of festivalManagedBean
*/
int startId;
int endId;
DataModel festivalNames;
festivalHelper helper;
private int recordCount = 2;
private int pageSize = 10;
private Festivals current;
private int selectedItemIndex;
public festivalManagedBean() {
helper = new festivalHelper();
startId = 1;
endId = 10;
}
public festivalManagedBean(int startId, int endId) {
helper = new festivalHelper();
this.startId = startId;
this.endId = endId;
}
public Festivals getSelected() {
if (current == null) {
current = new Festivals();
selectedItemIndex = -1;
}
return current;
}
public DataModel getFestivalNames() {
if (festivalNames == null) {
festivalNames = new ListDataModel(helper.getFestivalNames(startId, endId));
}
return festivalNames;
}
void recreateModel() {
festivalNames = null;
}
public boolean isHasNextPage() {
if (endId + pageSize <= recordCount) {
return true;
}
return false;
}
public boolean isHasPreviousPage() {
if (startId-pageSize > 0) {
return true;
}
return false;
}
public String next() {
startId = endId+1;
endId = endId + pageSize;
recreateModel();
return "index";
}
public String previous() {
startId = startId - pageSize;
endId = endId - pageSize;
recreateModel();
return "index";
}
public int getPageSize() {
return pageSize;
}
public String prepareView(){
current = (Festivals) getFestivalNames().getRowData();
return "browse";
}
public String prepareList(){
recreateModel();
return "index";
}
// alle bands van een bepaald festival ophalen en achter elkaar zetten
public String getBands() {
List bands = helper.getBandsByID(current.getFestId());
StringBuilder totalLineUp = new StringBuilder();
for (int i = 0; i < bands.size(); i++) {
Bands band = (Bands) bands.get(i);
totalLineUp.append(band.getBandNaam());
totalLineUp.append(" : ");
totalLineUp.append(band.getBandSoortMuziek());
totalLineUp.append("; ");
}
return totalLineUp.toString();
}
// alle tickets<SUF>
public String getTicketypes() {
List tickets = helper.getTicketsByID(current.getFestId());
StringBuilder totalTickets = new StringBuilder();
for (int i = 0; i < tickets.size(); i++) {
Tickettypes ticket = (Tickettypes) tickets.get(i);
totalTickets.append(ticket.getTypOmschr());
totalTickets.append(" : €");
totalTickets.append(ticket.getTypPrijs().toString());
totalTickets.append("; ");
}
return totalTickets.toString();
}
}
|
14678_12 | package nl.nijmegen.mule.agelimits;
import java.time.LocalDate;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.api.transport.PropertyScope;
import org.mule.transformer.AbstractMessageTransformer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class calculateAgeLimits extends AbstractMessageTransformer{
private static Log logger = LogFactory.getLog("nl.Nijmegen.brp.irma-api.calculateagelimits");
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
//Zet geboortedatum
//String bDay = "20000000";
//String bDay = message.getInvocationProperty("sv_geboortedatum");
String bDay = message.getProperty("sv_geboortedatum", PropertyScope.INVOCATION);
//Code uit elkaar halen op jaar, maand en dag
int lengteBDay = bDay.length();
if (lengteBDay !=8) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
//Code uit elkaar halen op jaar, maand en dag
String bYear = (bDay.substring(0,4));
String bMonth1= bDay.substring(bDay.length() - 4);
String bMonth2 = (bMonth1.substring(0,2));
String bDag = bDay.substring(bDay.length() - 2);
//omzetten naar een int.
int bYearInt = Integer.parseInt(bYear);
int bMonthInt = Integer.parseInt(bMonth2);
int bDagInt = Integer.parseInt(bDag);
logger.debug("jaar: " + bYearInt);
logger.debug("maand: " + bMonthInt);
logger.debug("dag: " + bDagInt);
if (bYearInt ==0 || bYearInt <1850) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
if (bMonthInt >12) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
if (bDagInt >31) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
//als maand null is dan 1 juli invullen
if (bMonthInt == 0) {
bMonthInt = 1;
bMonthInt = 7;}
//als dag null is, dan waarde op 1 zetten en vervolgens naar laatste dag van de maand
if (bDagInt == 00) {
LocalDate noDay = LocalDate.of(bYearInt,bMonthInt,1);
LocalDate end = noDay.withDayOfMonth(noDay.lengthOfMonth());
int dayOfMonth = end.getDayOfMonth();
bDagInt = dayOfMonth;
}
if (bMonthInt == 2 & bDagInt == 29) {
bDagInt=28;
}
String resultString = "";
//geboortedag bepalen
LocalDate currentTime = LocalDate.now();
LocalDate birthday = LocalDate.of(bYearInt,bMonthInt,bDagInt);
logger.debug("Huidige datum: " + currentTime);
logger.debug("Geboortedatum: " + birthday);
//array maken met alle jaren erin
int[] jaar = new int[] {12,16,18,21,65};
for (int i=0; i<jaar.length; i++)
{
//door array lopen
//in de array current date bepalen
//jaren van currentdate afhalen
LocalDate date1 = LocalDate.now().minusYears(jaar[i]);
String resultValue;
String resultLabel;
//vergelijken geboortedatum en currentdate
if(date1.isBefore(birthday)) {
resultValue = "No";
}
else {
resultValue = "Yes";
}
//string met "isOver+jaar":'ja/nee'" vullen en concateren over loop heen
resultLabel = "\"" +"over" + jaar[i];
resultString = resultString + resultLabel + "\"" +":"+ "\"" + resultValue + "\"" + ",";
}
//resultString teruggeven
resultString = "{" + resultString.substring(0, resultString.length()-1) +"}";
resultString = "{"+ "\""+"ageLimits"+"\""+": " + resultString +"}";
logger.debug("resultString: " + resultString);
return resultString;
}
};
| GemeenteNijmegen/irma-brp-opladen | src/api-source/calculateAgeLimits.java | 1,510 | //string met "isOver+jaar":'ja/nee'" vullen en concateren over loop heen
| line_comment | nl | package nl.nijmegen.mule.agelimits;
import java.time.LocalDate;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.api.transport.PropertyScope;
import org.mule.transformer.AbstractMessageTransformer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class calculateAgeLimits extends AbstractMessageTransformer{
private static Log logger = LogFactory.getLog("nl.Nijmegen.brp.irma-api.calculateagelimits");
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
//Zet geboortedatum
//String bDay = "20000000";
//String bDay = message.getInvocationProperty("sv_geboortedatum");
String bDay = message.getProperty("sv_geboortedatum", PropertyScope.INVOCATION);
//Code uit elkaar halen op jaar, maand en dag
int lengteBDay = bDay.length();
if (lengteBDay !=8) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
//Code uit elkaar halen op jaar, maand en dag
String bYear = (bDay.substring(0,4));
String bMonth1= bDay.substring(bDay.length() - 4);
String bMonth2 = (bMonth1.substring(0,2));
String bDag = bDay.substring(bDay.length() - 2);
//omzetten naar een int.
int bYearInt = Integer.parseInt(bYear);
int bMonthInt = Integer.parseInt(bMonth2);
int bDagInt = Integer.parseInt(bDag);
logger.debug("jaar: " + bYearInt);
logger.debug("maand: " + bMonthInt);
logger.debug("dag: " + bDagInt);
if (bYearInt ==0 || bYearInt <1850) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
if (bMonthInt >12) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
if (bDagInt >31) {
throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");
}
//als maand null is dan 1 juli invullen
if (bMonthInt == 0) {
bMonthInt = 1;
bMonthInt = 7;}
//als dag null is, dan waarde op 1 zetten en vervolgens naar laatste dag van de maand
if (bDagInt == 00) {
LocalDate noDay = LocalDate.of(bYearInt,bMonthInt,1);
LocalDate end = noDay.withDayOfMonth(noDay.lengthOfMonth());
int dayOfMonth = end.getDayOfMonth();
bDagInt = dayOfMonth;
}
if (bMonthInt == 2 & bDagInt == 29) {
bDagInt=28;
}
String resultString = "";
//geboortedag bepalen
LocalDate currentTime = LocalDate.now();
LocalDate birthday = LocalDate.of(bYearInt,bMonthInt,bDagInt);
logger.debug("Huidige datum: " + currentTime);
logger.debug("Geboortedatum: " + birthday);
//array maken met alle jaren erin
int[] jaar = new int[] {12,16,18,21,65};
for (int i=0; i<jaar.length; i++)
{
//door array lopen
//in de array current date bepalen
//jaren van currentdate afhalen
LocalDate date1 = LocalDate.now().minusYears(jaar[i]);
String resultValue;
String resultLabel;
//vergelijken geboortedatum en currentdate
if(date1.isBefore(birthday)) {
resultValue = "No";
}
else {
resultValue = "Yes";
}
//string met<SUF>
resultLabel = "\"" +"over" + jaar[i];
resultString = resultString + resultLabel + "\"" +":"+ "\"" + resultValue + "\"" + ",";
}
//resultString teruggeven
resultString = "{" + resultString.substring(0, resultString.length()-1) +"}";
resultString = "{"+ "\""+"ageLimits"+"\""+": " + resultString +"}";
logger.debug("resultString: " + resultString);
return resultString;
}
};
|
83985_13 | /**
* %HEADER%
*/
package net.sf.genomeview.gui.viztracks.hts;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.JWindow;
import javax.swing.border.Border;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import net.sf.genomeview.core.Configuration;
import net.sf.genomeview.data.Model;
import net.sf.genomeview.data.provider.ShortReadProvider;
import net.sf.genomeview.gui.Convert;
import net.sf.genomeview.gui.MessageManager;
import net.sf.genomeview.gui.viztracks.Track;
import net.sf.genomeview.gui.viztracks.TrackCommunicationModel;
import net.sf.jannot.DataKey;
import net.sf.jannot.Location;
import net.sf.samtools.SAMRecord;
/**
*
* @author Thomas Abeel
*
*/
public class ShortReadTrack extends Track {
private srtRender render;
// private ShortReadProvider provider;
private ShortReadTrackConfig srtc;
public ShortReadTrack(DataKey key, ShortReadProvider provider, Model model) {
super(key, model, true, new ShortReadTrackConfig(model, key));
this.srtc = (ShortReadTrackConfig) config;
// this.provider = provider;
render = new srtRender(model, provider, srtc, key);
}
private InsertionTooltip tooltip = new InsertionTooltip();
private ReadInfo readinfo = new ReadInfo();
private static class InsertionTooltip extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public InsertionTooltip() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, ShortReadInsertion sri) {
if (sri == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sri != null) {
text.append(MessageManager.getString("shortreadtrack.insertion") + " ");
byte[] bases = sri.esr.getReadBases();
for (int i = sri.start; i < sri.start + sri.len; i++) {
text.append((char) bases[i]);
}
text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
}
private static class ReadInfo extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public ReadInfo() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, SAMRecord sr) {
if (sr == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sr != null) {
text.append(MessageManager.getString("shortreadtrack.name") + " " + sr.getReadName() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.len") + " " + sr.getReadLength() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.cigar") + " " + sr.getCigarString() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.sequence") + " " + rerun(sr.getReadString()) + "<br/>");
text.append(MessageManager.getString("shortreadtrack.paired") + " " + sr.getReadPairedFlag() + "<br/>");
if (sr.getReadPairedFlag()) {
if (!sr.getMateUnmappedFlag())
text.append(MessageManager.getString("shortreadtrack.mate") + " " + sr.getMateReferenceName() + ":" + sr.getMateAlignmentStart()
+ "<br/>");
else
text.append(MessageManager.getString("shortreadtrack.mate_missing") + "<br/>");
text.append(MessageManager.getString("shortreadtrack.second") + " " + sr.getFirstOfPairFlag());
}
// text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
public void textual() {
if(!isVisible())
return;
// create jeditorpane
JEditorPane jEditorPane = new JEditorPane();
// make it read-only
jEditorPane.setEditable(false);
// create a scrollpane; modify its attributes as desired
JScrollPane scrollPane = new JScrollPane(jEditorPane);
// add an html editor kit
HTMLEditorKit kit = new HTMLEditorKit();
jEditorPane.setEditorKit(kit);
Document doc = kit.createDefaultDocument();
jEditorPane.setDocument(doc);
jEditorPane.setText(floater.getText());
// now add it all to a frame
JFrame j = new JFrame("Read information");
j.getContentPane().add(scrollPane, BorderLayout.CENTER);
// make it easy to close the application
j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// display the frame
j.setSize(new Dimension(300, 200));
// pack it, if you prefer
// j.pack();
// center the jframe, then make it visible
j.setLocationRelativeTo(null);
j.setVisible(true);
}
}
private static String rerun(String arg) {
StringBuffer out = new StringBuffer();
int i = 0;
for (; i < arg.length() - 80; i += 80)
out.append(arg.substring(i, i + 80) + "<br/>");
out.append(arg.substring(i, arg.length()));
return out.toString();
}
@Override
public boolean mouseExited(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseClicked(int x, int y, MouseEvent source) {
super.mouseClicked(x, y, source);
if (source.isConsumed())
return true;
// System.out.println("Click: " + x + " " + y);
if (source.getClickCount() > 1) {
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
System.out.println("2*Click: " + e.getValue());
if (e.getValue().getReadPairedFlag() && !e.getValue().getMateUnmappedFlag())
model.vlm.center(e.getValue().getMateAlignmentStart());
}
}
} else {
readinfo.textual();
}
return false;
}
@Override
public boolean mouseDragged(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseMoved(int x, int y, MouseEvent source) {
if (model.vlm.getAnnotationLocationVisible().length() < Configuration.getInt("geneStructureNucleotideWindow")) {
ShortReadInsertion sri = null;
for (java.util.Map.Entry<Rectangle, ShortReadInsertion> e : render.meta().paintedBlocks.entrySet()) {
if (e.getKey().contains(x, y)) {
sri = e.getValue();
break;
}
}
if (sri != null) {
if (!tooltip.isVisible())
tooltip.setVisible(true);
tooltip.set(source, sri);
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
//
// System.out.println("Moved: " + x + " " + y);
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
// System.out.println("Prijs: " + e.getValue());
readinfo.set(source, e.getValue());
}
}
//
return false;
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
return false;
}
@Override
public int paintTrack(Graphics2D gGlobal, int yOffset, double screenWidth, JViewport view, TrackCommunicationModel tcm) {
// Location bufferedLocation = render.location();
// Location visible = model.vlm.getVisibleLocation();
// int x = 0;
// if (bufferedLocation != null)
// x = Convert.translateGenomeToScreen(bufferedLocation.start, visible, screenWidth);
gGlobal.drawImage(render.buffer(), 0, yOffset, null);
return render.buffer().getHeight();
}
}
| GenomeView/genomeview | src/net/sf/genomeview/gui/viztracks/hts/ShortReadTrack.java | 2,934 | // System.out.println("Prijs: " + e.getValue()); | line_comment | nl | /**
* %HEADER%
*/
package net.sf.genomeview.gui.viztracks.hts;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.JWindow;
import javax.swing.border.Border;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import net.sf.genomeview.core.Configuration;
import net.sf.genomeview.data.Model;
import net.sf.genomeview.data.provider.ShortReadProvider;
import net.sf.genomeview.gui.Convert;
import net.sf.genomeview.gui.MessageManager;
import net.sf.genomeview.gui.viztracks.Track;
import net.sf.genomeview.gui.viztracks.TrackCommunicationModel;
import net.sf.jannot.DataKey;
import net.sf.jannot.Location;
import net.sf.samtools.SAMRecord;
/**
*
* @author Thomas Abeel
*
*/
public class ShortReadTrack extends Track {
private srtRender render;
// private ShortReadProvider provider;
private ShortReadTrackConfig srtc;
public ShortReadTrack(DataKey key, ShortReadProvider provider, Model model) {
super(key, model, true, new ShortReadTrackConfig(model, key));
this.srtc = (ShortReadTrackConfig) config;
// this.provider = provider;
render = new srtRender(model, provider, srtc, key);
}
private InsertionTooltip tooltip = new InsertionTooltip();
private ReadInfo readinfo = new ReadInfo();
private static class InsertionTooltip extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public InsertionTooltip() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, ShortReadInsertion sri) {
if (sri == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sri != null) {
text.append(MessageManager.getString("shortreadtrack.insertion") + " ");
byte[] bases = sri.esr.getReadBases();
for (int i = sri.start; i < sri.start + sri.len; i++) {
text.append((char) bases[i]);
}
text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
}
private static class ReadInfo extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public ReadInfo() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, SAMRecord sr) {
if (sr == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sr != null) {
text.append(MessageManager.getString("shortreadtrack.name") + " " + sr.getReadName() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.len") + " " + sr.getReadLength() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.cigar") + " " + sr.getCigarString() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.sequence") + " " + rerun(sr.getReadString()) + "<br/>");
text.append(MessageManager.getString("shortreadtrack.paired") + " " + sr.getReadPairedFlag() + "<br/>");
if (sr.getReadPairedFlag()) {
if (!sr.getMateUnmappedFlag())
text.append(MessageManager.getString("shortreadtrack.mate") + " " + sr.getMateReferenceName() + ":" + sr.getMateAlignmentStart()
+ "<br/>");
else
text.append(MessageManager.getString("shortreadtrack.mate_missing") + "<br/>");
text.append(MessageManager.getString("shortreadtrack.second") + " " + sr.getFirstOfPairFlag());
}
// text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
public void textual() {
if(!isVisible())
return;
// create jeditorpane
JEditorPane jEditorPane = new JEditorPane();
// make it read-only
jEditorPane.setEditable(false);
// create a scrollpane; modify its attributes as desired
JScrollPane scrollPane = new JScrollPane(jEditorPane);
// add an html editor kit
HTMLEditorKit kit = new HTMLEditorKit();
jEditorPane.setEditorKit(kit);
Document doc = kit.createDefaultDocument();
jEditorPane.setDocument(doc);
jEditorPane.setText(floater.getText());
// now add it all to a frame
JFrame j = new JFrame("Read information");
j.getContentPane().add(scrollPane, BorderLayout.CENTER);
// make it easy to close the application
j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// display the frame
j.setSize(new Dimension(300, 200));
// pack it, if you prefer
// j.pack();
// center the jframe, then make it visible
j.setLocationRelativeTo(null);
j.setVisible(true);
}
}
private static String rerun(String arg) {
StringBuffer out = new StringBuffer();
int i = 0;
for (; i < arg.length() - 80; i += 80)
out.append(arg.substring(i, i + 80) + "<br/>");
out.append(arg.substring(i, arg.length()));
return out.toString();
}
@Override
public boolean mouseExited(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseClicked(int x, int y, MouseEvent source) {
super.mouseClicked(x, y, source);
if (source.isConsumed())
return true;
// System.out.println("Click: " + x + " " + y);
if (source.getClickCount() > 1) {
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
System.out.println("2*Click: " + e.getValue());
if (e.getValue().getReadPairedFlag() && !e.getValue().getMateUnmappedFlag())
model.vlm.center(e.getValue().getMateAlignmentStart());
}
}
} else {
readinfo.textual();
}
return false;
}
@Override
public boolean mouseDragged(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseMoved(int x, int y, MouseEvent source) {
if (model.vlm.getAnnotationLocationVisible().length() < Configuration.getInt("geneStructureNucleotideWindow")) {
ShortReadInsertion sri = null;
for (java.util.Map.Entry<Rectangle, ShortReadInsertion> e : render.meta().paintedBlocks.entrySet()) {
if (e.getKey().contains(x, y)) {
sri = e.getValue();
break;
}
}
if (sri != null) {
if (!tooltip.isVisible())
tooltip.setVisible(true);
tooltip.set(source, sri);
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
//
// System.out.println("Moved: " + x + " " + y);
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
// System.out.println("Prijs: "<SUF>
readinfo.set(source, e.getValue());
}
}
//
return false;
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
return false;
}
@Override
public int paintTrack(Graphics2D gGlobal, int yOffset, double screenWidth, JViewport view, TrackCommunicationModel tcm) {
// Location bufferedLocation = render.location();
// Location visible = model.vlm.getVisibleLocation();
// int x = 0;
// if (bufferedLocation != null)
// x = Convert.translateGenomeToScreen(bufferedLocation.start, visible, screenWidth);
gGlobal.drawImage(render.buffer(), 0, yOffset, null);
return render.buffer().getHeight();
}
}
|
58015_1 | package com.digicoachindezorg.didz_backend.config;
import com.digicoachindezorg.didz_backend.filter.JwtRequestFilter;
import com.digicoachindezorg.didz_backend.services.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
public final PasswordEncoder passwordEncoder;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService , PasswordEncoder passwordEncoder, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.passwordEncoder = passwordEncoder;
this.jwtRequestFilter = jwtRequestFilter;
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder)
.and()
.build();
}
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
.requestMatchers(HttpMethod.POST,"/authenticate").permitAll()
.requestMatchers(HttpMethod.GET, "/authenticated").authenticated()
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET, "/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/users/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/users/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/users/{id}/authorities").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/contactform").permitAll()
.requestMatchers(HttpMethod.GET, "/contactform").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/contactform/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/contactform/{id}").hasRole("ADMIN") //todo: Niemand kan dit aanpassen.
.requestMatchers(HttpMethod.DELETE, "/contactform/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/reviews").hasRole("USER")
.requestMatchers(HttpMethod.PUT,"/reviews/{id}").hasRole("USER")
.requestMatchers(HttpMethod.DELETE,"/reviews/{id}").hasAnyRole("USER", "ADMIN")
.requestMatchers(HttpMethod.GET,"/reviews/{id}").permitAll()
.requestMatchers(HttpMethod.GET,"/reviews/product/{productId}").permitAll()
.requestMatchers(HttpMethod.GET, "/invoices").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/invoices/new-user").permitAll()
.requestMatchers(HttpMethod.POST,"/invoices/existing-user").hasRole("USER")
.requestMatchers(HttpMethod.PUT,"/invoices/{invoiceId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE,"/invoices/{invoiceId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET,"/invoices/{invoiceId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET,"/invoices/user/{userId}").hasAnyRole("USER","ADMIN")
.requestMatchers(HttpMethod.POST,"/messages").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.PUT,"/messages/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.DELETE,"/messages/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/messages/{id}").hasAnyRole("USER", "COACH", "ADMIN") //todo: Extra logica bouwen, user mag berichten van zichzelf openen, digicoach alleen van studygroup, admin alles. (User ophalen en checken of het bericht met id in zijn berichtenbox zit. Zo niet een error, anders show message)
.requestMatchers(HttpMethod.GET,"/messages/date/{date}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/messages/users/{userId}").hasRole("ADMIN") //todo: Mogelijk endpoint weghalen omdat de admin dit niet zomaar mag, dit kan ook in de database.
.requestMatchers(HttpMethod.GET,"/messages/sent/{userId}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/messages/study-group/{studyGroupId}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.POST,"/products").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT,"/products/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE,"/products/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET,"/products/{id}").permitAll()
.requestMatchers(HttpMethod.GET,"/products").permitAll()
.requestMatchers(HttpMethod.GET,"/products/by-user/{userId}").permitAll()
.requestMatchers(HttpMethod.POST, "/study-group").hasAnyRole("COACH","ADMIN")
.requestMatchers(HttpMethod.PUT, "/study-group/{id}").hasAnyRole("COACH","ADMIN")
.requestMatchers(HttpMethod.DELETE, "/study-group/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/{id}").hasAnyRole("USER", "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/by-product/{productId}").hasAnyRole( "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/study-group/{studyGroupId}/users/{userId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/study-group/{studyGroupId}/users/{userId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/{studyGroupId}/users").hasAnyRole("USER","COACH","ADMIN")
.requestMatchers(HttpMethod.POST, "/uploadprofilepic/{userId}").hasAnyRole("USER", "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/downloadprofilepic/{userId}").permitAll()
.requestMatchers(HttpMethod.DELETE, "/deleteprofilepic/{userId}").hasAnyRole("USER", "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/by-user/{userId}").hasRole("USER")
.anyRequest().denyAll()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} | Gentlemannerss/DIDZ_Backend | src/main/java/com/digicoachindezorg/didz_backend/config/SpringSecurityConfig.java | 2,213 | //todo: Extra logica bouwen, user mag berichten van zichzelf openen, digicoach alleen van studygroup, admin alles. (User ophalen en checken of het bericht met id in zijn berichtenbox zit. Zo niet een error, anders show message) | line_comment | nl | package com.digicoachindezorg.didz_backend.config;
import com.digicoachindezorg.didz_backend.filter.JwtRequestFilter;
import com.digicoachindezorg.didz_backend.services.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
public final PasswordEncoder passwordEncoder;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService , PasswordEncoder passwordEncoder, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.passwordEncoder = passwordEncoder;
this.jwtRequestFilter = jwtRequestFilter;
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder)
.and()
.build();
}
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
.requestMatchers(HttpMethod.POST,"/authenticate").permitAll()
.requestMatchers(HttpMethod.GET, "/authenticated").authenticated()
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET, "/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/users/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/users/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/users/{id}/authorities").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/contactform").permitAll()
.requestMatchers(HttpMethod.GET, "/contactform").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/contactform/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/contactform/{id}").hasRole("ADMIN") //todo: Niemand kan dit aanpassen.
.requestMatchers(HttpMethod.DELETE, "/contactform/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/reviews").hasRole("USER")
.requestMatchers(HttpMethod.PUT,"/reviews/{id}").hasRole("USER")
.requestMatchers(HttpMethod.DELETE,"/reviews/{id}").hasAnyRole("USER", "ADMIN")
.requestMatchers(HttpMethod.GET,"/reviews/{id}").permitAll()
.requestMatchers(HttpMethod.GET,"/reviews/product/{productId}").permitAll()
.requestMatchers(HttpMethod.GET, "/invoices").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/invoices/new-user").permitAll()
.requestMatchers(HttpMethod.POST,"/invoices/existing-user").hasRole("USER")
.requestMatchers(HttpMethod.PUT,"/invoices/{invoiceId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE,"/invoices/{invoiceId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET,"/invoices/{invoiceId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET,"/invoices/user/{userId}").hasAnyRole("USER","ADMIN")
.requestMatchers(HttpMethod.POST,"/messages").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.PUT,"/messages/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.DELETE,"/messages/{id}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/messages/{id}").hasAnyRole("USER", "COACH", "ADMIN") //todo: Extra<SUF>
.requestMatchers(HttpMethod.GET,"/messages/date/{date}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/messages/users/{userId}").hasRole("ADMIN") //todo: Mogelijk endpoint weghalen omdat de admin dit niet zomaar mag, dit kan ook in de database.
.requestMatchers(HttpMethod.GET,"/messages/sent/{userId}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.GET,"/messages/study-group/{studyGroupId}").hasAnyRole("USER", "COACH", "ADMIN")
.requestMatchers(HttpMethod.POST,"/products").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT,"/products/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE,"/products/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET,"/products/{id}").permitAll()
.requestMatchers(HttpMethod.GET,"/products").permitAll()
.requestMatchers(HttpMethod.GET,"/products/by-user/{userId}").permitAll()
.requestMatchers(HttpMethod.POST, "/study-group").hasAnyRole("COACH","ADMIN")
.requestMatchers(HttpMethod.PUT, "/study-group/{id}").hasAnyRole("COACH","ADMIN")
.requestMatchers(HttpMethod.DELETE, "/study-group/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/{id}").hasAnyRole("USER", "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/by-product/{productId}").hasAnyRole( "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/study-group/{studyGroupId}/users/{userId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/study-group/{studyGroupId}/users/{userId}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/{studyGroupId}/users").hasAnyRole("USER","COACH","ADMIN")
.requestMatchers(HttpMethod.POST, "/uploadprofilepic/{userId}").hasAnyRole("USER", "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/downloadprofilepic/{userId}").permitAll()
.requestMatchers(HttpMethod.DELETE, "/deleteprofilepic/{userId}").hasAnyRole("USER", "COACH","ADMIN")
.requestMatchers(HttpMethod.GET, "/study-group/by-user/{userId}").hasRole("USER")
.anyRequest().denyAll()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} |
174929_3 | package com.techiteasy.techiteasycontrolleruitwerkingen.dtos;
import com.techiteasy.techiteasycontrolleruitwerkingen.models.Television;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TelevisionDto {
//id kun je meegeven, maar dit is een afweging. Misschien wil iemand het id wel opvragen.
private Long id; //property is changed to private. This is to ensure that the id is not directly modified from outside the class.
@NotNull //dit zorgt dat je kunt controleren en invloed hebt op de inhoud.
public String type;
public String brand;
@NotBlank
public String name;
@Min(1) //deze annotaties gebruik je voornamelijk bij input, bij output is dit al gecheckt (behalve misschien wachtwoord)
public Double price;
public Double availableSize;
public Double refreshRate;
public String screenType;
public String screenQuality;
public Boolean smartTv;
public Boolean wifi;
public Boolean voiceControl;
public Boolean hdr;
public Boolean bluetooth;
public Boolean ambiLight;
public Integer originalStock;
public Integer sold;
// Constructor
public TelevisionDto() {
}
// Static method to create a TelevisionDto from a Television object
public static TelevisionDto fromTelevision(Television television) {
TelevisionDto dto = new TelevisionDto();
dto.id = television.getId();
dto.type = television.getType();
dto.brand = television.getBrand();
dto.name = television.getName();
dto.price = television.getPrice();
dto.availableSize = television.getAvailableSize();
dto.refreshRate = television.getRefreshRate();
dto.screenType = television.getScreenType();
dto.screenQuality = television.getScreenQuality();
dto.smartTv = television.getSmartTv();
dto.wifi = television.getWifi();
dto.voiceControl = television.getVoiceControl();
dto.hdr = television.getHdr();
dto.bluetooth = television.getBluetooth();
dto.ambiLight = television.getAmbiLight();
dto.originalStock = television.getOriginalStock();
dto.sold = television.getSold();
return dto;
}
}
| Gentlemannerss/TechItEasyController | src/main/java/com/techiteasy/techiteasycontrolleruitwerkingen/dtos/TelevisionDto.java | 676 | //deze annotaties gebruik je voornamelijk bij input, bij output is dit al gecheckt (behalve misschien wachtwoord) | line_comment | nl | package com.techiteasy.techiteasycontrolleruitwerkingen.dtos;
import com.techiteasy.techiteasycontrolleruitwerkingen.models.Television;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TelevisionDto {
//id kun je meegeven, maar dit is een afweging. Misschien wil iemand het id wel opvragen.
private Long id; //property is changed to private. This is to ensure that the id is not directly modified from outside the class.
@NotNull //dit zorgt dat je kunt controleren en invloed hebt op de inhoud.
public String type;
public String brand;
@NotBlank
public String name;
@Min(1) //deze annotaties<SUF>
public Double price;
public Double availableSize;
public Double refreshRate;
public String screenType;
public String screenQuality;
public Boolean smartTv;
public Boolean wifi;
public Boolean voiceControl;
public Boolean hdr;
public Boolean bluetooth;
public Boolean ambiLight;
public Integer originalStock;
public Integer sold;
// Constructor
public TelevisionDto() {
}
// Static method to create a TelevisionDto from a Television object
public static TelevisionDto fromTelevision(Television television) {
TelevisionDto dto = new TelevisionDto();
dto.id = television.getId();
dto.type = television.getType();
dto.brand = television.getBrand();
dto.name = television.getName();
dto.price = television.getPrice();
dto.availableSize = television.getAvailableSize();
dto.refreshRate = television.getRefreshRate();
dto.screenType = television.getScreenType();
dto.screenQuality = television.getScreenQuality();
dto.smartTv = television.getSmartTv();
dto.wifi = television.getWifi();
dto.voiceControl = television.getVoiceControl();
dto.hdr = television.getHdr();
dto.bluetooth = television.getBluetooth();
dto.ambiLight = television.getAmbiLight();
dto.originalStock = television.getOriginalStock();
dto.sold = television.getSold();
return dto;
}
}
|
52480_0 | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
| Gentlemannerss/digicoachindezorg_backend | src/main/java/com/digicoachindezorg/digicoachindezorg_backend/config/GlobalCorsConfiguration.java | 323 | /*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/ | block_comment | nl | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin<SUF>*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
|
12240_3 | package SecurityForSpringBoot.config;
// Import the JwtRequestFilter
// Import the CustomUserDetailsService
import SecurityForSpringBoot.filter.JwtRequestFilter;
import SecurityForSpringBoot.services.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.jwtRequestFilter = jwtRequestFilter;
}
// Authenticatie met customUserDetailsService en passwordEncoder
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}
// PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig.
// Je kunt dit ook in een aparte configuratie klasse zetten.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Authorizatie met jwt
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
//JWT token authentication
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
//Vanaf hier ga je zeggen welke rol een bepaalde request mag doen:
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
//Voeg hier de overige requestMatchers toe:
//Het is ook mogelijk om meedere paths tegelijk te defineren.
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()/*allen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/
.anyRequest().denyAll()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} | Gentlemannerss/spring-boot-security | src/SecurityForSpringBoot/config/SpringSecurityConfig.java | 887 | // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. | line_comment | nl | package SecurityForSpringBoot.config;
// Import the JwtRequestFilter
// Import the CustomUserDetailsService
import SecurityForSpringBoot.filter.JwtRequestFilter;
import SecurityForSpringBoot.services.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.jwtRequestFilter = jwtRequestFilter;
}
// Authenticatie met customUserDetailsService en passwordEncoder
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}
// PasswordEncoderBean. Deze<SUF>
// Je kunt dit ook in een aparte configuratie klasse zetten.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Authorizatie met jwt
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
//JWT token authentication
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
//Vanaf hier ga je zeggen welke rol een bepaalde request mag doen:
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
//Voeg hier de overige requestMatchers toe:
//Het is ook mogelijk om meedere paths tegelijk te defineren.
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()/*allen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/
.anyRequest().denyAll()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} |
134392_0 | package be.ugent.gsr.financien.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Lob;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Document extends AbstractAuditableEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Lob
@Column(nullable = false)
private byte[] pdfData; // Dit is niet super efficient voor een databank maar het is wel veel gemakkelijker dan files opslaan in een filepath
/*
* Momenteel enkel PDF's maar het kan zeker uitgebreid worden naar andere filetypes
*/
//@Column(nullable = false)
//private String filetype;
}
| GentseStudentenraad/fin-platform | backend/src/main/java/be/ugent/gsr/financien/domain/Document.java | 300 | // Dit is niet super efficient voor een databank maar het is wel veel gemakkelijker dan files opslaan in een filepath | line_comment | nl | package be.ugent.gsr.financien.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Lob;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Document extends AbstractAuditableEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Lob
@Column(nullable = false)
private byte[] pdfData; // Dit is<SUF>
/*
* Momenteel enkel PDF's maar het kan zeker uitgebreid worden naar andere filetypes
*/
//@Column(nullable = false)
//private String filetype;
}
|
2065_25 | package com.genymobile.scrcpy;
import android.media.MediaCodec;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
public final class Streamer {
private static final long PACKET_FLAG_CONFIG = 1L << 63;
private static final long PACKET_FLAG_KEY_FRAME = 1L << 62;
private final FileDescriptor fd;
private final Codec codec;
private final boolean sendCodecMeta;
private final boolean sendFrameMeta;
private final ByteBuffer headerBuffer = ByteBuffer.allocate(12);
public Streamer(FileDescriptor fd, Codec codec, boolean sendCodecMeta, boolean sendFrameMeta) {
this.fd = fd;
this.codec = codec;
this.sendCodecMeta = sendCodecMeta;
this.sendFrameMeta = sendFrameMeta;
}
public Codec getCodec() {
return codec;
}
public void writeAudioHeader() throws IOException {
if (sendCodecMeta) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(codec.getId());
buffer.flip();
IO.writeFully(fd, buffer);
}
}
public void writeVideoHeader(Size videoSize) throws IOException {
if (sendCodecMeta) {
ByteBuffer buffer = ByteBuffer.allocate(12);
buffer.putInt(codec.getId());
buffer.putInt(videoSize.getWidth());
buffer.putInt(videoSize.getHeight());
buffer.flip();
IO.writeFully(fd, buffer);
}
}
public void writeDisableStream(boolean error) throws IOException {
// Writing a specific code as codec-id means that the device disables the stream
// code 0: it explicitly disables the stream (because it could not capture audio), scrcpy should continue mirroring video only
// code 1: a configuration error occurred, scrcpy must be stopped
byte[] code = new byte[4];
if (error) {
code[3] = 1;
}
IO.writeFully(fd, code, 0, code.length);
}
public void writePacket(ByteBuffer buffer, long pts, boolean config, boolean keyFrame) throws IOException {
if (config) {
if (codec == AudioCodec.OPUS) {
fixOpusConfigPacket(buffer);
} else if (codec == AudioCodec.FLAC) {
fixFlacConfigPacket(buffer);
}
}
if (sendFrameMeta) {
writeFrameMeta(fd, buffer.remaining(), pts, config, keyFrame);
}
IO.writeFully(fd, buffer);
}
public void writePacket(ByteBuffer codecBuffer, MediaCodec.BufferInfo bufferInfo) throws IOException {
long pts = bufferInfo.presentationTimeUs;
boolean config = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0;
boolean keyFrame = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0;
writePacket(codecBuffer, pts, config, keyFrame);
}
private void writeFrameMeta(FileDescriptor fd, int packetSize, long pts, boolean config, boolean keyFrame) throws IOException {
headerBuffer.clear();
long ptsAndFlags;
if (config) {
ptsAndFlags = PACKET_FLAG_CONFIG; // non-media data packet
} else {
ptsAndFlags = pts;
if (keyFrame) {
ptsAndFlags |= PACKET_FLAG_KEY_FRAME;
}
}
headerBuffer.putLong(ptsAndFlags);
headerBuffer.putInt(packetSize);
headerBuffer.flip();
IO.writeFully(fd, headerBuffer);
}
private static void fixOpusConfigPacket(ByteBuffer buffer) throws IOException {
// Here is an example of the config packet received for an OPUS stream:
//
// 00000000 41 4f 50 55 53 48 44 52 13 00 00 00 00 00 00 00 |AOPUSHDR........|
// -------------- BELOW IS THE PART WE MUST PUT AS EXTRADATA -------------------
// 00000010 4f 70 75 73 48 65 61 64 01 01 38 01 80 bb 00 00 |OpusHead..8.....|
// 00000020 00 00 00 |... |
// ------------------------------------------------------------------------------
// 00000020 41 4f 50 55 53 44 4c 59 08 00 00 00 00 | AOPUSDLY.....|
// 00000030 00 00 00 a0 2e 63 00 00 00 00 00 41 4f 50 55 53 |.....c.....AOPUS|
// 00000040 50 52 4c 08 00 00 00 00 00 00 00 00 b4 c4 04 00 |PRL.............|
// 00000050 00 00 00 |...|
//
// Each "section" is prefixed by a 64-bit ID and a 64-bit length.
//
// <https://developer.android.com/reference/android/media/MediaCodec#CSD>
if (buffer.remaining() < 16) {
throw new IOException("Not enough data in OPUS config packet");
}
final byte[] opusHeaderId = {'A', 'O', 'P', 'U', 'S', 'H', 'D', 'R'};
byte[] idBuffer = new byte[8];
buffer.get(idBuffer);
if (!Arrays.equals(idBuffer, opusHeaderId)) {
throw new IOException("OPUS header not found");
}
// The size is in native byte-order
long sizeLong = buffer.getLong();
if (sizeLong < 0 || sizeLong >= 0x7FFFFFFF) {
throw new IOException("Invalid block size in OPUS header: " + sizeLong);
}
int size = (int) sizeLong;
if (buffer.remaining() < size) {
throw new IOException("Not enough data in OPUS header (invalid size: " + size + ")");
}
// Set the buffer to point to the OPUS header slice
buffer.limit(buffer.position() + size);
}
private static void fixFlacConfigPacket(ByteBuffer buffer) throws IOException {
// 00000000 66 4c 61 43 00 00 00 22 |fLaC..." |
// -------------- BELOW IS THE PART WE MUST PUT AS EXTRADATA -------------------
// 00000000 10 00 10 00 00 00 00 00 | ........|
// 00000010 00 00 0b b8 02 f0 00 00 00 00 00 00 00 00 00 00 |................|
// 00000020 00 00 00 00 00 00 00 00 00 00 |.......... |
// ------------------------------------------------------------------------------
// 00000020 84 00 00 28 20 00 | ...( .|
// 00000030 00 00 72 65 66 65 72 65 6e 63 65 20 6c 69 62 46 |..reference libF|
// 00000040 4c 41 43 20 31 2e 33 2e 32 20 32 30 32 32 31 30 |LAC 1.3.2 202210|
// 00000050 32 32 00 00 00 00 |22....|
//
// <https://developer.android.com/reference/android/media/MediaCodec#CSD>
if (buffer.remaining() < 8) {
throw new IOException("Not enough data in FLAC config packet");
}
final byte[] flacHeaderId = {'f', 'L', 'a', 'C'};
byte[] idBuffer = new byte[4];
buffer.get(idBuffer);
if (!Arrays.equals(idBuffer, flacHeaderId)) {
throw new IOException("FLAC header not found");
}
// The size is in big-endian
buffer.order(ByteOrder.BIG_ENDIAN);
int size = buffer.getInt();
if (buffer.remaining() < size) {
throw new IOException("Not enough data in FLAC header (invalid size: " + size + ")");
}
// Set the buffer to point to the FLAC header slice
buffer.limit(buffer.position() + size);
}
}
| Genymobile/scrcpy | server/src/main/java/com/genymobile/scrcpy/Streamer.java | 2,315 | // The size is in big-endian | line_comment | nl | package com.genymobile.scrcpy;
import android.media.MediaCodec;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
public final class Streamer {
private static final long PACKET_FLAG_CONFIG = 1L << 63;
private static final long PACKET_FLAG_KEY_FRAME = 1L << 62;
private final FileDescriptor fd;
private final Codec codec;
private final boolean sendCodecMeta;
private final boolean sendFrameMeta;
private final ByteBuffer headerBuffer = ByteBuffer.allocate(12);
public Streamer(FileDescriptor fd, Codec codec, boolean sendCodecMeta, boolean sendFrameMeta) {
this.fd = fd;
this.codec = codec;
this.sendCodecMeta = sendCodecMeta;
this.sendFrameMeta = sendFrameMeta;
}
public Codec getCodec() {
return codec;
}
public void writeAudioHeader() throws IOException {
if (sendCodecMeta) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(codec.getId());
buffer.flip();
IO.writeFully(fd, buffer);
}
}
public void writeVideoHeader(Size videoSize) throws IOException {
if (sendCodecMeta) {
ByteBuffer buffer = ByteBuffer.allocate(12);
buffer.putInt(codec.getId());
buffer.putInt(videoSize.getWidth());
buffer.putInt(videoSize.getHeight());
buffer.flip();
IO.writeFully(fd, buffer);
}
}
public void writeDisableStream(boolean error) throws IOException {
// Writing a specific code as codec-id means that the device disables the stream
// code 0: it explicitly disables the stream (because it could not capture audio), scrcpy should continue mirroring video only
// code 1: a configuration error occurred, scrcpy must be stopped
byte[] code = new byte[4];
if (error) {
code[3] = 1;
}
IO.writeFully(fd, code, 0, code.length);
}
public void writePacket(ByteBuffer buffer, long pts, boolean config, boolean keyFrame) throws IOException {
if (config) {
if (codec == AudioCodec.OPUS) {
fixOpusConfigPacket(buffer);
} else if (codec == AudioCodec.FLAC) {
fixFlacConfigPacket(buffer);
}
}
if (sendFrameMeta) {
writeFrameMeta(fd, buffer.remaining(), pts, config, keyFrame);
}
IO.writeFully(fd, buffer);
}
public void writePacket(ByteBuffer codecBuffer, MediaCodec.BufferInfo bufferInfo) throws IOException {
long pts = bufferInfo.presentationTimeUs;
boolean config = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0;
boolean keyFrame = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0;
writePacket(codecBuffer, pts, config, keyFrame);
}
private void writeFrameMeta(FileDescriptor fd, int packetSize, long pts, boolean config, boolean keyFrame) throws IOException {
headerBuffer.clear();
long ptsAndFlags;
if (config) {
ptsAndFlags = PACKET_FLAG_CONFIG; // non-media data packet
} else {
ptsAndFlags = pts;
if (keyFrame) {
ptsAndFlags |= PACKET_FLAG_KEY_FRAME;
}
}
headerBuffer.putLong(ptsAndFlags);
headerBuffer.putInt(packetSize);
headerBuffer.flip();
IO.writeFully(fd, headerBuffer);
}
private static void fixOpusConfigPacket(ByteBuffer buffer) throws IOException {
// Here is an example of the config packet received for an OPUS stream:
//
// 00000000 41 4f 50 55 53 48 44 52 13 00 00 00 00 00 00 00 |AOPUSHDR........|
// -------------- BELOW IS THE PART WE MUST PUT AS EXTRADATA -------------------
// 00000010 4f 70 75 73 48 65 61 64 01 01 38 01 80 bb 00 00 |OpusHead..8.....|
// 00000020 00 00 00 |... |
// ------------------------------------------------------------------------------
// 00000020 41 4f 50 55 53 44 4c 59 08 00 00 00 00 | AOPUSDLY.....|
// 00000030 00 00 00 a0 2e 63 00 00 00 00 00 41 4f 50 55 53 |.....c.....AOPUS|
// 00000040 50 52 4c 08 00 00 00 00 00 00 00 00 b4 c4 04 00 |PRL.............|
// 00000050 00 00 00 |...|
//
// Each "section" is prefixed by a 64-bit ID and a 64-bit length.
//
// <https://developer.android.com/reference/android/media/MediaCodec#CSD>
if (buffer.remaining() < 16) {
throw new IOException("Not enough data in OPUS config packet");
}
final byte[] opusHeaderId = {'A', 'O', 'P', 'U', 'S', 'H', 'D', 'R'};
byte[] idBuffer = new byte[8];
buffer.get(idBuffer);
if (!Arrays.equals(idBuffer, opusHeaderId)) {
throw new IOException("OPUS header not found");
}
// The size is in native byte-order
long sizeLong = buffer.getLong();
if (sizeLong < 0 || sizeLong >= 0x7FFFFFFF) {
throw new IOException("Invalid block size in OPUS header: " + sizeLong);
}
int size = (int) sizeLong;
if (buffer.remaining() < size) {
throw new IOException("Not enough data in OPUS header (invalid size: " + size + ")");
}
// Set the buffer to point to the OPUS header slice
buffer.limit(buffer.position() + size);
}
private static void fixFlacConfigPacket(ByteBuffer buffer) throws IOException {
// 00000000 66 4c 61 43 00 00 00 22 |fLaC..." |
// -------------- BELOW IS THE PART WE MUST PUT AS EXTRADATA -------------------
// 00000000 10 00 10 00 00 00 00 00 | ........|
// 00000010 00 00 0b b8 02 f0 00 00 00 00 00 00 00 00 00 00 |................|
// 00000020 00 00 00 00 00 00 00 00 00 00 |.......... |
// ------------------------------------------------------------------------------
// 00000020 84 00 00 28 20 00 | ...( .|
// 00000030 00 00 72 65 66 65 72 65 6e 63 65 20 6c 69 62 46 |..reference libF|
// 00000040 4c 41 43 20 31 2e 33 2e 32 20 32 30 32 32 31 30 |LAC 1.3.2 202210|
// 00000050 32 32 00 00 00 00 |22....|
//
// <https://developer.android.com/reference/android/media/MediaCodec#CSD>
if (buffer.remaining() < 8) {
throw new IOException("Not enough data in FLAC config packet");
}
final byte[] flacHeaderId = {'f', 'L', 'a', 'C'};
byte[] idBuffer = new byte[4];
buffer.get(idBuffer);
if (!Arrays.equals(idBuffer, flacHeaderId)) {
throw new IOException("FLAC header not found");
}
// The size<SUF>
buffer.order(ByteOrder.BIG_ENDIAN);
int size = buffer.getInt();
if (buffer.remaining() < size) {
throw new IOException("Not enough data in FLAC header (invalid size: " + size + ")");
}
// Set the buffer to point to the FLAC header slice
buffer.limit(buffer.position() + size);
}
}
|
114410_5 | /*
* Copyright (c) 2012-2013, Dienst Landelijk Gebied - Ministerie van Economische Zaken
*
* Gepubliceerd onder de BSD 2-clause licentie,
* zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie.
*/
package nl.mineleni.cbsviewer.util;
import java.io.File;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import nl.mineleni.cbsviewer.util.xml.LayerDescriptor;
import nl.mineleni.cbsviewer.util.xml.LayersList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import flexjson.JSONSerializer;
import flexjson.transformer.AbstractTransformer;
/**
* AvailableLayersBean maakt de beschikbare kaarten bekend in de applicatie op
* basis van het xml configuratie bestand {@code AvailableLayers.xml}.
*
* @author mprins
* @since 1.6
*
* @composed 1 - 1..* LayerDescriptor
* @depend - layersList - LayersList
*/
public class AvailableLayersBean {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
.getLogger(AvailableLayersBean.class);
/**
* lijst met beschikbare layers.
*/
private List<LayerDescriptor> layers = null;
/**
* default constructor.
*/
public AvailableLayersBean() {
try {
final JAXBContext jc = JAXBContext
.newInstance("nl.mineleni.cbsviewer.util.xml");
final Unmarshaller u = jc.createUnmarshaller();
final URL r = this.getClass().getClassLoader()
.getResource("AvailableLayers.xml");
if (r != null) {
final File f = new File(r.getFile());
@SuppressWarnings("unchecked")
final JAXBElement<LayersList> element = (JAXBElement<LayersList>) u
.unmarshal(f);
final LayersList layerslist = element.getValue();
this.layers = layerslist.getLayerdescriptor();
} else {
throw new JAXBException(
"Bestand 'AvailableLayers.xml' niet gevonden");
}
} catch (final JAXBException e) {
LOGGER.error(
"Er is een fout opgetreden bij het inlezen van de layers.",
e);
}
}
/**
* accessor voor de lijst met layers.
*
* @return geeft de lijst van LayerDescriptors voor de applicatie
*/
public List<LayerDescriptor> getLayers() {
return Collections.unmodifiableList(this.layers);
}
/**
* Geeft de kaarten als javascript variabele.
*
* @return layers als json object
* @see #asJSON(boolean)
*/
public String asJSON() {
return this.asJSON(true);
}
/**
* Geeft de kaarten als json object ({@code asVar == false}) of javascript
* variabele, ingepakt in een CDATA sectie. Het object is een array met
* LayerDescriptors. Null waarden worden niet geserialiseerd, hierdoor zijn
* objecten niet round-trip serialiseerbaar (dus equals() niet bruikbaar).
*
* @param asVar
* {@code true} als er een javascript variabele moet worden
* gegeven.
* @return layers als json
*
* @see #asJSON()
*/
public String asJSON(final boolean asVar) {
final JSONSerializer serializer = new JSONSerializer();
final String json = serializer.transform(new AbstractTransformer() {
@Override
public Boolean isInline() {
return true;
}
@Override
public void transform(final Object object) {
// null objecten niet serializeren.
return;
}
}, void.class).exclude("class", "aliases", "attributes")
.prettyPrint(LOGGER.isDebugEnabled()).serialize(this.layers);
if (asVar) {
return "\n/* <![CDATA[ */ var _layers=" + json + ";/* ]]> */";
}
return json;
}
/**
* geeft de eerste layerdescriptor met de gevraagde id.
*
* @param id
* de ID van de laag
* @return the layer by id
* @see LayerDescriptor#getId()
*/
public LayerDescriptor getLayerByID(final String id) {
for (final LayerDescriptor desc : this.layers) {
if (desc.getId().equalsIgnoreCase(id)) {
return desc;
}
}
return null;
}
/**
* geeft de eerste layerdescriptor met de gevraagde naam.
*
* @param queryLyrName
* de naam van de wms laag
* @param lyrUrl
* de url van de wms
*
* @return the layer by name and url
* @see LayerDescriptor#getLayers()
*/
public LayerDescriptor getLayerByLayers(final String queryLyrName,
final String lyrUrl) {
for (final LayerDescriptor desc : this.layers) {
if ((desc.getLayers().replaceAll("\\s", ""))
.equalsIgnoreCase(queryLyrName.replaceAll("\\s", ""))) {
if (desc.getUrl().equalsIgnoreCase(lyrUrl)) {
LOGGER.debug("Gevonden layer-id is: " + desc.getId());
return desc;
}
}
}
return null;
}
/**
* geeft de eerste layerdescriptor met de gevraagde naam, url en styles.
*
* @param queryLyrName
* de naam van de wms laag
* @param lyrUrl
* de url van de wms
* @param styles
* wms styles
*
* @return the layer by name and url
* @see LayerDescriptor#getLayers()
*/
public LayerDescriptor getLayerByLayers(final String queryLyrName,
final String lyrUrl, final String styles) {
for (final LayerDescriptor desc : this.layers) {
if ((desc.getLayers().replaceAll("\\s", ""))
.equalsIgnoreCase(queryLyrName.replaceAll("\\s", ""))) {
if (desc.getUrl().equalsIgnoreCase(lyrUrl)) {
if (desc.getStyles().replaceAll("\\s", "")
.equalsIgnoreCase(styles)) {
LOGGER.debug("Gevonden layer-id is: " + desc.getId());
return desc;
}
}
}
}
return null;
}
/**
* geeft de eerste layerdescriptor met de gevraagde naam.
*
* @param name
* de naam van de laag
* @return the layer by name
* @see LayerDescriptor#getName()
*/
public LayerDescriptor getLayerByName(final String name) {
for (final LayerDescriptor desc : this.layers) {
if (desc.getName().equalsIgnoreCase(name)) {
LOGGER.debug("Gevonden layer-id is: " + desc.getId());
return desc;
}
}
return null;
}
}
| GeoDienstenCentrum/CBSviewer | src/main/java/nl/mineleni/cbsviewer/util/AvailableLayersBean.java | 2,057 | /**
* accessor voor de lijst met layers.
*
* @return geeft de lijst van LayerDescriptors voor de applicatie
*/ | block_comment | nl | /*
* Copyright (c) 2012-2013, Dienst Landelijk Gebied - Ministerie van Economische Zaken
*
* Gepubliceerd onder de BSD 2-clause licentie,
* zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie.
*/
package nl.mineleni.cbsviewer.util;
import java.io.File;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import nl.mineleni.cbsviewer.util.xml.LayerDescriptor;
import nl.mineleni.cbsviewer.util.xml.LayersList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import flexjson.JSONSerializer;
import flexjson.transformer.AbstractTransformer;
/**
* AvailableLayersBean maakt de beschikbare kaarten bekend in de applicatie op
* basis van het xml configuratie bestand {@code AvailableLayers.xml}.
*
* @author mprins
* @since 1.6
*
* @composed 1 - 1..* LayerDescriptor
* @depend - layersList - LayersList
*/
public class AvailableLayersBean {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
.getLogger(AvailableLayersBean.class);
/**
* lijst met beschikbare layers.
*/
private List<LayerDescriptor> layers = null;
/**
* default constructor.
*/
public AvailableLayersBean() {
try {
final JAXBContext jc = JAXBContext
.newInstance("nl.mineleni.cbsviewer.util.xml");
final Unmarshaller u = jc.createUnmarshaller();
final URL r = this.getClass().getClassLoader()
.getResource("AvailableLayers.xml");
if (r != null) {
final File f = new File(r.getFile());
@SuppressWarnings("unchecked")
final JAXBElement<LayersList> element = (JAXBElement<LayersList>) u
.unmarshal(f);
final LayersList layerslist = element.getValue();
this.layers = layerslist.getLayerdescriptor();
} else {
throw new JAXBException(
"Bestand 'AvailableLayers.xml' niet gevonden");
}
} catch (final JAXBException e) {
LOGGER.error(
"Er is een fout opgetreden bij het inlezen van de layers.",
e);
}
}
/**
* accessor voor de<SUF>*/
public List<LayerDescriptor> getLayers() {
return Collections.unmodifiableList(this.layers);
}
/**
* Geeft de kaarten als javascript variabele.
*
* @return layers als json object
* @see #asJSON(boolean)
*/
public String asJSON() {
return this.asJSON(true);
}
/**
* Geeft de kaarten als json object ({@code asVar == false}) of javascript
* variabele, ingepakt in een CDATA sectie. Het object is een array met
* LayerDescriptors. Null waarden worden niet geserialiseerd, hierdoor zijn
* objecten niet round-trip serialiseerbaar (dus equals() niet bruikbaar).
*
* @param asVar
* {@code true} als er een javascript variabele moet worden
* gegeven.
* @return layers als json
*
* @see #asJSON()
*/
public String asJSON(final boolean asVar) {
final JSONSerializer serializer = new JSONSerializer();
final String json = serializer.transform(new AbstractTransformer() {
@Override
public Boolean isInline() {
return true;
}
@Override
public void transform(final Object object) {
// null objecten niet serializeren.
return;
}
}, void.class).exclude("class", "aliases", "attributes")
.prettyPrint(LOGGER.isDebugEnabled()).serialize(this.layers);
if (asVar) {
return "\n/* <![CDATA[ */ var _layers=" + json + ";/* ]]> */";
}
return json;
}
/**
* geeft de eerste layerdescriptor met de gevraagde id.
*
* @param id
* de ID van de laag
* @return the layer by id
* @see LayerDescriptor#getId()
*/
public LayerDescriptor getLayerByID(final String id) {
for (final LayerDescriptor desc : this.layers) {
if (desc.getId().equalsIgnoreCase(id)) {
return desc;
}
}
return null;
}
/**
* geeft de eerste layerdescriptor met de gevraagde naam.
*
* @param queryLyrName
* de naam van de wms laag
* @param lyrUrl
* de url van de wms
*
* @return the layer by name and url
* @see LayerDescriptor#getLayers()
*/
public LayerDescriptor getLayerByLayers(final String queryLyrName,
final String lyrUrl) {
for (final LayerDescriptor desc : this.layers) {
if ((desc.getLayers().replaceAll("\\s", ""))
.equalsIgnoreCase(queryLyrName.replaceAll("\\s", ""))) {
if (desc.getUrl().equalsIgnoreCase(lyrUrl)) {
LOGGER.debug("Gevonden layer-id is: " + desc.getId());
return desc;
}
}
}
return null;
}
/**
* geeft de eerste layerdescriptor met de gevraagde naam, url en styles.
*
* @param queryLyrName
* de naam van de wms laag
* @param lyrUrl
* de url van de wms
* @param styles
* wms styles
*
* @return the layer by name and url
* @see LayerDescriptor#getLayers()
*/
public LayerDescriptor getLayerByLayers(final String queryLyrName,
final String lyrUrl, final String styles) {
for (final LayerDescriptor desc : this.layers) {
if ((desc.getLayers().replaceAll("\\s", ""))
.equalsIgnoreCase(queryLyrName.replaceAll("\\s", ""))) {
if (desc.getUrl().equalsIgnoreCase(lyrUrl)) {
if (desc.getStyles().replaceAll("\\s", "")
.equalsIgnoreCase(styles)) {
LOGGER.debug("Gevonden layer-id is: " + desc.getId());
return desc;
}
}
}
}
return null;
}
/**
* geeft de eerste layerdescriptor met de gevraagde naam.
*
* @param name
* de naam van de laag
* @return the layer by name
* @see LayerDescriptor#getName()
*/
public LayerDescriptor getLayerByName(final String name) {
for (final LayerDescriptor desc : this.layers) {
if (desc.getName().equalsIgnoreCase(name)) {
LOGGER.debug("Gevonden layer-id is: " + desc.getId());
return desc;
}
}
return null;
}
}
|
129986_1 | package com.example.steven.joetzandroid.Activities;
import android.support.v4.app.Fragment;
import com.example.steven.joetzandroid.Domain.Vakantie;
/**
* Created by Steven on 3/12/14.
*/
//Overerven verplicht voor alle fragmenten die de details van een vakantie weergeven
public abstract class VakantieDetailFragment extends Fragment {
protected Vakantie vakantie;
private static String aTag;
public void setVakantie(Vakantie vakantie){
this.vakantie = vakantie;
}
public String getaTag()
{
return aTag;
}
public void setaTag(String tag)
{
aTag = tag;
}
}
| Geoffry304/MobileOne | JoetzAndroid2/app/src/main/java/com/example/steven/joetzandroid/Activities/VakantieDetailFragment.java | 206 | //Overerven verplicht voor alle fragmenten die de details van een vakantie weergeven | line_comment | nl | package com.example.steven.joetzandroid.Activities;
import android.support.v4.app.Fragment;
import com.example.steven.joetzandroid.Domain.Vakantie;
/**
* Created by Steven on 3/12/14.
*/
//Overerven verplicht<SUF>
public abstract class VakantieDetailFragment extends Fragment {
protected Vakantie vakantie;
private static String aTag;
public void setVakantie(Vakantie vakantie){
this.vakantie = vakantie;
}
public String getaTag()
{
return aTag;
}
public void setaTag(String tag)
{
aTag = tag;
}
}
|
49834_4 | /*
* Geotoolkit.org - An Open Source Java GIS Toolkit
* http://www.geotoolkit.org
*
* (C) 2014, Geomatys
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotoolkit.processing.coverage.shadedrelief;
import org.apache.sis.coverage.grid.GridCoverage;
import org.apache.sis.parameter.ParameterBuilder;
import org.geotoolkit.processing.AbstractProcessDescriptor;
import org.geotoolkit.process.Process;
import org.geotoolkit.process.ProcessDescriptor;
import org.geotoolkit.processing.GeotkProcessingRegistry;
import org.geotoolkit.processing.ProcessBundle;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.operation.MathTransform1D;
import org.opengis.util.InternationalString;
/**
*
* @author Johann Sorel (Geomatys)
*/
public class ShadedReliefDescriptor extends AbstractProcessDescriptor {
public static final String NAME = "coverage:shadedrelief";
public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract);
/*
* Coverage base image
*/
public static final String IN_COVERAGE_PARAM_NAME = "inCoverage";
public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage);
public static final ParameterDescriptor<GridCoverage> COVERAGE = new ParameterBuilder()
.addName(IN_COVERAGE_PARAM_NAME)
.setRemarks(IN_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation
*/
public static final String IN_ELEVATION_PARAM_NAME = "inElevation";
public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<GridCoverage> ELEVATION = new ParameterBuilder()
.addName(IN_ELEVATION_PARAM_NAME)
.setRemarks(IN_ELEVATION_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation value to meters
*/
public static final String IN_ELECONV_PARAM_NAME = "inEleEnv";
public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder()
.addName(IN_ELECONV_PARAM_NAME)
.setRemarks(IN_ELECONV_PARAM_REMARKS)
.setRequired(true)
.create(MathTransform1D.class, null);
/**Input parameters */
public static final ParameterDescriptorGroup INPUT_DESC =
new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV);
/*
* Coverage result
*/
public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage";
public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage);
public static final ParameterDescriptor<GridCoverage> OUTCOVERAGE = new ParameterBuilder()
.addName(OUT_COVERAGE_PARAM_NAME)
.setRemarks(OUT_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/**Output parameters */
public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE);
public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor();
private ShadedReliefDescriptor() {
super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC);
}
@Override
public Process createProcess(final ParameterValueGroup input) {
return new ShadedRelief(INSTANCE, input);
}
}
| Geomatys/geotoolkit | geotk-processing/src/main/java/org/geotoolkit/processing/coverage/shadedrelief/ShadedReliefDescriptor.java | 1,309 | /*
* Coverage elevation value to meters
*/ | block_comment | nl | /*
* Geotoolkit.org - An Open Source Java GIS Toolkit
* http://www.geotoolkit.org
*
* (C) 2014, Geomatys
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotoolkit.processing.coverage.shadedrelief;
import org.apache.sis.coverage.grid.GridCoverage;
import org.apache.sis.parameter.ParameterBuilder;
import org.geotoolkit.processing.AbstractProcessDescriptor;
import org.geotoolkit.process.Process;
import org.geotoolkit.process.ProcessDescriptor;
import org.geotoolkit.processing.GeotkProcessingRegistry;
import org.geotoolkit.processing.ProcessBundle;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.operation.MathTransform1D;
import org.opengis.util.InternationalString;
/**
*
* @author Johann Sorel (Geomatys)
*/
public class ShadedReliefDescriptor extends AbstractProcessDescriptor {
public static final String NAME = "coverage:shadedrelief";
public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract);
/*
* Coverage base image
*/
public static final String IN_COVERAGE_PARAM_NAME = "inCoverage";
public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage);
public static final ParameterDescriptor<GridCoverage> COVERAGE = new ParameterBuilder()
.addName(IN_COVERAGE_PARAM_NAME)
.setRemarks(IN_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation
*/
public static final String IN_ELEVATION_PARAM_NAME = "inElevation";
public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<GridCoverage> ELEVATION = new ParameterBuilder()
.addName(IN_ELEVATION_PARAM_NAME)
.setRemarks(IN_ELEVATION_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation value<SUF>*/
public static final String IN_ELECONV_PARAM_NAME = "inEleEnv";
public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder()
.addName(IN_ELECONV_PARAM_NAME)
.setRemarks(IN_ELECONV_PARAM_REMARKS)
.setRequired(true)
.create(MathTransform1D.class, null);
/**Input parameters */
public static final ParameterDescriptorGroup INPUT_DESC =
new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV);
/*
* Coverage result
*/
public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage";
public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage);
public static final ParameterDescriptor<GridCoverage> OUTCOVERAGE = new ParameterBuilder()
.addName(OUT_COVERAGE_PARAM_NAME)
.setRemarks(OUT_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/**Output parameters */
public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE);
public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor();
private ShadedReliefDescriptor() {
super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC);
}
@Override
public Process createProcess(final ParameterValueGroup input) {
return new ShadedRelief(INSTANCE, input);
}
}
|
202128_0 | package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame die een gegeven uitslag observeert. */
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
| GerjanWielink/software-systems | ss/src/main/java/ss/week6/voteMachine/gui/ResultJFrame.java | 415 | /**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/ | block_comment | nl | package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
* P2 prac wk3.<SUF>*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame die een gegeven uitslag observeert. */
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
|