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
26253_2
package whitetea.magicmatrix.model; import java.awt.Color; import java.awt.image.BufferedImage; /** * * @author WhiteTea * */ public class Frame implements Cloneable { //TODO overal met x y & width heigthwerken ipv rowNr & colNr private final int rows, cols; private Color[][] colors; public Frame(int rows, int cols) { if(rows <= 0) throw new IllegalArgumentException("The number of rows must be strictly positive."); if(cols <= 0) throw new IllegalArgumentException("The number of columns must be strictly positive."); this.rows = rows; this.cols = cols; colors = new Color[rows][cols]; fill(new Color(0, 0, 0)); } public Frame(Frame frame) { this.rows = frame.getNbOfRows(); this.cols = frame.getNbOfColumns(); colors = new Color[rows][cols]; for (int y = 0; y < this.rows; y++) for (int x = 0; x < this.cols; x++) setPixelColor(y, x, frame.getPixelColor(y, x)); } public int getNbOfRows() { return rows; } public int getNbOfColumns() { return cols; } public boolean isValidRowNr(int rowNr) { return rowNr >= 0 && rowNr < rows; } public boolean isValidColNr(int colNr) { return colNr >= 0 && colNr < cols; } public void setPixelColor(int rowNr, int colNr, Color c) { if (!isValidRowNr(rowNr) || !isValidColNr(colNr)) throw new IllegalArgumentException( "The given indices are not valid for this matrix size." + "\nMatrix size: " + rows + "x" + cols + "\nGiven indices: " + rowNr + ", " + colNr); colors[rowNr][colNr] = c; } public Color getPixelColor(int rowNr, int colNr) { if (!isValidRowNr(rowNr) || !isValidColNr(colNr)) throw new IllegalArgumentException( "The given indices are not valid for this matrix size." + "\nMatrix size: " + rows + "x" + cols + "\nGiven indices: " + rowNr + ", " + colNr); return colors[rowNr][colNr]; } public void fill(Color c) { for (int i = 0; i < rows; i++) { fillRow(i, c); } } public void fillRow(int rowNr, Color c) { if (!isValidRowNr(rowNr)) throw new IllegalArgumentException("Invalid row number: " + rowNr + ". Matrix size is: " + rows + "x" + cols); for (int i = 0; i < cols; i++) setPixelColor(rowNr, i, c); } public void fillColumn(int colNr, Color c) { if (!isValidColNr(colNr)) throw new IllegalArgumentException("Invalid column number: " + colNr + ". Matrix size is: " + rows + "x" + cols); for (int i = 0; i < rows; i++) setPixelColor(i, colNr, c); } //TODO laatste rij kleuren van eerste rij met boolean //TODO strategy met color voor laatste rij public void shiftLeft() { for (int x = 0; x < this.cols; x++) for (int y = 0; y < this.rows; y++) setPixelColor(y, x, (x < this.cols - 1) ? getPixelColor(y, x+1) : new Color(0,0,0)); } public void shiftRight() { for (int y = 0; y < this.rows; y++) { for (int x = this.cols - 1; x >= 0; x--) { setPixelColor(y, x, (x > 0) ? getPixelColor(y,x - 1) : new Color(0,0,0)); } } } public void shiftUp() { for (int y = 0; y < this.rows; y++) { for (int x = 0; x < this.cols; x++) { setPixelColor(y, x, (y < this.rows - 1) ? getPixelColor(y + 1, x) : new Color(0,0,0)); } } } public void shiftDown() { for (int y = this.rows - 1; y >= 0; y--) { for (int x = 0; x < this.cols; x++) { setPixelColor(y, x, (y > 0) ? getPixelColor(y - 1, x) : new Color(0,0,0)); } } } public BufferedImage getImage() { BufferedImage bufferedImage = new BufferedImage(colors[0].length, colors.length, BufferedImage.TYPE_INT_RGB); // Set each pixel of the BufferedImage to the color from the Color[][]. for (int x = 0; x < getNbOfColumns(); x++) for (int y = 0; y < getNbOfRows(); y++) bufferedImage.setRGB(x, y, colors[y][x].getRGB()); return bufferedImage; } @Override public Frame clone() { return new Frame(this); } }
wietsebuseyne/MagicMatrix
MagicMatrix/src/whitetea/magicmatrix/model/Frame.java
1,549
//TODO laatste rij kleuren van eerste rij met boolean
line_comment
nl
package whitetea.magicmatrix.model; import java.awt.Color; import java.awt.image.BufferedImage; /** * * @author WhiteTea * */ public class Frame implements Cloneable { //TODO overal met x y & width heigthwerken ipv rowNr & colNr private final int rows, cols; private Color[][] colors; public Frame(int rows, int cols) { if(rows <= 0) throw new IllegalArgumentException("The number of rows must be strictly positive."); if(cols <= 0) throw new IllegalArgumentException("The number of columns must be strictly positive."); this.rows = rows; this.cols = cols; colors = new Color[rows][cols]; fill(new Color(0, 0, 0)); } public Frame(Frame frame) { this.rows = frame.getNbOfRows(); this.cols = frame.getNbOfColumns(); colors = new Color[rows][cols]; for (int y = 0; y < this.rows; y++) for (int x = 0; x < this.cols; x++) setPixelColor(y, x, frame.getPixelColor(y, x)); } public int getNbOfRows() { return rows; } public int getNbOfColumns() { return cols; } public boolean isValidRowNr(int rowNr) { return rowNr >= 0 && rowNr < rows; } public boolean isValidColNr(int colNr) { return colNr >= 0 && colNr < cols; } public void setPixelColor(int rowNr, int colNr, Color c) { if (!isValidRowNr(rowNr) || !isValidColNr(colNr)) throw new IllegalArgumentException( "The given indices are not valid for this matrix size." + "\nMatrix size: " + rows + "x" + cols + "\nGiven indices: " + rowNr + ", " + colNr); colors[rowNr][colNr] = c; } public Color getPixelColor(int rowNr, int colNr) { if (!isValidRowNr(rowNr) || !isValidColNr(colNr)) throw new IllegalArgumentException( "The given indices are not valid for this matrix size." + "\nMatrix size: " + rows + "x" + cols + "\nGiven indices: " + rowNr + ", " + colNr); return colors[rowNr][colNr]; } public void fill(Color c) { for (int i = 0; i < rows; i++) { fillRow(i, c); } } public void fillRow(int rowNr, Color c) { if (!isValidRowNr(rowNr)) throw new IllegalArgumentException("Invalid row number: " + rowNr + ". Matrix size is: " + rows + "x" + cols); for (int i = 0; i < cols; i++) setPixelColor(rowNr, i, c); } public void fillColumn(int colNr, Color c) { if (!isValidColNr(colNr)) throw new IllegalArgumentException("Invalid column number: " + colNr + ". Matrix size is: " + rows + "x" + cols); for (int i = 0; i < rows; i++) setPixelColor(i, colNr, c); } //TODO laatste<SUF> //TODO strategy met color voor laatste rij public void shiftLeft() { for (int x = 0; x < this.cols; x++) for (int y = 0; y < this.rows; y++) setPixelColor(y, x, (x < this.cols - 1) ? getPixelColor(y, x+1) : new Color(0,0,0)); } public void shiftRight() { for (int y = 0; y < this.rows; y++) { for (int x = this.cols - 1; x >= 0; x--) { setPixelColor(y, x, (x > 0) ? getPixelColor(y,x - 1) : new Color(0,0,0)); } } } public void shiftUp() { for (int y = 0; y < this.rows; y++) { for (int x = 0; x < this.cols; x++) { setPixelColor(y, x, (y < this.rows - 1) ? getPixelColor(y + 1, x) : new Color(0,0,0)); } } } public void shiftDown() { for (int y = this.rows - 1; y >= 0; y--) { for (int x = 0; x < this.cols; x++) { setPixelColor(y, x, (y > 0) ? getPixelColor(y - 1, x) : new Color(0,0,0)); } } } public BufferedImage getImage() { BufferedImage bufferedImage = new BufferedImage(colors[0].length, colors.length, BufferedImage.TYPE_INT_RGB); // Set each pixel of the BufferedImage to the color from the Color[][]. for (int x = 0; x < getNbOfColumns(); x++) for (int y = 0; y < getNbOfRows(); y++) bufferedImage.setRGB(x, y, colors[y][x].getRGB()); return bufferedImage; } @Override public Frame clone() { return new Frame(this); } }
73612_9
package eu.wietsevenema.lang.oberon.ast.visitors.interpreter; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import xtc.tree.Visitor; import eu.wietsevenema.lang.oberon.ast.expressions.Expression; import eu.wietsevenema.lang.oberon.ast.expressions.Identifier; import eu.wietsevenema.lang.oberon.ast.expressions.ProcedureUndefinedException; import eu.wietsevenema.lang.oberon.ast.statements.AssignmentStatement; import eu.wietsevenema.lang.oberon.ast.statements.ElseIfStatement; import eu.wietsevenema.lang.oberon.ast.statements.IfStatement; import eu.wietsevenema.lang.oberon.ast.statements.ProcedureCallStatement; import eu.wietsevenema.lang.oberon.ast.statements.Statement; import eu.wietsevenema.lang.oberon.ast.statements.WhileStatement; import eu.wietsevenema.lang.oberon.ast.statements.WithStatement; import eu.wietsevenema.lang.oberon.exceptions.IdentifierExpectedInParamList; import eu.wietsevenema.lang.oberon.exceptions.ImmutableException; import eu.wietsevenema.lang.oberon.exceptions.SymbolAlreadyDeclaredException; import eu.wietsevenema.lang.oberon.exceptions.SymbolNotDeclaredException; import eu.wietsevenema.lang.oberon.exceptions.TypeMismatchException; import eu.wietsevenema.lang.oberon.exceptions.ValueUndefinedException; import eu.wietsevenema.lang.oberon.exceptions.WrongNumberOfArgsException; import eu.wietsevenema.lang.oberon.interpreter.Formal; import eu.wietsevenema.lang.oberon.interpreter.Procedure; import eu.wietsevenema.lang.oberon.interpreter.InterpreterScope; import eu.wietsevenema.lang.oberon.interpreter.ValueReference; import eu.wietsevenema.lang.oberon.interpreter.values.BooleanValue; import eu.wietsevenema.lang.oberon.interpreter.values.RecordValue; import eu.wietsevenema.lang.oberon.interpreter.values.Value; public class StatementEvaluator extends Visitor { InterpreterScope scope; public StatementEvaluator(InterpreterScope scope) { this.scope = scope; } public void visit(AssignmentStatement assign) throws SymbolNotDeclaredException, TypeMismatchException, ImmutableException { // 1. Retrieve existing reference. ValueReferenceResolver resolv = new ValueReferenceResolver(scope); ValueReference currentValRef = (ValueReference) resolv.dispatch(assign.getIdentifier()); if (currentValRef == null) { throw new SymbolNotDeclaredException("Variable not declared. " + assign.getLocation().toString()); } // 2. Evaluate expression ExpressionEvaluator eval = new ExpressionEvaluator(scope); Value value = (Value) eval.dispatch(assign.getExpression()); // 3. Assign new value currentValRef.setValue(value); } public void visit(ProcedureCallStatement pCall) throws WrongNumberOfArgsException, IdentifierExpectedInParamList, SymbolAlreadyDeclaredException, SymbolNotDeclaredException, TypeMismatchException, ProcedureUndefinedException, ValueUndefinedException, ImmutableException { // Find procedure node. Procedure procedure = (Procedure) scope.lookupProc(pCall.getIdentifier().getName()); if (procedure == null) { throw new ProcedureUndefinedException("Procedure " + pCall.getIdentifier().getName() + " undefined."); } // Enter scope. scope = new InterpreterScope(scope); List<Expression> parameters = pCall.getParameters(); List<Formal> formals = procedure.getFormals(); if (formals.size() != parameters.size()) { throw new WrongNumberOfArgsException(); } for (int i = 0; i < formals.size(); i++) { Formal formal = formals.get(i); formal.assignParameter(scope, parameters.get(i)); } procedure.execute(scope); //Exit scope scope = scope.getParent(); } public void visit( WithStatement withStatement) throws SymbolAlreadyDeclaredException{ ExpressionEvaluator exprEval = new ExpressionEvaluator(scope); RecordValue record = (RecordValue) exprEval.dispatch(withStatement.getRecord()); //Enter new scope and expose members of record. scope = new InterpreterScope(scope); for( Entry<Identifier, ValueReference> entry : record.entrySet() ){ Identifier id = entry.getKey(); ValueReference reference = entry.getValue(); String symbol = id.getName(); scope.declareValueReference(symbol, reference); } //Execute all statements StatementEvaluator statEval = new StatementEvaluator(scope); for(Statement stat: withStatement.getStatements()){ statEval.dispatch(stat); } //Exit scope scope = scope.getParent(); } public void visit(IfStatement ifStatement) throws TypeMismatchException, ValueUndefinedException { if (evalCondition(ifStatement.getCondition())) { // 1. Als de if matched, evalueren we die statement en stoppen de // evaluatie. visitStatements(ifStatement.getTrueStatements()); return; } else { for (Iterator<ElseIfStatement> iterator = ifStatement.getElseIfs().iterator(); iterator.hasNext();) { ElseIfStatement elseif = (ElseIfStatement) iterator.next(); if (evalCondition(elseif.getCondition())) { // 2. Zodra er een elseif is gematched en uitgevoerd stopt // de evaluatie. visitStatements(elseif.getTrueStatements()); return; } } // 3. Finally, als zowel het if statement en de elseif's falen te // matchen, voeren we de else uit. visitStatements(ifStatement.getFalseStatements()); return; } } private void visitStatements(List<Statement> statements) { if (!statements.isEmpty()) { StatementEvaluator statEval = new StatementEvaluator(scope); for (Statement stat : statements) { statEval.dispatch(stat); } } } private boolean evalCondition(Expression exp) throws TypeMismatchException, ValueUndefinedException { ExpressionEvaluator expEval = new ExpressionEvaluator(scope); BooleanValue result = (BooleanValue) expEval.dispatch(exp); return result.getValue(); } public void visit(WhileStatement whilestat) throws TypeMismatchException, ValueUndefinedException { StatementEvaluator statEval = new StatementEvaluator(scope); while (evalCondition(whilestat.getCondition())) { for (Statement s : whilestat.getStatements()) { statEval.dispatch(s); } } } }
wietsevenema/Oberon-0-interpreter
src/eu/wietsevenema/lang/oberon/ast/visitors/interpreter/StatementEvaluator.java
1,893
// matchen, voeren we de else uit.
line_comment
nl
package eu.wietsevenema.lang.oberon.ast.visitors.interpreter; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import xtc.tree.Visitor; import eu.wietsevenema.lang.oberon.ast.expressions.Expression; import eu.wietsevenema.lang.oberon.ast.expressions.Identifier; import eu.wietsevenema.lang.oberon.ast.expressions.ProcedureUndefinedException; import eu.wietsevenema.lang.oberon.ast.statements.AssignmentStatement; import eu.wietsevenema.lang.oberon.ast.statements.ElseIfStatement; import eu.wietsevenema.lang.oberon.ast.statements.IfStatement; import eu.wietsevenema.lang.oberon.ast.statements.ProcedureCallStatement; import eu.wietsevenema.lang.oberon.ast.statements.Statement; import eu.wietsevenema.lang.oberon.ast.statements.WhileStatement; import eu.wietsevenema.lang.oberon.ast.statements.WithStatement; import eu.wietsevenema.lang.oberon.exceptions.IdentifierExpectedInParamList; import eu.wietsevenema.lang.oberon.exceptions.ImmutableException; import eu.wietsevenema.lang.oberon.exceptions.SymbolAlreadyDeclaredException; import eu.wietsevenema.lang.oberon.exceptions.SymbolNotDeclaredException; import eu.wietsevenema.lang.oberon.exceptions.TypeMismatchException; import eu.wietsevenema.lang.oberon.exceptions.ValueUndefinedException; import eu.wietsevenema.lang.oberon.exceptions.WrongNumberOfArgsException; import eu.wietsevenema.lang.oberon.interpreter.Formal; import eu.wietsevenema.lang.oberon.interpreter.Procedure; import eu.wietsevenema.lang.oberon.interpreter.InterpreterScope; import eu.wietsevenema.lang.oberon.interpreter.ValueReference; import eu.wietsevenema.lang.oberon.interpreter.values.BooleanValue; import eu.wietsevenema.lang.oberon.interpreter.values.RecordValue; import eu.wietsevenema.lang.oberon.interpreter.values.Value; public class StatementEvaluator extends Visitor { InterpreterScope scope; public StatementEvaluator(InterpreterScope scope) { this.scope = scope; } public void visit(AssignmentStatement assign) throws SymbolNotDeclaredException, TypeMismatchException, ImmutableException { // 1. Retrieve existing reference. ValueReferenceResolver resolv = new ValueReferenceResolver(scope); ValueReference currentValRef = (ValueReference) resolv.dispatch(assign.getIdentifier()); if (currentValRef == null) { throw new SymbolNotDeclaredException("Variable not declared. " + assign.getLocation().toString()); } // 2. Evaluate expression ExpressionEvaluator eval = new ExpressionEvaluator(scope); Value value = (Value) eval.dispatch(assign.getExpression()); // 3. Assign new value currentValRef.setValue(value); } public void visit(ProcedureCallStatement pCall) throws WrongNumberOfArgsException, IdentifierExpectedInParamList, SymbolAlreadyDeclaredException, SymbolNotDeclaredException, TypeMismatchException, ProcedureUndefinedException, ValueUndefinedException, ImmutableException { // Find procedure node. Procedure procedure = (Procedure) scope.lookupProc(pCall.getIdentifier().getName()); if (procedure == null) { throw new ProcedureUndefinedException("Procedure " + pCall.getIdentifier().getName() + " undefined."); } // Enter scope. scope = new InterpreterScope(scope); List<Expression> parameters = pCall.getParameters(); List<Formal> formals = procedure.getFormals(); if (formals.size() != parameters.size()) { throw new WrongNumberOfArgsException(); } for (int i = 0; i < formals.size(); i++) { Formal formal = formals.get(i); formal.assignParameter(scope, parameters.get(i)); } procedure.execute(scope); //Exit scope scope = scope.getParent(); } public void visit( WithStatement withStatement) throws SymbolAlreadyDeclaredException{ ExpressionEvaluator exprEval = new ExpressionEvaluator(scope); RecordValue record = (RecordValue) exprEval.dispatch(withStatement.getRecord()); //Enter new scope and expose members of record. scope = new InterpreterScope(scope); for( Entry<Identifier, ValueReference> entry : record.entrySet() ){ Identifier id = entry.getKey(); ValueReference reference = entry.getValue(); String symbol = id.getName(); scope.declareValueReference(symbol, reference); } //Execute all statements StatementEvaluator statEval = new StatementEvaluator(scope); for(Statement stat: withStatement.getStatements()){ statEval.dispatch(stat); } //Exit scope scope = scope.getParent(); } public void visit(IfStatement ifStatement) throws TypeMismatchException, ValueUndefinedException { if (evalCondition(ifStatement.getCondition())) { // 1. Als de if matched, evalueren we die statement en stoppen de // evaluatie. visitStatements(ifStatement.getTrueStatements()); return; } else { for (Iterator<ElseIfStatement> iterator = ifStatement.getElseIfs().iterator(); iterator.hasNext();) { ElseIfStatement elseif = (ElseIfStatement) iterator.next(); if (evalCondition(elseif.getCondition())) { // 2. Zodra er een elseif is gematched en uitgevoerd stopt // de evaluatie. visitStatements(elseif.getTrueStatements()); return; } } // 3. Finally, als zowel het if statement en de elseif's falen te // matchen, voeren<SUF> visitStatements(ifStatement.getFalseStatements()); return; } } private void visitStatements(List<Statement> statements) { if (!statements.isEmpty()) { StatementEvaluator statEval = new StatementEvaluator(scope); for (Statement stat : statements) { statEval.dispatch(stat); } } } private boolean evalCondition(Expression exp) throws TypeMismatchException, ValueUndefinedException { ExpressionEvaluator expEval = new ExpressionEvaluator(scope); BooleanValue result = (BooleanValue) expEval.dispatch(exp); return result.getValue(); } public void visit(WhileStatement whilestat) throws TypeMismatchException, ValueUndefinedException { StatementEvaluator statEval = new StatementEvaluator(scope); while (evalCondition(whilestat.getCondition())) { for (Statement s : whilestat.getStatements()) { statEval.dispatch(s); } } } }
103348_6
package wiiv.emporium.client.model; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; /** * kitchen_cabinet_doors_top - wiiv * Created using Tabula 4.1.1 */ public class ModelCabinet extends ModelBase { private static final ModelCabinet INSTANCE = new ModelCabinet(); //ceiling cabinet top public ModelRenderer topc; //floor cabinet top public ModelRenderer topf; public ModelRenderer back; public ModelRenderer lside; public ModelRenderer rside; public ModelRenderer bottom; public ModelRenderer shelft; public ModelRenderer shelfb; //ceiling cabinet doors public ModelRenderer ldoor; public ModelRenderer rdoor; public ModelRenderer lhandle; public ModelRenderer rhandle; //floor cabinet doors public ModelRenderer fldoor; public ModelRenderer frdoor; public ModelRenderer flhandle; public ModelRenderer frhandle; //ceiling cabinet doors public ModelRenderer ldoorc= (new ModelRenderer(this, 0, 64)).setTextureSize(64, 128); public ModelRenderer lhandlec; public ModelRenderer rdoorc = (new ModelRenderer(this, 18, 64)).setTextureSize(64, 128); public ModelRenderer rhandlec; //floor cabinet door public ModelRenderer ldoorf; public ModelRenderer lhandlef; public ModelRenderer rdoorf; public ModelRenderer rhandlef; public static ModelCabinet getInstance() { return INSTANCE; } public static ModelCabinet newInstance() { return new ModelCabinet(); } public ModelCabinet() { this.textureWidth = 64; this.textureHeight = 128; //ceiling cabinet top this.topc = new ModelRenderer(this, 0, 18); this.topc.setRotationPoint(0.0F, 16.0F, 0.0F); this.topc.addBox(-8.0F, -8.0F, -6.0F, 16, 2, 14, 0.0F); //floor cabinet top this.topf = new ModelRenderer(this, 0, 0); this.topf.setRotationPoint(0.0F, 16.0F, 0.0F); this.topf.addBox(-8.0F, -8.0F, -8.0F, 16, 2, 16, 0.0F); this.back = new ModelRenderer(this, 0, 50); this.back.setRotationPoint(0.0F, 16.0F, 0.0F); this.back.addBox(-8.0F, -6.0F, 6.0F, 16, 12, 2, 0.0F); this.lside = new ModelRenderer(this, 0, 90); this.lside.setRotationPoint(0.0F, 16.0F, 0.0F); this.lside.addBox(-8.0F, -6.0F, -6.0F, 1, 12, 12, 0.0F); this.rside = new ModelRenderer(this, 26, 90); this.rside.setRotationPoint(0.0F, 16.0F, 0.0F); this.rside.addBox(7.0F, -6.0F, -6.0F, 1, 12, 12, 0.0F); this.bottom = new ModelRenderer(this, 0, 34); this.bottom.setRotationPoint(0.0F, 16.0F, 0.0F); this.bottom.addBox(-8.0F, 6.0F, -6.0F, 16, 2, 14, 0.0F); this.shelft = new ModelRenderer(this, 0, 114); this.shelft.setRotationPoint(0.0F, 16.0F, 0.0F); this.shelft.addBox(-7.0F, -6.0F, -6.0F, 14, 1, 12, 0.0F); this.shelfb = new ModelRenderer(this, 0, 114); this.shelfb.setRotationPoint(0.0F, 16.0F, 0.0F); this.shelfb.addBox(-7.0F, 0.0F, -6.0F, 14, 1, 12, 0.0F); //ceiling cabinet doors this.ldoorc = new ModelRenderer(this, 0, 64); this.ldoorc.setRotationPoint(-7.0F, 16.0F, -7.0F); this.ldoorc.addBox(-1.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.lhandlec = new ModelRenderer(this, 0, 0); this.lhandlec.setRotationPoint(0.0F, 0.0F, 0.0F); this.lhandlec.addBox(5.0F, 1.0F, -1.0F, 1, 4, 1, 0.0F); this.rdoorc = new ModelRenderer(this, 18, 64); this.rdoorc.setRotationPoint(7.0F, 16.0F, -7.0F); this.rdoorc.addBox(-7.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.rhandlec = new ModelRenderer(this, 0, 0); this.rhandlec.setRotationPoint(0.0F, 0.0F, 0.0F); this.rhandlec.addBox(-6.0F, 1.0F, -1.0F, 1, 4, 1, 0.0F); //floor cabinet doors this.ldoorf = new ModelRenderer(this, 0, 64); this.ldoorf.setRotationPoint(-7.0F, 16.0F, -7.0F); this.ldoorf.addBox(-1.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.lhandlef = new ModelRenderer(this, 0, 0); this.lhandlef.setRotationPoint(0.0F, 0.0F, 0.0F); this.lhandlef.addBox(5.0F, -5.0F, -1.0F, 1, 4, 1, 0.0F); this.rdoorf = new ModelRenderer(this, 18, 64); this.rdoorf.setRotationPoint(7.0F, 16.0F, -7.0F); this.rdoorf.addBox(-7.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.rhandlef = new ModelRenderer(this, 0, 0); this.rhandlef.setRotationPoint(0.0F, 0.0F, 0.0F); this.rhandlef.addBox(-6.0F, -5.0F, -1.0F, 1, 4, 1, 0.0F); //floor cabinet door this.rdoor = new ModelRenderer(this, 0, 77); this.rdoor.setRotationPoint(7.0F, 16.0F, -7.0F); this.rdoor.addBox(-15.0F, -6.0F, 0.0F, 16, 12, 1, 0.0F); this.rhandle = new ModelRenderer(this, 4, 0); this.rhandle.setRotationPoint(0.0F, 0.0F, 0.0F); this.rhandle.addBox(-14.0F, -1.0F, -1.0F, 1, 6, 1, 0.0F); this.ldoor = new ModelRenderer(this, 0, 77); this.ldoor.setRotationPoint(-7.0F, 16.0F, -7.0F); this.ldoor.addBox(-1.0F, -6.0F, 0.0F, 16, 12, 1, 0.0F); this.lhandle = new ModelRenderer(this, 4, 0); this.lhandle.setRotationPoint(0.0F, 0.0F, 0.0F); this.lhandle.addBox(13.0F, -1.0F, -1.0F, 1, 6, 1, 0.0F); this.ldoorc.addChild(this.lhandlec); this.rdoorc.addChild(this.rhandlec); this.ldoorf.addChild(this.lhandlef); this.rdoorf.addChild(this.rhandlef); this.ldoor.addChild(this.lhandle); this.rdoor.addChild(this.rhandle); } public void render(float f5) { //this.topc.render(f5); this.topf.render(f5); this.back.render(f5); this.lside.render(f5); this.rside.render(f5); this.bottom.render(f5); this.shelft.render(f5); this.shelfb.render(f5); //this.ldoorc.render(f5); //this.rdoorc.render(f5); this.ldoorf.render(f5); this.rdoorf.render(f5); //this.ldoor.render(f5); //this.rdoor.render(f5); //current setup renders a ceiling cabinet with double doors } }
wiiv/Emporium
src/main/java/wiiv/emporium/client/model/ModelCabinet.java
2,666
//floor cabinet door
line_comment
nl
package wiiv.emporium.client.model; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; /** * kitchen_cabinet_doors_top - wiiv * Created using Tabula 4.1.1 */ public class ModelCabinet extends ModelBase { private static final ModelCabinet INSTANCE = new ModelCabinet(); //ceiling cabinet top public ModelRenderer topc; //floor cabinet top public ModelRenderer topf; public ModelRenderer back; public ModelRenderer lside; public ModelRenderer rside; public ModelRenderer bottom; public ModelRenderer shelft; public ModelRenderer shelfb; //ceiling cabinet doors public ModelRenderer ldoor; public ModelRenderer rdoor; public ModelRenderer lhandle; public ModelRenderer rhandle; //floor cabinet doors public ModelRenderer fldoor; public ModelRenderer frdoor; public ModelRenderer flhandle; public ModelRenderer frhandle; //ceiling cabinet doors public ModelRenderer ldoorc= (new ModelRenderer(this, 0, 64)).setTextureSize(64, 128); public ModelRenderer lhandlec; public ModelRenderer rdoorc = (new ModelRenderer(this, 18, 64)).setTextureSize(64, 128); public ModelRenderer rhandlec; //floor cabinet<SUF> public ModelRenderer ldoorf; public ModelRenderer lhandlef; public ModelRenderer rdoorf; public ModelRenderer rhandlef; public static ModelCabinet getInstance() { return INSTANCE; } public static ModelCabinet newInstance() { return new ModelCabinet(); } public ModelCabinet() { this.textureWidth = 64; this.textureHeight = 128; //ceiling cabinet top this.topc = new ModelRenderer(this, 0, 18); this.topc.setRotationPoint(0.0F, 16.0F, 0.0F); this.topc.addBox(-8.0F, -8.0F, -6.0F, 16, 2, 14, 0.0F); //floor cabinet top this.topf = new ModelRenderer(this, 0, 0); this.topf.setRotationPoint(0.0F, 16.0F, 0.0F); this.topf.addBox(-8.0F, -8.0F, -8.0F, 16, 2, 16, 0.0F); this.back = new ModelRenderer(this, 0, 50); this.back.setRotationPoint(0.0F, 16.0F, 0.0F); this.back.addBox(-8.0F, -6.0F, 6.0F, 16, 12, 2, 0.0F); this.lside = new ModelRenderer(this, 0, 90); this.lside.setRotationPoint(0.0F, 16.0F, 0.0F); this.lside.addBox(-8.0F, -6.0F, -6.0F, 1, 12, 12, 0.0F); this.rside = new ModelRenderer(this, 26, 90); this.rside.setRotationPoint(0.0F, 16.0F, 0.0F); this.rside.addBox(7.0F, -6.0F, -6.0F, 1, 12, 12, 0.0F); this.bottom = new ModelRenderer(this, 0, 34); this.bottom.setRotationPoint(0.0F, 16.0F, 0.0F); this.bottom.addBox(-8.0F, 6.0F, -6.0F, 16, 2, 14, 0.0F); this.shelft = new ModelRenderer(this, 0, 114); this.shelft.setRotationPoint(0.0F, 16.0F, 0.0F); this.shelft.addBox(-7.0F, -6.0F, -6.0F, 14, 1, 12, 0.0F); this.shelfb = new ModelRenderer(this, 0, 114); this.shelfb.setRotationPoint(0.0F, 16.0F, 0.0F); this.shelfb.addBox(-7.0F, 0.0F, -6.0F, 14, 1, 12, 0.0F); //ceiling cabinet doors this.ldoorc = new ModelRenderer(this, 0, 64); this.ldoorc.setRotationPoint(-7.0F, 16.0F, -7.0F); this.ldoorc.addBox(-1.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.lhandlec = new ModelRenderer(this, 0, 0); this.lhandlec.setRotationPoint(0.0F, 0.0F, 0.0F); this.lhandlec.addBox(5.0F, 1.0F, -1.0F, 1, 4, 1, 0.0F); this.rdoorc = new ModelRenderer(this, 18, 64); this.rdoorc.setRotationPoint(7.0F, 16.0F, -7.0F); this.rdoorc.addBox(-7.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.rhandlec = new ModelRenderer(this, 0, 0); this.rhandlec.setRotationPoint(0.0F, 0.0F, 0.0F); this.rhandlec.addBox(-6.0F, 1.0F, -1.0F, 1, 4, 1, 0.0F); //floor cabinet doors this.ldoorf = new ModelRenderer(this, 0, 64); this.ldoorf.setRotationPoint(-7.0F, 16.0F, -7.0F); this.ldoorf.addBox(-1.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.lhandlef = new ModelRenderer(this, 0, 0); this.lhandlef.setRotationPoint(0.0F, 0.0F, 0.0F); this.lhandlef.addBox(5.0F, -5.0F, -1.0F, 1, 4, 1, 0.0F); this.rdoorf = new ModelRenderer(this, 18, 64); this.rdoorf.setRotationPoint(7.0F, 16.0F, -7.0F); this.rdoorf.addBox(-7.0F, -6.0F, 0.0F, 8, 12, 1, 0.0F); this.rhandlef = new ModelRenderer(this, 0, 0); this.rhandlef.setRotationPoint(0.0F, 0.0F, 0.0F); this.rhandlef.addBox(-6.0F, -5.0F, -1.0F, 1, 4, 1, 0.0F); //floor cabinet door this.rdoor = new ModelRenderer(this, 0, 77); this.rdoor.setRotationPoint(7.0F, 16.0F, -7.0F); this.rdoor.addBox(-15.0F, -6.0F, 0.0F, 16, 12, 1, 0.0F); this.rhandle = new ModelRenderer(this, 4, 0); this.rhandle.setRotationPoint(0.0F, 0.0F, 0.0F); this.rhandle.addBox(-14.0F, -1.0F, -1.0F, 1, 6, 1, 0.0F); this.ldoor = new ModelRenderer(this, 0, 77); this.ldoor.setRotationPoint(-7.0F, 16.0F, -7.0F); this.ldoor.addBox(-1.0F, -6.0F, 0.0F, 16, 12, 1, 0.0F); this.lhandle = new ModelRenderer(this, 4, 0); this.lhandle.setRotationPoint(0.0F, 0.0F, 0.0F); this.lhandle.addBox(13.0F, -1.0F, -1.0F, 1, 6, 1, 0.0F); this.ldoorc.addChild(this.lhandlec); this.rdoorc.addChild(this.rhandlec); this.ldoorf.addChild(this.lhandlef); this.rdoorf.addChild(this.rhandlef); this.ldoor.addChild(this.lhandle); this.rdoor.addChild(this.rhandle); } public void render(float f5) { //this.topc.render(f5); this.topf.render(f5); this.back.render(f5); this.lside.render(f5); this.rside.render(f5); this.bottom.render(f5); this.shelft.render(f5); this.shelfb.render(f5); //this.ldoorc.render(f5); //this.rdoorc.render(f5); this.ldoorf.render(f5); this.rdoorf.render(f5); //this.ldoor.render(f5); //this.rdoor.render(f5); //current setup renders a ceiling cabinet with double doors } }
101794_19
/* Copyright (c) 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty. */ package cern.clhep; /** * High Energy Physics coherent system of Units. * This class is a Java port of the <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep/manual/RefGuide/Units/SystemOfUnits_h.html">C++ version</a> found in <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep">CLHEP 1.4.0</a>, which in turn has been provided by Geant4 (a simulation toolkit for HEP). * * @author [email protected] * @version 1.0, 09/24/99 */ public class Units { public static final double millimeter = 1.0; public static final double millimeter2 = millimeter*millimeter; public static final double millimeter3 = millimeter*millimeter*millimeter; public static final double centimeter = 10.*millimeter; public static final double centimeter2 = centimeter*centimeter; public static final double centimeter3 = centimeter*centimeter*centimeter; public static final double meter = 1000.*millimeter; public static final double meter2 = meter*meter; public static final double meter3 = meter*meter*meter; public static final double kilometer = 1000.*meter; public static final double kilometer2 = kilometer*kilometer; public static final double kilometer3 = kilometer*kilometer*kilometer; public static final double micrometer = 1.e-6 *meter; public static final double nanometer = 1.e-9 *meter; public static final double angstrom = 1.e-10*meter; public static final double fermi = 1.e-15*meter; public static final double barn = 1.e-28*meter2; public static final double millibarn = 1.e-3 *barn; public static final double microbarn = 1.e-6 *barn; public static final double nanobarn = 1.e-9 *barn; public static final double picobarn = 1.e-12*barn; // symbols public static final double mm = millimeter; public static final double mm2 = millimeter2; public static final double mm3 = millimeter3; public static final double cm = centimeter; public static final double cm2 = centimeter2; public static final double cm3 = centimeter3; public static final double m = meter; public static final double m2 = meter2; public static final double m3 = meter3; public static final double km = kilometer; public static final double km2 = kilometer2; public static final double km3 = kilometer3; // // Angle // public static final double radian = 1.; public static final double milliradian = 1.e-3*radian; public static final double degree = (Math.PI/180.0)*radian; //(3.14159265358979323846/180.0)*radian; public static final double steradian = 1.; // symbols public static final double rad = radian; public static final double mrad = milliradian; public static final double sr = steradian; public static final double deg = degree; // // Time [T] // public static final double nanosecond = 1.; public static final double second = 1.e+9 *nanosecond; public static final double millisecond = 1.e-3 *second; public static final double microsecond = 1.e-6 *second; public static final double picosecond = 1.e-12*second; public static final double hertz = 1./second; public static final double kilohertz = 1.e+3*hertz; public static final double megahertz = 1.e+6*hertz; // symbols public static final double ns = nanosecond; public static final double s = second; public static final double ms = millisecond; // // Electric charge [Q] // public static final double eplus = 1. ; // positron charge public static final double e_SI = 1.60217733e-19; // positron charge in coulomb public static final double coulomb = eplus/e_SI; // coulomb = 6.24150 e+18 * eplus // // Energy [E] // public static final double megaelectronvolt = 1. ; public static final double electronvolt = 1.e-6*megaelectronvolt; public static final double kiloelectronvolt = 1.e-3*megaelectronvolt; public static final double gigaelectronvolt = 1.e+3*megaelectronvolt; public static final double teraelectronvolt = 1.e+6*megaelectronvolt; public static final double petaelectronvolt = 1.e+9*megaelectronvolt; public static final double joule = electronvolt/e_SI; // joule = 6.24150 e+12 * MeV // symbols public static final double MeV = megaelectronvolt; public static final double eV = electronvolt; public static final double keV = kiloelectronvolt; public static final double GeV = gigaelectronvolt; public static final double TeV = teraelectronvolt; public static final double PeV = petaelectronvolt; // // Mass [E][T^2][L^-2] // public static final double kilogram = joule*second*second/(meter*meter); public static final double gram = 1.e-3*kilogram; public static final double milligram = 1.e-3*gram; // symbols public static final double kg = kilogram; public static final double g = gram; public static final double mg = milligram; // // Power [E][T^-1] // public static final double watt = joule/second; // watt = 6.24150 e+3 * MeV/ns // // Force [E][L^-1] // public static final double newton = joule/meter; // newton = 6.24150 e+9 * MeV/mm // // Pressure [E][L^-3] // public static final double hep_pascal = newton/m2; // pascal = 6.24150 e+3 * MeV/mm3 public static final double pascal = hep_pascal; public static final double bar = 100000*pascal; // bar = 6.24150 e+8 * MeV/mm3 public static final double atmosphere = 101325*pascal; // atm = 6.32420 e+8 * MeV/mm3 // // Electric current [Q][T^-1] // public static final double ampere = coulomb/second; // ampere = 6.24150 e+9 * eplus/ns public static final double milliampere = 1.e-3*ampere; public static final double microampere = 1.e-6*ampere; public static final double nanoampere = 1.e-9*ampere; // // Electric potential [E][Q^-1] // public static final double megavolt = megaelectronvolt/eplus; public static final double kilovolt = 1.e-3*megavolt; public static final double volt = 1.e-6*megavolt; // // Electric resistance [E][T][Q^-2] // public static final double ohm = volt/ampere; // ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) // // Electric capacitance [Q^2][E^-1] // public static final double farad = coulomb/volt; // farad = 6.24150e+24 * eplus/Megavolt public static final double millifarad = 1.e-3*farad; public static final double microfarad = 1.e-6*farad; public static final double nanofarad = 1.e-9*farad; public static final double picofarad = 1.e-12*farad; // // Magnetic Flux [T][E][Q^-1] // public static final double weber = volt*second; // weber = 1000*megavolt*ns // // Magnetic Field [T][E][Q^-1][L^-2] // public static final double tesla = volt*second/meter2; // tesla =0.001*megavolt*ns/mm2 public static final double gauss = 1.e-4*tesla; public static final double kilogauss = 1.e-1*tesla; // // Inductance [T^2][E][Q^-2] // public static final double henry = weber/ampere; // henry = 1.60217e-7*MeV*(ns/eplus)**2 // // Temperature // public static final double kelvin = 1.; // // Amount of substance // public static final double mole = 1.; // // Activity [T^-1] // public static final double becquerel = 1./second ; public static final double curie = 3.7e+10 * becquerel; // // Absorbed dose [L^2][T^-2] // public static final double gray = joule/kilogram ; // // Luminous intensity [I] // public static final double candela = 1.; // // Luminous flux [I] // public static final double lumen = candela*steradian; // // Illuminance [I][L^-2] // public static final double lux = lumen/meter2; // // Miscellaneous // public static final double perCent = 0.01 ; public static final double perThousand = 0.001; public static final double perMillion = 0.000001; /** * Makes this class non instantiable, but still let's others inherit from it. */ protected Units() {} }
wikimedia/wikidata-query-blazegraph
blazegraph-colt/src/main/java/cern/clhep/Units.java
2,885
// weber = 1000*megavolt*ns
line_comment
nl
/* Copyright (c) 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty. */ package cern.clhep; /** * High Energy Physics coherent system of Units. * This class is a Java port of the <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep/manual/RefGuide/Units/SystemOfUnits_h.html">C++ version</a> found in <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep">CLHEP 1.4.0</a>, which in turn has been provided by Geant4 (a simulation toolkit for HEP). * * @author [email protected] * @version 1.0, 09/24/99 */ public class Units { public static final double millimeter = 1.0; public static final double millimeter2 = millimeter*millimeter; public static final double millimeter3 = millimeter*millimeter*millimeter; public static final double centimeter = 10.*millimeter; public static final double centimeter2 = centimeter*centimeter; public static final double centimeter3 = centimeter*centimeter*centimeter; public static final double meter = 1000.*millimeter; public static final double meter2 = meter*meter; public static final double meter3 = meter*meter*meter; public static final double kilometer = 1000.*meter; public static final double kilometer2 = kilometer*kilometer; public static final double kilometer3 = kilometer*kilometer*kilometer; public static final double micrometer = 1.e-6 *meter; public static final double nanometer = 1.e-9 *meter; public static final double angstrom = 1.e-10*meter; public static final double fermi = 1.e-15*meter; public static final double barn = 1.e-28*meter2; public static final double millibarn = 1.e-3 *barn; public static final double microbarn = 1.e-6 *barn; public static final double nanobarn = 1.e-9 *barn; public static final double picobarn = 1.e-12*barn; // symbols public static final double mm = millimeter; public static final double mm2 = millimeter2; public static final double mm3 = millimeter3; public static final double cm = centimeter; public static final double cm2 = centimeter2; public static final double cm3 = centimeter3; public static final double m = meter; public static final double m2 = meter2; public static final double m3 = meter3; public static final double km = kilometer; public static final double km2 = kilometer2; public static final double km3 = kilometer3; // // Angle // public static final double radian = 1.; public static final double milliradian = 1.e-3*radian; public static final double degree = (Math.PI/180.0)*radian; //(3.14159265358979323846/180.0)*radian; public static final double steradian = 1.; // symbols public static final double rad = radian; public static final double mrad = milliradian; public static final double sr = steradian; public static final double deg = degree; // // Time [T] // public static final double nanosecond = 1.; public static final double second = 1.e+9 *nanosecond; public static final double millisecond = 1.e-3 *second; public static final double microsecond = 1.e-6 *second; public static final double picosecond = 1.e-12*second; public static final double hertz = 1./second; public static final double kilohertz = 1.e+3*hertz; public static final double megahertz = 1.e+6*hertz; // symbols public static final double ns = nanosecond; public static final double s = second; public static final double ms = millisecond; // // Electric charge [Q] // public static final double eplus = 1. ; // positron charge public static final double e_SI = 1.60217733e-19; // positron charge in coulomb public static final double coulomb = eplus/e_SI; // coulomb = 6.24150 e+18 * eplus // // Energy [E] // public static final double megaelectronvolt = 1. ; public static final double electronvolt = 1.e-6*megaelectronvolt; public static final double kiloelectronvolt = 1.e-3*megaelectronvolt; public static final double gigaelectronvolt = 1.e+3*megaelectronvolt; public static final double teraelectronvolt = 1.e+6*megaelectronvolt; public static final double petaelectronvolt = 1.e+9*megaelectronvolt; public static final double joule = electronvolt/e_SI; // joule = 6.24150 e+12 * MeV // symbols public static final double MeV = megaelectronvolt; public static final double eV = electronvolt; public static final double keV = kiloelectronvolt; public static final double GeV = gigaelectronvolt; public static final double TeV = teraelectronvolt; public static final double PeV = petaelectronvolt; // // Mass [E][T^2][L^-2] // public static final double kilogram = joule*second*second/(meter*meter); public static final double gram = 1.e-3*kilogram; public static final double milligram = 1.e-3*gram; // symbols public static final double kg = kilogram; public static final double g = gram; public static final double mg = milligram; // // Power [E][T^-1] // public static final double watt = joule/second; // watt = 6.24150 e+3 * MeV/ns // // Force [E][L^-1] // public static final double newton = joule/meter; // newton = 6.24150 e+9 * MeV/mm // // Pressure [E][L^-3] // public static final double hep_pascal = newton/m2; // pascal = 6.24150 e+3 * MeV/mm3 public static final double pascal = hep_pascal; public static final double bar = 100000*pascal; // bar = 6.24150 e+8 * MeV/mm3 public static final double atmosphere = 101325*pascal; // atm = 6.32420 e+8 * MeV/mm3 // // Electric current [Q][T^-1] // public static final double ampere = coulomb/second; // ampere = 6.24150 e+9 * eplus/ns public static final double milliampere = 1.e-3*ampere; public static final double microampere = 1.e-6*ampere; public static final double nanoampere = 1.e-9*ampere; // // Electric potential [E][Q^-1] // public static final double megavolt = megaelectronvolt/eplus; public static final double kilovolt = 1.e-3*megavolt; public static final double volt = 1.e-6*megavolt; // // Electric resistance [E][T][Q^-2] // public static final double ohm = volt/ampere; // ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) // // Electric capacitance [Q^2][E^-1] // public static final double farad = coulomb/volt; // farad = 6.24150e+24 * eplus/Megavolt public static final double millifarad = 1.e-3*farad; public static final double microfarad = 1.e-6*farad; public static final double nanofarad = 1.e-9*farad; public static final double picofarad = 1.e-12*farad; // // Magnetic Flux [T][E][Q^-1] // public static final double weber = volt*second; // weber =<SUF> // // Magnetic Field [T][E][Q^-1][L^-2] // public static final double tesla = volt*second/meter2; // tesla =0.001*megavolt*ns/mm2 public static final double gauss = 1.e-4*tesla; public static final double kilogauss = 1.e-1*tesla; // // Inductance [T^2][E][Q^-2] // public static final double henry = weber/ampere; // henry = 1.60217e-7*MeV*(ns/eplus)**2 // // Temperature // public static final double kelvin = 1.; // // Amount of substance // public static final double mole = 1.; // // Activity [T^-1] // public static final double becquerel = 1./second ; public static final double curie = 3.7e+10 * becquerel; // // Absorbed dose [L^2][T^-2] // public static final double gray = joule/kilogram ; // // Luminous intensity [I] // public static final double candela = 1.; // // Luminous flux [I] // public static final double lumen = candela*steradian; // // Illuminance [I][L^-2] // public static final double lux = lumen/meter2; // // Miscellaneous // public static final double perCent = 0.01 ; public static final double perThousand = 0.001; public static final double perMillion = 0.000001; /** * Makes this class non instantiable, but still let's others inherit from it. */ protected Units() {} }
156451_34
package com.xiaoleilu.loServer.handler; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; import cn.hutool.core.net.NetUtil; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieDecoder; import io.netty.handler.codec.http.multipart.Attribute; import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory; import io.netty.handler.codec.http.multipart.FileUpload; import io.netty.handler.codec.http.multipart.HttpDataFactory; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; import io.netty.handler.codec.http.multipart.InterfaceHttpData; import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType; import org.slf4j.LoggerFactory; /** * Http请求对象 * * @author Looly * */ public class Request { private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(Request.class); public static final String METHOD_DELETE = HttpMethod.DELETE.name(); public static final String METHOD_HEAD = HttpMethod.HEAD.name(); public static final String METHOD_GET = HttpMethod.GET.name(); public static final String METHOD_OPTIONS = HttpMethod.OPTIONS.name(); public static final String METHOD_POST = HttpMethod.POST.name(); public static final String METHOD_PUT = HttpMethod.PUT.name(); public static final String METHOD_TRACE = HttpMethod.TRACE.name(); private static final HttpDataFactory HTTP_DATA_FACTORY = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); private FullHttpRequest nettyRequest; private String path; private String ip; private Map<String, String> headers = new HashMap<String, String>(); private Map<String, Object> params = new HashMap<String, Object>(); private Map<String, Cookie> cookies = new HashMap<String, Cookie>(); /** * 构造 * * @param ctx ChannelHandlerContext * @param nettyRequest HttpRequest */ private Request(ChannelHandlerContext ctx, FullHttpRequest nettyRequest) { this.nettyRequest = nettyRequest; final String uri = nettyRequest.uri(); this.path = URLUtil.getPath(getUri()); this.putHeadersAndCookies(nettyRequest.headers()); // request URI parameters this.putParams(new QueryStringDecoder(uri)); // IP this.putIp(ctx); } /** * @return Netty的HttpRequest */ public HttpRequest getNettyRequest() { return this.nettyRequest; } /** * 获得版本信息 * * @return 版本 */ public String getProtocolVersion() { return nettyRequest.protocolVersion().text(); } /** * 获得URI(带参数的路径) * * @return URI */ public String getUri() { return nettyRequest.uri(); } /** * @return 获得path(不带参数的路径) */ public String getPath() { return path; } /** * 获得Http方法 * * @return Http method */ public String getMethod() { return nettyRequest.method().name(); } /** * 获得IP地址 * * @return IP地址 */ public String getIp() { return ip; } /** * 获得所有头信息 * * @return 头信息Map */ public Map<String, String> getHeaders() { return headers; } /** * 使用ISO8859_1字符集获得Header内容<br> * 由于Header中很少有中文,故一般情况下无需转码 * * @param headerKey 头信息的KEY * @return 值 */ public String getHeader(String headerKey) { return headers.get(headerKey); } /** * @return 是否为普通表单(application/x-www-form-urlencoded) */ public boolean isXWwwFormUrlencoded() { return "application/x-www-form-urlencoded".equals(getHeader("Content-Type")); } /** * 获得指定的Cookie * * @param name cookie名 * @return Cookie对象 */ public Cookie getCookie(String name) { return cookies.get(name); } /** * @return 获得所有Cookie信息 */ public Map<String, Cookie> getCookies() { return this.cookies; } /** * @return 客户浏览器是否为IE */ public boolean isIE() { String userAgent = getHeader("User-Agent"); if (StrUtil.isNotBlank(userAgent)) { userAgent = userAgent.toUpperCase(); if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT")) { return true; } } return false; } /** * @param name 参数名 * @return 获得请求参数 */ public String getParam(String name) { final Object value = params.get(name); if(null == value){ return null; } if(value instanceof String){ return (String)value; } return value.toString(); } /** * @param name 参数名 * @return 获得请求参数 */ public Object getObjParam(String name) { return params.get(name); } /** * 获得GET请求参数<br> * 会根据浏览器类型自动识别GET请求的编码方式从而解码<br> * charsetOfServlet为null则默认的ISO_8859_1 * * @param name 参数名 * @param charset 字符集 * @return 获得请求参数 */ public String getParam(String name, Charset charset) { if (null == charset) { charset = Charset.forName(CharsetUtil.ISO_8859_1); } String destCharset = CharsetUtil.UTF_8; if (isIE()) { // IE浏览器GET请求使用GBK编码 destCharset = CharsetUtil.GBK; } String value = getParam(name); if (METHOD_GET.equalsIgnoreCase(getMethod())) { value = CharsetUtil.convert(value, charset.toString(), destCharset); } return value; } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得请求参数 */ public String getParam(String name, String defaultValue) { String param = getParam(name); return StrUtil.isBlank(param) ? defaultValue : param; } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Integer类型请求参数 */ public Integer getIntParam(String name, Integer defaultValue) { return Convert.toInt(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得long类型请求参数 */ public Long getLongParam(String name, Long defaultValue) { return Convert.toLong(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Double类型请求参数 */ public Double getDoubleParam(String name, Double defaultValue) { return Convert.toDouble(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Float类型请求参数 */ public Float getFloatParam(String name, Float defaultValue) { return Convert.toFloat(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Boolean类型请求参数 */ public Boolean getBoolParam(String name, Boolean defaultValue) { return Convert.toBool(getParam(name), defaultValue); } /** * 格式:<br> * 1、yyyy-MM-dd HH:mm:ss <br> * 2、yyyy-MM-dd <br> * 3、HH:mm:ss <br> * * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Date类型请求参数,默认格式: */ public Date getDateParam(String name, Date defaultValue) { String param = getParam(name); return StrUtil.isBlank(param) ? defaultValue : DateUtil.parse(param); } /** * @param name 参数名 * @param format 格式 * @param defaultValue 当客户端未传参的默认值 * @return 获得Date类型请求参数 */ public Date getDateParam(String name, String format, Date defaultValue) { String param = getParam(name); return StrUtil.isBlank(param) ? defaultValue : DateUtil.parse(param, format); } /** * 获得请求参数<br> * 列表类型值,常用于表单中的多选框 * * @param name 参数名 * @return 数组 */ @SuppressWarnings("unchecked") public List<String> getArrayParam(String name) { Object value = params.get(name); if(null == value){ return null; } if(value instanceof List){ return (List<String>) value; }else if(value instanceof String){ return StrUtil.split((String)value, ','); }else{ throw new RuntimeException("Value is not a List type!"); } } /** * 获得所有请求参数 * * @return Map */ public Map<String, Object> getParams() { return params; } /** * @return 是否为长连接 */ public boolean isKeepAlive() { final String connectionHeader = getHeader(HttpHeaderNames.CONNECTION.toString()); // 无论任何版本Connection为close时都关闭连接 if (HttpHeaderValues.CLOSE.toString().equalsIgnoreCase(connectionHeader)) { return false; } // HTTP/1.0只有Connection为Keep-Alive时才会保持连接 if (HttpVersion.HTTP_1_0.text().equals(getProtocolVersion())) { if (false == HttpHeaderValues.KEEP_ALIVE.toString().equalsIgnoreCase(connectionHeader)) { return false; } } // HTTP/1.1默认打开Keep-Alive return true; } // --------------------------------------------------------- Protected method start /** * 填充参数(GET请求的参数) * * @param decoder QueryStringDecoder */ protected void putParams(QueryStringDecoder decoder) { if (null != decoder) { List<String> valueList; for (Entry<String, List<String>> entry : decoder.parameters().entrySet()) { valueList = entry.getValue(); if(null != valueList){ this.putParam(entry.getKey(), 1 == valueList.size() ? valueList.get(0) : valueList); } } } } /** * 填充参数(POST请求的参数) * * @param decoder QueryStringDecoder */ protected void putParams(HttpPostRequestDecoder decoder) { if (null == decoder) { return; } for (InterfaceHttpData data : decoder.getBodyHttpDatas()) { putParam(data); } } /** * 填充参数 * * @param data InterfaceHttpData */ protected void putParam(InterfaceHttpData data) { final HttpDataType dataType = data.getHttpDataType(); if (dataType == HttpDataType.Attribute) { //普通参数 Attribute attribute = (Attribute) data; try { this.putParam(attribute.getName(), attribute.getValue()); } catch (IOException e) { Logger.error(e.toString()); } }else if(dataType == HttpDataType.FileUpload){ //文件 FileUpload fileUpload = (FileUpload) data; if(fileUpload.isCompleted()){ try { this.putParam(data.getName(), fileUpload.getFile()); } catch (IOException e) { Logger.error(e.toString(), "Get file param [{}] error!", data.getName()); } } } } /** * 填充参数 * * @param key 参数名 * @param value 参数值 */ protected void putParam(String key, Object value) { this.params.put(key, value); } /** * 填充头部信息和Cookie信息 * * @param headers HttpHeaders */ protected void putHeadersAndCookies(HttpHeaders headers) { for (Entry<String, String> entry : headers) { this.headers.put(entry.getKey(), entry.getValue()); } // Cookie final String cookieString = this.headers.get(HttpHeaderNames.COOKIE); if (StrUtil.isNotBlank(cookieString)) { final Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString); for (Cookie cookie : cookies) { this.cookies.put(cookie.name(), cookie); } } } /** * 设置客户端IP * * @param ctx ChannelHandlerContext */ protected void putIp(ChannelHandlerContext ctx) { String ip = getHeader("X-Forwarded-For"); if (StrUtil.isNotBlank(ip)) { ip = NetUtil.getMultistageReverseProxyIp(ip); } else { final InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress(); ip = insocket.getAddress().getHostAddress(); } this.ip = ip; } // --------------------------------------------------------- Protected method end @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("\r\nprotocolVersion: ").append(getProtocolVersion()).append("\r\n"); sb.append("uri: ").append(getUri()).append("\r\n"); sb.append("path: ").append(path).append("\r\n"); sb.append("method: ").append(getMethod()).append("\r\n"); sb.append("ip: ").append(ip).append("\r\n"); sb.append("headers:\r\n "); for (Entry<String, String> entry : headers.entrySet()) { sb.append(" ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n"); } sb.append("params: \r\n"); for (Entry<String, Object> entry : params.entrySet()) { sb.append(" ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n"); } return sb.toString(); } /** * 构建Request对象 * * @param ctx ChannelHandlerContext * @param nettyRequest Netty的HttpRequest * @return Request */ protected final static Request build(ChannelHandlerContext ctx, FullHttpRequest nettyRequest) { return new Request(ctx, nettyRequest); } }
wildfirechat/im-server
broker/src/main/java/com/xiaoleilu/loServer/handler/Request.java
4,459
/** * 填充头部信息和Cookie信息 * * @param headers HttpHeaders */
block_comment
nl
package com.xiaoleilu.loServer.handler; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; import cn.hutool.core.net.NetUtil; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieDecoder; import io.netty.handler.codec.http.multipart.Attribute; import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory; import io.netty.handler.codec.http.multipart.FileUpload; import io.netty.handler.codec.http.multipart.HttpDataFactory; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; import io.netty.handler.codec.http.multipart.InterfaceHttpData; import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType; import org.slf4j.LoggerFactory; /** * Http请求对象 * * @author Looly * */ public class Request { private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(Request.class); public static final String METHOD_DELETE = HttpMethod.DELETE.name(); public static final String METHOD_HEAD = HttpMethod.HEAD.name(); public static final String METHOD_GET = HttpMethod.GET.name(); public static final String METHOD_OPTIONS = HttpMethod.OPTIONS.name(); public static final String METHOD_POST = HttpMethod.POST.name(); public static final String METHOD_PUT = HttpMethod.PUT.name(); public static final String METHOD_TRACE = HttpMethod.TRACE.name(); private static final HttpDataFactory HTTP_DATA_FACTORY = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); private FullHttpRequest nettyRequest; private String path; private String ip; private Map<String, String> headers = new HashMap<String, String>(); private Map<String, Object> params = new HashMap<String, Object>(); private Map<String, Cookie> cookies = new HashMap<String, Cookie>(); /** * 构造 * * @param ctx ChannelHandlerContext * @param nettyRequest HttpRequest */ private Request(ChannelHandlerContext ctx, FullHttpRequest nettyRequest) { this.nettyRequest = nettyRequest; final String uri = nettyRequest.uri(); this.path = URLUtil.getPath(getUri()); this.putHeadersAndCookies(nettyRequest.headers()); // request URI parameters this.putParams(new QueryStringDecoder(uri)); // IP this.putIp(ctx); } /** * @return Netty的HttpRequest */ public HttpRequest getNettyRequest() { return this.nettyRequest; } /** * 获得版本信息 * * @return 版本 */ public String getProtocolVersion() { return nettyRequest.protocolVersion().text(); } /** * 获得URI(带参数的路径) * * @return URI */ public String getUri() { return nettyRequest.uri(); } /** * @return 获得path(不带参数的路径) */ public String getPath() { return path; } /** * 获得Http方法 * * @return Http method */ public String getMethod() { return nettyRequest.method().name(); } /** * 获得IP地址 * * @return IP地址 */ public String getIp() { return ip; } /** * 获得所有头信息 * * @return 头信息Map */ public Map<String, String> getHeaders() { return headers; } /** * 使用ISO8859_1字符集获得Header内容<br> * 由于Header中很少有中文,故一般情况下无需转码 * * @param headerKey 头信息的KEY * @return 值 */ public String getHeader(String headerKey) { return headers.get(headerKey); } /** * @return 是否为普通表单(application/x-www-form-urlencoded) */ public boolean isXWwwFormUrlencoded() { return "application/x-www-form-urlencoded".equals(getHeader("Content-Type")); } /** * 获得指定的Cookie * * @param name cookie名 * @return Cookie对象 */ public Cookie getCookie(String name) { return cookies.get(name); } /** * @return 获得所有Cookie信息 */ public Map<String, Cookie> getCookies() { return this.cookies; } /** * @return 客户浏览器是否为IE */ public boolean isIE() { String userAgent = getHeader("User-Agent"); if (StrUtil.isNotBlank(userAgent)) { userAgent = userAgent.toUpperCase(); if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT")) { return true; } } return false; } /** * @param name 参数名 * @return 获得请求参数 */ public String getParam(String name) { final Object value = params.get(name); if(null == value){ return null; } if(value instanceof String){ return (String)value; } return value.toString(); } /** * @param name 参数名 * @return 获得请求参数 */ public Object getObjParam(String name) { return params.get(name); } /** * 获得GET请求参数<br> * 会根据浏览器类型自动识别GET请求的编码方式从而解码<br> * charsetOfServlet为null则默认的ISO_8859_1 * * @param name 参数名 * @param charset 字符集 * @return 获得请求参数 */ public String getParam(String name, Charset charset) { if (null == charset) { charset = Charset.forName(CharsetUtil.ISO_8859_1); } String destCharset = CharsetUtil.UTF_8; if (isIE()) { // IE浏览器GET请求使用GBK编码 destCharset = CharsetUtil.GBK; } String value = getParam(name); if (METHOD_GET.equalsIgnoreCase(getMethod())) { value = CharsetUtil.convert(value, charset.toString(), destCharset); } return value; } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得请求参数 */ public String getParam(String name, String defaultValue) { String param = getParam(name); return StrUtil.isBlank(param) ? defaultValue : param; } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Integer类型请求参数 */ public Integer getIntParam(String name, Integer defaultValue) { return Convert.toInt(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得long类型请求参数 */ public Long getLongParam(String name, Long defaultValue) { return Convert.toLong(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Double类型请求参数 */ public Double getDoubleParam(String name, Double defaultValue) { return Convert.toDouble(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Float类型请求参数 */ public Float getFloatParam(String name, Float defaultValue) { return Convert.toFloat(getParam(name), defaultValue); } /** * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Boolean类型请求参数 */ public Boolean getBoolParam(String name, Boolean defaultValue) { return Convert.toBool(getParam(name), defaultValue); } /** * 格式:<br> * 1、yyyy-MM-dd HH:mm:ss <br> * 2、yyyy-MM-dd <br> * 3、HH:mm:ss <br> * * @param name 参数名 * @param defaultValue 当客户端未传参的默认值 * @return 获得Date类型请求参数,默认格式: */ public Date getDateParam(String name, Date defaultValue) { String param = getParam(name); return StrUtil.isBlank(param) ? defaultValue : DateUtil.parse(param); } /** * @param name 参数名 * @param format 格式 * @param defaultValue 当客户端未传参的默认值 * @return 获得Date类型请求参数 */ public Date getDateParam(String name, String format, Date defaultValue) { String param = getParam(name); return StrUtil.isBlank(param) ? defaultValue : DateUtil.parse(param, format); } /** * 获得请求参数<br> * 列表类型值,常用于表单中的多选框 * * @param name 参数名 * @return 数组 */ @SuppressWarnings("unchecked") public List<String> getArrayParam(String name) { Object value = params.get(name); if(null == value){ return null; } if(value instanceof List){ return (List<String>) value; }else if(value instanceof String){ return StrUtil.split((String)value, ','); }else{ throw new RuntimeException("Value is not a List type!"); } } /** * 获得所有请求参数 * * @return Map */ public Map<String, Object> getParams() { return params; } /** * @return 是否为长连接 */ public boolean isKeepAlive() { final String connectionHeader = getHeader(HttpHeaderNames.CONNECTION.toString()); // 无论任何版本Connection为close时都关闭连接 if (HttpHeaderValues.CLOSE.toString().equalsIgnoreCase(connectionHeader)) { return false; } // HTTP/1.0只有Connection为Keep-Alive时才会保持连接 if (HttpVersion.HTTP_1_0.text().equals(getProtocolVersion())) { if (false == HttpHeaderValues.KEEP_ALIVE.toString().equalsIgnoreCase(connectionHeader)) { return false; } } // HTTP/1.1默认打开Keep-Alive return true; } // --------------------------------------------------------- Protected method start /** * 填充参数(GET请求的参数) * * @param decoder QueryStringDecoder */ protected void putParams(QueryStringDecoder decoder) { if (null != decoder) { List<String> valueList; for (Entry<String, List<String>> entry : decoder.parameters().entrySet()) { valueList = entry.getValue(); if(null != valueList){ this.putParam(entry.getKey(), 1 == valueList.size() ? valueList.get(0) : valueList); } } } } /** * 填充参数(POST请求的参数) * * @param decoder QueryStringDecoder */ protected void putParams(HttpPostRequestDecoder decoder) { if (null == decoder) { return; } for (InterfaceHttpData data : decoder.getBodyHttpDatas()) { putParam(data); } } /** * 填充参数 * * @param data InterfaceHttpData */ protected void putParam(InterfaceHttpData data) { final HttpDataType dataType = data.getHttpDataType(); if (dataType == HttpDataType.Attribute) { //普通参数 Attribute attribute = (Attribute) data; try { this.putParam(attribute.getName(), attribute.getValue()); } catch (IOException e) { Logger.error(e.toString()); } }else if(dataType == HttpDataType.FileUpload){ //文件 FileUpload fileUpload = (FileUpload) data; if(fileUpload.isCompleted()){ try { this.putParam(data.getName(), fileUpload.getFile()); } catch (IOException e) { Logger.error(e.toString(), "Get file param [{}] error!", data.getName()); } } } } /** * 填充参数 * * @param key 参数名 * @param value 参数值 */ protected void putParam(String key, Object value) { this.params.put(key, value); } /** * 填充头部信息和Cookie信息 <SUF>*/ protected void putHeadersAndCookies(HttpHeaders headers) { for (Entry<String, String> entry : headers) { this.headers.put(entry.getKey(), entry.getValue()); } // Cookie final String cookieString = this.headers.get(HttpHeaderNames.COOKIE); if (StrUtil.isNotBlank(cookieString)) { final Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString); for (Cookie cookie : cookies) { this.cookies.put(cookie.name(), cookie); } } } /** * 设置客户端IP * * @param ctx ChannelHandlerContext */ protected void putIp(ChannelHandlerContext ctx) { String ip = getHeader("X-Forwarded-For"); if (StrUtil.isNotBlank(ip)) { ip = NetUtil.getMultistageReverseProxyIp(ip); } else { final InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress(); ip = insocket.getAddress().getHostAddress(); } this.ip = ip; } // --------------------------------------------------------- Protected method end @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("\r\nprotocolVersion: ").append(getProtocolVersion()).append("\r\n"); sb.append("uri: ").append(getUri()).append("\r\n"); sb.append("path: ").append(path).append("\r\n"); sb.append("method: ").append(getMethod()).append("\r\n"); sb.append("ip: ").append(ip).append("\r\n"); sb.append("headers:\r\n "); for (Entry<String, String> entry : headers.entrySet()) { sb.append(" ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n"); } sb.append("params: \r\n"); for (Entry<String, Object> entry : params.entrySet()) { sb.append(" ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n"); } return sb.toString(); } /** * 构建Request对象 * * @param ctx ChannelHandlerContext * @param nettyRequest Netty的HttpRequest * @return Request */ protected final static Request build(ChannelHandlerContext ctx, FullHttpRequest nettyRequest) { return new Request(ctx, nettyRequest); } }
177532_14
package nl.wildlands.wildlandseducation.Activities; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import com.github.nkzawa.emitter.Emitter; import com.github.nkzawa.socketio.client.Socket; import org.json.JSONException; import org.json.JSONObject; import nl.wildlands.wildlandseducation.GlobalSettings.DefaultApplication; import nl.wildlands.wildlandseducation.R; /** * Activity waarbij de docent de gegevens van de quiz kan invoeren * en deze vervolgens d.m.v. socekts wordt aangemaakt */ public class GenerateQuiz extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener { ImageButton backBtn; // ImageButton om terug te gaan Button generateQuiz; // Button om quiz te genereren Socket mSocket; // Socket voor de quizverbinding private SeekBar bar; // Seekbar om tijd dynamisch in te stellen private TextView textProgress, genereerQuiz,tijd; // TextView voor weergave huidige tijdsinput /** * Actie die voltrokken wordt, als de socket een bepaald bericht krijgt */ private Emitter.Listener onNewMessage = new Emitter.Listener() { @Override public void call(final Object... args) { GenerateQuiz.this.runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; // Zet de data om in een JSONObject String success; // Succes van aanmaken int quizID; // ID van de gegenereerde quiz try { success = data.getString("success"); // Success message quizID = data.getInt("quizid"); // Quizid } catch (JSONException e) { return; } startNewActivity(success, quizID); // Roep startNewActivity aan met de waardes } }); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Zet layout setContentView(R.layout.activity_generate_quiz); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // Fullscreen WindowManager.LayoutParams.FLAG_FULLSCREEN); generateQuiz = (Button)findViewById(R.id.generateQuiz); // Button voor genereren quiz generateQuiz.setOnClickListener(this); // Activeer knopactie backBtn = (ImageButton)findViewById(R.id.quitbutton); // ImageButton om terug te gaan backBtn.setOnClickListener(this); // Activeer knopactie bar =(SeekBar)findViewById(R.id.seekBar1); // Seekbar om tijd in te stellen bar.setOnSeekBarChangeListener(this); // Actie bij het veranderen van de seekbar textProgress = (TextView)findViewById(R.id.textView3); // Tekst voor de actuele tijdsinstelling genereerQuiz = (TextView)findViewById(R.id.textView1); tijd = (TextView)findViewById(R.id.textView2); Typeface tf = DefaultApplication.tf2; // Verander de lettertypes genereerQuiz.setTypeface(tf); tijd.setTypeface(tf); Typeface tf2 = DefaultApplication.tf; // Verander de lettertypes generateQuiz.setTypeface(tf2); textProgress.setTypeface(tf2); mSocket = ((DefaultApplication)this.getApplicationContext()).getSocket(); // Vraag de centrale socket op mSocket.connect(); // Maak verbinding met de server } @Override public void onClick(View v) { switch(v.getId()) { case R.id.generateQuiz: // Genereer quiz ingedrukt mSocket.emit("createQuiz",""); // Verzend het verzoek om een quiz te maken startListening(); // Wacht op bevestiging break; case R.id.quitbutton: Intent i = new Intent(this, ChooseQuizGroup.class); // Backbutton gaat naar choose quiz group activity startActivity(i); this.finish(); // Beeindig deze activity break; } } public void startListening() { mSocket.on("quizCreated", onNewMessage); // Start de actie als de socket bevestiging krijgt } /** * Zet het quizid en de lengte van de quiz in de global variables * en start een nieuwe activity * @param success * @param quizID */ public void startNewActivity(String success, int quizID) { ((DefaultApplication)this.getApplication()).setSocketcode(quizID); // Zet de socketcode ((DefaultApplication)this.getApplication()).setDuration(bar.getProgress()); // Zet de quizduur in minuten Intent codeScreen = new Intent(this, QuizStart.class); // Intent met het wachtscherm startActivity(codeScreen); // Start het wachtscherm this.finish(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textProgress.setText(progress+ " MIN"); // Bij verandering van de balk, zet de actuele tijdinstelling } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
wildlands/wildlands-android
app/src/main/java/nl/wildlands/wildlandseducation/Activities/GenerateQuiz.java
1,678
// Actie bij het veranderen van de seekbar
line_comment
nl
package nl.wildlands.wildlandseducation.Activities; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import com.github.nkzawa.emitter.Emitter; import com.github.nkzawa.socketio.client.Socket; import org.json.JSONException; import org.json.JSONObject; import nl.wildlands.wildlandseducation.GlobalSettings.DefaultApplication; import nl.wildlands.wildlandseducation.R; /** * Activity waarbij de docent de gegevens van de quiz kan invoeren * en deze vervolgens d.m.v. socekts wordt aangemaakt */ public class GenerateQuiz extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener { ImageButton backBtn; // ImageButton om terug te gaan Button generateQuiz; // Button om quiz te genereren Socket mSocket; // Socket voor de quizverbinding private SeekBar bar; // Seekbar om tijd dynamisch in te stellen private TextView textProgress, genereerQuiz,tijd; // TextView voor weergave huidige tijdsinput /** * Actie die voltrokken wordt, als de socket een bepaald bericht krijgt */ private Emitter.Listener onNewMessage = new Emitter.Listener() { @Override public void call(final Object... args) { GenerateQuiz.this.runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; // Zet de data om in een JSONObject String success; // Succes van aanmaken int quizID; // ID van de gegenereerde quiz try { success = data.getString("success"); // Success message quizID = data.getInt("quizid"); // Quizid } catch (JSONException e) { return; } startNewActivity(success, quizID); // Roep startNewActivity aan met de waardes } }); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Zet layout setContentView(R.layout.activity_generate_quiz); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // Fullscreen WindowManager.LayoutParams.FLAG_FULLSCREEN); generateQuiz = (Button)findViewById(R.id.generateQuiz); // Button voor genereren quiz generateQuiz.setOnClickListener(this); // Activeer knopactie backBtn = (ImageButton)findViewById(R.id.quitbutton); // ImageButton om terug te gaan backBtn.setOnClickListener(this); // Activeer knopactie bar =(SeekBar)findViewById(R.id.seekBar1); // Seekbar om tijd in te stellen bar.setOnSeekBarChangeListener(this); // Actie bij<SUF> textProgress = (TextView)findViewById(R.id.textView3); // Tekst voor de actuele tijdsinstelling genereerQuiz = (TextView)findViewById(R.id.textView1); tijd = (TextView)findViewById(R.id.textView2); Typeface tf = DefaultApplication.tf2; // Verander de lettertypes genereerQuiz.setTypeface(tf); tijd.setTypeface(tf); Typeface tf2 = DefaultApplication.tf; // Verander de lettertypes generateQuiz.setTypeface(tf2); textProgress.setTypeface(tf2); mSocket = ((DefaultApplication)this.getApplicationContext()).getSocket(); // Vraag de centrale socket op mSocket.connect(); // Maak verbinding met de server } @Override public void onClick(View v) { switch(v.getId()) { case R.id.generateQuiz: // Genereer quiz ingedrukt mSocket.emit("createQuiz",""); // Verzend het verzoek om een quiz te maken startListening(); // Wacht op bevestiging break; case R.id.quitbutton: Intent i = new Intent(this, ChooseQuizGroup.class); // Backbutton gaat naar choose quiz group activity startActivity(i); this.finish(); // Beeindig deze activity break; } } public void startListening() { mSocket.on("quizCreated", onNewMessage); // Start de actie als de socket bevestiging krijgt } /** * Zet het quizid en de lengte van de quiz in de global variables * en start een nieuwe activity * @param success * @param quizID */ public void startNewActivity(String success, int quizID) { ((DefaultApplication)this.getApplication()).setSocketcode(quizID); // Zet de socketcode ((DefaultApplication)this.getApplication()).setDuration(bar.getProgress()); // Zet de quizduur in minuten Intent codeScreen = new Intent(this, QuizStart.class); // Intent met het wachtscherm startActivity(codeScreen); // Start het wachtscherm this.finish(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textProgress.setText(progress+ " MIN"); // Bij verandering van de balk, zet de actuele tijdinstelling } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
120436_33
/******************************************************************************* * Copyright 2009, 2017 Martin Davis * * 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.locationtech.proj4j; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.locationtech.proj4j.datum.Datum; import org.locationtech.proj4j.datum.Ellipsoid; import org.locationtech.proj4j.proj.*; /** * Supplies predefined values for various library classes * such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}. * * @author Martin Davis */ public class Registry { public Registry() { super(); initialize(); } public final static Datum[] datums = { Datum.WGS84, Datum.GGRS87, Datum.NAD27, Datum.NAD83, Datum.POTSDAM, Datum.CARTHAGE, Datum.HERMANNSKOGEL, Datum.IRE65, Datum.NZGD49, Datum.OSEB36 }; public Datum getDatum(String code) { for (int i = 0; i < datums.length; i++) { if (datums[i].getCode().equals(code)) { return datums[i]; } } return null; } public final static Ellipsoid[] ellipsoids = { Ellipsoid.SPHERE, new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"), new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"), Ellipsoid.GRS80, new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"), Ellipsoid.AIRY, Ellipsoid.MOD_AIRY, new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"), new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"), new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"), new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"), new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"), Ellipsoid.BESSEL, new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"), Ellipsoid.CLARKE_1866, Ellipsoid.CLARKE_1880, new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"), new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"), new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"), Ellipsoid.EVEREST, new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"), new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"), new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"), new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"), new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"), new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"), new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"), new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"), new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"), Ellipsoid.INTERNATIONAL, Ellipsoid.INTERNATIONAL_1967, Ellipsoid.KRASSOVSKY, new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"), new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"), new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"), new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"), new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"), new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"), Ellipsoid.WGS60, Ellipsoid.WGS66, Ellipsoid.WGS72, Ellipsoid.WGS84, new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."), new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"), }; public Ellipsoid getEllipsoid(String name) { for (int i = 0; i < ellipsoids.length; i++) { if (ellipsoids[i].shortName.equals(name)) { return ellipsoids[i]; } } return null; } private Map<String, Class> projRegistry; private void register(String name, Class cls, String description) { projRegistry.put(name, cls); } public Projection getProjection(String name) { // if ( projRegistry == null ) // initialize(); Class cls = (Class) projRegistry.get(name); if (cls != null) { try { Projection projection = (Projection) cls.newInstance(); if (projection != null) projection.setName(name); return projection; } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { System.err.println("Cannot instantiate projection " + name + " [" + cls.getName() + "]"); e.printStackTrace(); } } return null; } public List<Projection> getProjections() { List<Projection> projections = new ArrayList<>(); for (String name : projRegistry.keySet()) { Projection projection = getProjection(name); if (projection != null) { projections.add(projection); } } return projections; } private synchronized void initialize() { // guard against race condition if (projRegistry != null) return; projRegistry = new HashMap(); register("aea", AlbersProjection.class, "Albers Equal Area"); register("aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant"); register("airy", AiryProjection.class, "Airy"); register("aitoff", AitoffProjection.class, "Aitoff"); register("alsk", Projection.class, "Mod. Stereographics of Alaska"); register("apian", Projection.class, "Apian Globular I"); register("august", AugustProjection.class, "August Epicycloidal"); register("bacon", Projection.class, "Bacon Globular"); register("bipc", BipolarProjection.class, "Bipolar conic of western hemisphere"); register("boggs", BoggsProjection.class, "Boggs Eumorphic"); register("bonne", BonneProjection.class, "Bonne (Werner lat_1=90)"); register("cass", CassiniProjection.class, "Cassini"); register("cc", CentralCylindricalProjection.class, "Central Cylindrical"); register("cea", CylindricalEqualAreaProjection.class, "Equal Area Cylindrical"); // register( "chamb", Projection.class, "Chamberlin Trimetric" ); register("collg", CollignonProjection.class, "Collignon"); register("crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)"); register("denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical"); register("eck1", Eckert1Projection.class, "Eckert I"); register("eck2", Eckert2Projection.class, "Eckert II"); // register( "eck3", Eckert3Projection.class, "Eckert III" ); register("eck4", Eckert4Projection.class, "Eckert IV"); register("eck5", Eckert5Projection.class, "Eckert V"); register("eck6", Eckert6Projection.class, "Eckert VI"); register("eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)"); register("eqdc", EquidistantConicProjection.class, "Equidistant Conic"); register("euler", EulerProjection.class, "Euler"); register("fahey", FaheyProjection.class, "Fahey"); register("fouc", FoucautProjection.class, "Foucaut"); register("fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal"); register("gall", GallProjection.class, "Gall (Gall Stereographic)"); register("geos", GeostationarySatelliteProjection.class, "Geostationary Satellite"); // register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" ); // register( "gn_sinu", Projection.class, "General Sinusoidal Series" ); register("gnom", GnomonicAzimuthalProjection.class, "Gnomonic"); register("goode", GoodeProjection.class, "Goode Homolosine"); // register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." ); // register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." ); register("hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff"); register("hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area"); // register( "imw_p", Projection.class, "Internation Map of the World Polyconic" ); register("kav5", KavraiskyVProjection.class, "Kavraisky V"); // register( "kav7", Projection.class, "Kavraisky VII" ); register("krovak", KrovakProjection.class, "Krovak"); // register( "labrd", Projection.class, "Laborde" ); register("laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area"); register("lagrng", LagrangeProjection.class, "Lagrange"); register("larr", LarriveeProjection.class, "Larrivee"); register("lask", LaskowskiProjection.class, "Laskowski"); register("latlong", LongLatProjection.class, "Lat/Long (Geodetic alias)"); register("longlat", LongLatProjection.class, "Lat/Long (Geodetic alias)"); register("latlon", LongLatProjection.class, "Lat/Long (Geodetic alias)"); register("lonlat", LongLatProjection.class, "Lat/Long (Geodetic)"); register("lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic"); register("leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic"); // register( "lee_os", Projection.class, "Lee Oblated Stereographic" ); register("loxim", LoximuthalProjection.class, "Loximuthal"); register("lsat", LandsatProjection.class, "Space oblique for LANDSAT"); // register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" ); register("mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)"); register("mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic"); register("mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic"); // register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" ); register("merc", MercatorProjection.class, "Mercator"); // register( "mil_os", Projection.class, "Miller Oblated Stereographic" ); register("mill", MillerProjection.class, "Miller Cylindrical"); // register( "mpoly", Projection.class, "Modified Polyconic" ); register("moll", MolleweideProjection.class, "Mollweide"); register("murd1", Murdoch1Projection.class, "Murdoch I"); register("murd2", Murdoch2Projection.class, "Murdoch II"); register("murd3", Murdoch3Projection.class, "Murdoch III"); register("nell", NellProjection.class, "Nell"); // register( "nell_h", Projection.class, "Nell-Hammer" ); register("nicol", NicolosiProjection.class, "Nicolosi Globular"); register("nsper", PerspectiveProjection.class, "Near-sided perspective"); register("nzmg", NewZealandMapGridProjection.class, "New Zealand Map Grid"); // register( "ob_tran", Projection.class, "General Oblique Transformation" ); // register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" ); // register( "oea", Projection.class, "Oblated Equal Area" ); register("omerc", ObliqueMercatorProjection.class, "Oblique Mercator"); // register( "ortel", Projection.class, "Ortelius Oval" ); register("ortho", OrthographicAzimuthalProjection.class, "Orthographic"); register("pconic", PerspectiveConicProjection.class, "Perspective Conic"); register("poly", PolyconicProjection.class, "Polyconic (American)"); // register( "putp1", Projection.class, "Putnins P1" ); register("putp2", PutninsP2Projection.class, "Putnins P2"); // register( "putp3", Projection.class, "Putnins P3" ); // register( "putp3p", Projection.class, "Putnins P3'" ); register("putp4p", PutninsP4Projection.class, "Putnins P4'"); register("putp5", PutninsP5Projection.class, "Putnins P5"); register("putp5p", PutninsP5PProjection.class, "Putnins P5'"); // register( "putp6", Projection.class, "Putnins P6" ); // register( "putp6p", Projection.class, "Putnins P6'" ); register("qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic"); register("robin", RobinsonProjection.class, "Robinson"); register("rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic"); register("sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)"); register("somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator"); register("stere", StereographicAzimuthalProjection.class, "Stereographic"); register("sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative"); register("tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical"); register("tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area"); // register( "tissot", TissotProjection.class, "Tissot Conic" ); register("tmerc", TransverseMercatorProjection.class, "Transverse Mercator"); register("etmerc", ExtendedTransverseMercatorProjection.class, "Extended Transverse Mercator"); // register( "tpeqd", Projection.class, "Two Point Equidistant" ); // register( "tpers", Projection.class, "Tilted perspective" ); // register( "ups", Projection.class, "Universal Polar Stereographic" ); // register( "urm5", Projection.class, "Urmaev V" ); register("urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal"); register("utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)"); register("vandg", VanDerGrintenProjection.class, "van der Grinten (I)"); // register( "vandg2", Projection.class, "van der Grinten II" ); // register( "vandg3", Projection.class, "van der Grinten III" ); // register( "vandg4", Projection.class, "van der Grinten IV" ); register("vitk1", VitkovskyProjection.class, "Vitkovsky I"); register("wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)"); register("wag2", Wagner2Projection.class, "Wagner II"); register("wag3", Wagner3Projection.class, "Wagner III"); register("wag4", Wagner4Projection.class, "Wagner IV"); register("wag5", Wagner5Projection.class, "Wagner V"); // register( "wag6", Projection.class, "Wagner VI" ); register("wag7", Wagner7Projection.class, "Wagner VII"); register("weren", WerenskioldProjection.class, "Werenskiold I"); // register( "wink1", Projection.class, "Winkel I" ); // register( "wink2", Projection.class, "Winkel II" ); register("wintri", WinkelTripelProjection.class, "Winkel Tripel"); } }
willcohen/proj4j
src/main/java/org/locationtech/proj4j/Registry.java
5,531
// register( "vandg2", Projection.class, "van der Grinten II" );
line_comment
nl
/******************************************************************************* * Copyright 2009, 2017 Martin Davis * * 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.locationtech.proj4j; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.locationtech.proj4j.datum.Datum; import org.locationtech.proj4j.datum.Ellipsoid; import org.locationtech.proj4j.proj.*; /** * Supplies predefined values for various library classes * such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}. * * @author Martin Davis */ public class Registry { public Registry() { super(); initialize(); } public final static Datum[] datums = { Datum.WGS84, Datum.GGRS87, Datum.NAD27, Datum.NAD83, Datum.POTSDAM, Datum.CARTHAGE, Datum.HERMANNSKOGEL, Datum.IRE65, Datum.NZGD49, Datum.OSEB36 }; public Datum getDatum(String code) { for (int i = 0; i < datums.length; i++) { if (datums[i].getCode().equals(code)) { return datums[i]; } } return null; } public final static Ellipsoid[] ellipsoids = { Ellipsoid.SPHERE, new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"), new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"), Ellipsoid.GRS80, new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"), Ellipsoid.AIRY, Ellipsoid.MOD_AIRY, new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"), new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"), new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"), new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"), new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"), Ellipsoid.BESSEL, new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"), Ellipsoid.CLARKE_1866, Ellipsoid.CLARKE_1880, new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"), new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"), new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"), Ellipsoid.EVEREST, new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"), new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"), new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"), new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"), new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"), new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"), new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"), new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"), new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"), Ellipsoid.INTERNATIONAL, Ellipsoid.INTERNATIONAL_1967, Ellipsoid.KRASSOVSKY, new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"), new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"), new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"), new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"), new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"), new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"), Ellipsoid.WGS60, Ellipsoid.WGS66, Ellipsoid.WGS72, Ellipsoid.WGS84, new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."), new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"), }; public Ellipsoid getEllipsoid(String name) { for (int i = 0; i < ellipsoids.length; i++) { if (ellipsoids[i].shortName.equals(name)) { return ellipsoids[i]; } } return null; } private Map<String, Class> projRegistry; private void register(String name, Class cls, String description) { projRegistry.put(name, cls); } public Projection getProjection(String name) { // if ( projRegistry == null ) // initialize(); Class cls = (Class) projRegistry.get(name); if (cls != null) { try { Projection projection = (Projection) cls.newInstance(); if (projection != null) projection.setName(name); return projection; } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { System.err.println("Cannot instantiate projection " + name + " [" + cls.getName() + "]"); e.printStackTrace(); } } return null; } public List<Projection> getProjections() { List<Projection> projections = new ArrayList<>(); for (String name : projRegistry.keySet()) { Projection projection = getProjection(name); if (projection != null) { projections.add(projection); } } return projections; } private synchronized void initialize() { // guard against race condition if (projRegistry != null) return; projRegistry = new HashMap(); register("aea", AlbersProjection.class, "Albers Equal Area"); register("aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant"); register("airy", AiryProjection.class, "Airy"); register("aitoff", AitoffProjection.class, "Aitoff"); register("alsk", Projection.class, "Mod. Stereographics of Alaska"); register("apian", Projection.class, "Apian Globular I"); register("august", AugustProjection.class, "August Epicycloidal"); register("bacon", Projection.class, "Bacon Globular"); register("bipc", BipolarProjection.class, "Bipolar conic of western hemisphere"); register("boggs", BoggsProjection.class, "Boggs Eumorphic"); register("bonne", BonneProjection.class, "Bonne (Werner lat_1=90)"); register("cass", CassiniProjection.class, "Cassini"); register("cc", CentralCylindricalProjection.class, "Central Cylindrical"); register("cea", CylindricalEqualAreaProjection.class, "Equal Area Cylindrical"); // register( "chamb", Projection.class, "Chamberlin Trimetric" ); register("collg", CollignonProjection.class, "Collignon"); register("crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)"); register("denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical"); register("eck1", Eckert1Projection.class, "Eckert I"); register("eck2", Eckert2Projection.class, "Eckert II"); // register( "eck3", Eckert3Projection.class, "Eckert III" ); register("eck4", Eckert4Projection.class, "Eckert IV"); register("eck5", Eckert5Projection.class, "Eckert V"); register("eck6", Eckert6Projection.class, "Eckert VI"); register("eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)"); register("eqdc", EquidistantConicProjection.class, "Equidistant Conic"); register("euler", EulerProjection.class, "Euler"); register("fahey", FaheyProjection.class, "Fahey"); register("fouc", FoucautProjection.class, "Foucaut"); register("fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal"); register("gall", GallProjection.class, "Gall (Gall Stereographic)"); register("geos", GeostationarySatelliteProjection.class, "Geostationary Satellite"); // register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" ); // register( "gn_sinu", Projection.class, "General Sinusoidal Series" ); register("gnom", GnomonicAzimuthalProjection.class, "Gnomonic"); register("goode", GoodeProjection.class, "Goode Homolosine"); // register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." ); // register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." ); register("hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff"); register("hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area"); // register( "imw_p", Projection.class, "Internation Map of the World Polyconic" ); register("kav5", KavraiskyVProjection.class, "Kavraisky V"); // register( "kav7", Projection.class, "Kavraisky VII" ); register("krovak", KrovakProjection.class, "Krovak"); // register( "labrd", Projection.class, "Laborde" ); register("laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area"); register("lagrng", LagrangeProjection.class, "Lagrange"); register("larr", LarriveeProjection.class, "Larrivee"); register("lask", LaskowskiProjection.class, "Laskowski"); register("latlong", LongLatProjection.class, "Lat/Long (Geodetic alias)"); register("longlat", LongLatProjection.class, "Lat/Long (Geodetic alias)"); register("latlon", LongLatProjection.class, "Lat/Long (Geodetic alias)"); register("lonlat", LongLatProjection.class, "Lat/Long (Geodetic)"); register("lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic"); register("leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic"); // register( "lee_os", Projection.class, "Lee Oblated Stereographic" ); register("loxim", LoximuthalProjection.class, "Loximuthal"); register("lsat", LandsatProjection.class, "Space oblique for LANDSAT"); // register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" ); register("mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)"); register("mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic"); register("mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic"); // register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" ); register("merc", MercatorProjection.class, "Mercator"); // register( "mil_os", Projection.class, "Miller Oblated Stereographic" ); register("mill", MillerProjection.class, "Miller Cylindrical"); // register( "mpoly", Projection.class, "Modified Polyconic" ); register("moll", MolleweideProjection.class, "Mollweide"); register("murd1", Murdoch1Projection.class, "Murdoch I"); register("murd2", Murdoch2Projection.class, "Murdoch II"); register("murd3", Murdoch3Projection.class, "Murdoch III"); register("nell", NellProjection.class, "Nell"); // register( "nell_h", Projection.class, "Nell-Hammer" ); register("nicol", NicolosiProjection.class, "Nicolosi Globular"); register("nsper", PerspectiveProjection.class, "Near-sided perspective"); register("nzmg", NewZealandMapGridProjection.class, "New Zealand Map Grid"); // register( "ob_tran", Projection.class, "General Oblique Transformation" ); // register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" ); // register( "oea", Projection.class, "Oblated Equal Area" ); register("omerc", ObliqueMercatorProjection.class, "Oblique Mercator"); // register( "ortel", Projection.class, "Ortelius Oval" ); register("ortho", OrthographicAzimuthalProjection.class, "Orthographic"); register("pconic", PerspectiveConicProjection.class, "Perspective Conic"); register("poly", PolyconicProjection.class, "Polyconic (American)"); // register( "putp1", Projection.class, "Putnins P1" ); register("putp2", PutninsP2Projection.class, "Putnins P2"); // register( "putp3", Projection.class, "Putnins P3" ); // register( "putp3p", Projection.class, "Putnins P3'" ); register("putp4p", PutninsP4Projection.class, "Putnins P4'"); register("putp5", PutninsP5Projection.class, "Putnins P5"); register("putp5p", PutninsP5PProjection.class, "Putnins P5'"); // register( "putp6", Projection.class, "Putnins P6" ); // register( "putp6p", Projection.class, "Putnins P6'" ); register("qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic"); register("robin", RobinsonProjection.class, "Robinson"); register("rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic"); register("sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)"); register("somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator"); register("stere", StereographicAzimuthalProjection.class, "Stereographic"); register("sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative"); register("tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical"); register("tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area"); // register( "tissot", TissotProjection.class, "Tissot Conic" ); register("tmerc", TransverseMercatorProjection.class, "Transverse Mercator"); register("etmerc", ExtendedTransverseMercatorProjection.class, "Extended Transverse Mercator"); // register( "tpeqd", Projection.class, "Two Point Equidistant" ); // register( "tpers", Projection.class, "Tilted perspective" ); // register( "ups", Projection.class, "Universal Polar Stereographic" ); // register( "urm5", Projection.class, "Urmaev V" ); register("urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal"); register("utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)"); register("vandg", VanDerGrintenProjection.class, "van der Grinten (I)"); // register( "vandg2",<SUF> // register( "vandg3", Projection.class, "van der Grinten III" ); // register( "vandg4", Projection.class, "van der Grinten IV" ); register("vitk1", VitkovskyProjection.class, "Vitkovsky I"); register("wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)"); register("wag2", Wagner2Projection.class, "Wagner II"); register("wag3", Wagner3Projection.class, "Wagner III"); register("wag4", Wagner4Projection.class, "Wagner IV"); register("wag5", Wagner5Projection.class, "Wagner V"); // register( "wag6", Projection.class, "Wagner VI" ); register("wag7", Wagner7Projection.class, "Wagner VII"); register("weren", WerenskioldProjection.class, "Werenskiold I"); // register( "wink1", Projection.class, "Winkel I" ); // register( "wink2", Projection.class, "Winkel II" ); register("wintri", WinkelTripelProjection.class, "Winkel Tripel"); } }
110989_6
package com.willdingle.jerfygame.areas; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.willdingle.jerfygame.HitBox; import com.willdingle.jerfygame.JerfyGame; import com.willdingle.jerfygame.TextBox; import com.willdingle.jerfygame.entities.*; import com.willdingle.jerfygame.items.Coin; import com.willdingle.jerfygame.menus.InventoryMenu; import com.willdingle.jerfygame.menus.PauseMenu; public class TownTown implements Screen { final JerfyGame game; private TiledMap map; private TiledMapTileLayer mapLayer; private OrthogonalTiledMapRenderer renderer; private OrthographicCamera cam; private Player player; private TextBox txtBox; private ShapeRenderer shRen; private BitmapFont font; private SpriteBatch batch; private boolean moveAllowed; private boolean showNeeded; private MovingNPC buggo; private StillNPC chocm, paper, donker; public MovingNPC movingNPCs[]; public StillNPC stillNPCs[]; private Coin[] coins; private float plx, ply; public TownTown(final JerfyGame game, float plx, float ply, String[][] inv) { this.game = game; map = new TmxMapLoader().load("maps/TownTown.tmx"); mapLayer = (TiledMapTileLayer) map.getLayers().get(0); renderer = new OrthogonalTiledMapRenderer(map); cam = new OrthographicCamera(Gdx.graphics.getWidth() / 4, Gdx.graphics.getHeight() / 4); cam.position.x = cam.viewportWidth / 2; cam.position.y = cam.viewportHeight / 2; cam.update(); player = new Player(mapLayer, plx, ply, inv); movingNPCs = new MovingNPC[1]; stillNPCs = new StillNPC[2]; buggo = new MovingNPC("buggo/0.png", mapLayer, 1, 6, 1, 5, 4); movingNPCs[0] = buggo; chocm = new StillNPC("doggo/chocm.png", mapLayer, 2, 10); stillNPCs[0] = chocm; donker = new StillNPC("donker.png", mapLayer, 16, 10); stillNPCs[1] = donker; coins = new Coin[5]; coins[0] = new Coin(mapLayer, 5, 5); coins[1] = new Coin(mapLayer, 15, 15); coins[2] = new Coin(mapLayer, 5, 7); coins[3] = new Coin(mapLayer, 23, 10); coins[4] = new Coin(mapLayer, 22, 9); game.parameter.size = 70; font = game.generator.generateFont(game.parameter); batch = new SpriteBatch(); shRen = new ShapeRenderer(); moveAllowed = true; showNeeded = false; } @Override public void show() { if(showNeeded) { this.player.setX(plx); this.player.setY(ply); this.player.setColLayer(mapLayer); showNeeded = false; } } @Override public void render(float delta) { Gdx.gl.glClearColor(44/255f, 120/255f, 213/255f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //Camera cam.position.set(player.getX() + player.getWidth() / 2, player.getY() + player.getHeight() / 2, 0); cam.update(); renderer.setView(cam); renderer.render(); //Draw sprites and player control renderer.getBatch().begin(); player.draw(renderer.getBatch()); if (moveAllowed) player.move(Gdx.graphics.getDeltaTime(), movingNPCs, stillNPCs, null); buggo.draw(renderer.getBatch()); chocm.draw(renderer.getBatch()); donker.draw(renderer.getBatch()); if(coins.length > 0) { for(int n = 0; n < coins.length; n++) { if(coins[n] != null) { coins[n].draw(renderer.getBatch()); } } } renderer.getBatch().end(); if(Gdx.input.isKeyJustPressed(Keys.ENTER)) interact(); if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)) game.setScreen(new PauseMenu(game, game.getScreen())); if(Gdx.input.isKeyJustPressed(Keys.E)) game.setScreen(new InventoryMenu(game, game.getScreen(), player)); //Pick up items if(coins.length > 0) { for(int n = 0; n < coins.length; n++) { if(coins[n] != null) { if(coins[n].touched(player)) { player.setMoney(player.getMoney() + 1); coins[n] = null; break; } } } } //Draw text box if(txtBox != null) txtBox.render(); //Draw HUD game.hud.draw(batch, player); } private void interact() { if (txtBox != null) { moveAllowed = true; txtBox = null; //Welcome sign } else if (HitBox.player(player, 48, 48, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Welcome to Town Town!"); moveAllowed = false; //Speak to chocm } else if (HitBox.player(player, chocm.getX(), chocm.getY(), chocm.getWidth(), chocm.getHeight(), HitBox.ALL, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Is doggo"); moveAllowed = false; //Donker's house sign } else if(HitBox.player(player, 11*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Donker's House"); moveAllowed = false; //Donker's door } else if(HitBox.player(player, 9*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { //set screen to donker's house plx = player.getX(); ply = player.getY(); showNeeded = true; StillNPC donkerClone = new StillNPC("donker.png", mapLayer, 10, 10); game.setScreen(new House("DonkerHouse.tmx", game, this, player, cam, donkerClone, txtBox, shRen, batch, font)); //Paper's house sign } else if(HitBox.player(player, 17*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Paper's House"); moveAllowed = false; //Paper's door } else if(HitBox.player(player, 15*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { //set screen to paper's house plx = player.getX(); ply = player.getY(); showNeeded = true; paper = new StillNPC("doggo/paper.png", mapLayer, 10, 10); game.setScreen(new House("PaperHouse.tmx", game, this, player, cam, paper, txtBox, shRen, batch, font)); //Buggo's house sign } else if(HitBox.player(player, 23*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Buggo's House"); moveAllowed = false; //Buggo's door } else if(HitBox.player(player, 21*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { //set screen to buggo's house plx = player.getX(); ply = player.getY(); showNeeded = true; StillNPC buggoStill = new StillNPC("buggo/0.png", mapLayer, 10, 10); game.setScreen(new House("BuggoHouse.tmx", game, this, player, cam, buggoStill, txtBox, shRen, batch, font)); //End door } else if(HitBox.player(player, 21*16, 17*16, 32, 48, HitBox.ALL, HitBox.INTERACT)) { if(player.inventoryContains("gem 1") && player.inventoryContains("gem 2")) { plx = player.getX(); ply = player.getY(); showNeeded = true; game.setScreen(new EndArea(game, player, this)); } else { txtBox = new TextBox(batch, shRen, font, "*You do not have the required gems to open this door!*"); } } } @Override public void pause() { } @Override public void resize(int width, int height) { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { map.dispose(); renderer.dispose(); batch.dispose(); } }
willdingle/JerfyGame
core/src/com/willdingle/jerfygame/areas/TownTown.java
2,999
//set screen to donker's house
line_comment
nl
package com.willdingle.jerfygame.areas; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.willdingle.jerfygame.HitBox; import com.willdingle.jerfygame.JerfyGame; import com.willdingle.jerfygame.TextBox; import com.willdingle.jerfygame.entities.*; import com.willdingle.jerfygame.items.Coin; import com.willdingle.jerfygame.menus.InventoryMenu; import com.willdingle.jerfygame.menus.PauseMenu; public class TownTown implements Screen { final JerfyGame game; private TiledMap map; private TiledMapTileLayer mapLayer; private OrthogonalTiledMapRenderer renderer; private OrthographicCamera cam; private Player player; private TextBox txtBox; private ShapeRenderer shRen; private BitmapFont font; private SpriteBatch batch; private boolean moveAllowed; private boolean showNeeded; private MovingNPC buggo; private StillNPC chocm, paper, donker; public MovingNPC movingNPCs[]; public StillNPC stillNPCs[]; private Coin[] coins; private float plx, ply; public TownTown(final JerfyGame game, float plx, float ply, String[][] inv) { this.game = game; map = new TmxMapLoader().load("maps/TownTown.tmx"); mapLayer = (TiledMapTileLayer) map.getLayers().get(0); renderer = new OrthogonalTiledMapRenderer(map); cam = new OrthographicCamera(Gdx.graphics.getWidth() / 4, Gdx.graphics.getHeight() / 4); cam.position.x = cam.viewportWidth / 2; cam.position.y = cam.viewportHeight / 2; cam.update(); player = new Player(mapLayer, plx, ply, inv); movingNPCs = new MovingNPC[1]; stillNPCs = new StillNPC[2]; buggo = new MovingNPC("buggo/0.png", mapLayer, 1, 6, 1, 5, 4); movingNPCs[0] = buggo; chocm = new StillNPC("doggo/chocm.png", mapLayer, 2, 10); stillNPCs[0] = chocm; donker = new StillNPC("donker.png", mapLayer, 16, 10); stillNPCs[1] = donker; coins = new Coin[5]; coins[0] = new Coin(mapLayer, 5, 5); coins[1] = new Coin(mapLayer, 15, 15); coins[2] = new Coin(mapLayer, 5, 7); coins[3] = new Coin(mapLayer, 23, 10); coins[4] = new Coin(mapLayer, 22, 9); game.parameter.size = 70; font = game.generator.generateFont(game.parameter); batch = new SpriteBatch(); shRen = new ShapeRenderer(); moveAllowed = true; showNeeded = false; } @Override public void show() { if(showNeeded) { this.player.setX(plx); this.player.setY(ply); this.player.setColLayer(mapLayer); showNeeded = false; } } @Override public void render(float delta) { Gdx.gl.glClearColor(44/255f, 120/255f, 213/255f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //Camera cam.position.set(player.getX() + player.getWidth() / 2, player.getY() + player.getHeight() / 2, 0); cam.update(); renderer.setView(cam); renderer.render(); //Draw sprites and player control renderer.getBatch().begin(); player.draw(renderer.getBatch()); if (moveAllowed) player.move(Gdx.graphics.getDeltaTime(), movingNPCs, stillNPCs, null); buggo.draw(renderer.getBatch()); chocm.draw(renderer.getBatch()); donker.draw(renderer.getBatch()); if(coins.length > 0) { for(int n = 0; n < coins.length; n++) { if(coins[n] != null) { coins[n].draw(renderer.getBatch()); } } } renderer.getBatch().end(); if(Gdx.input.isKeyJustPressed(Keys.ENTER)) interact(); if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)) game.setScreen(new PauseMenu(game, game.getScreen())); if(Gdx.input.isKeyJustPressed(Keys.E)) game.setScreen(new InventoryMenu(game, game.getScreen(), player)); //Pick up items if(coins.length > 0) { for(int n = 0; n < coins.length; n++) { if(coins[n] != null) { if(coins[n].touched(player)) { player.setMoney(player.getMoney() + 1); coins[n] = null; break; } } } } //Draw text box if(txtBox != null) txtBox.render(); //Draw HUD game.hud.draw(batch, player); } private void interact() { if (txtBox != null) { moveAllowed = true; txtBox = null; //Welcome sign } else if (HitBox.player(player, 48, 48, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Welcome to Town Town!"); moveAllowed = false; //Speak to chocm } else if (HitBox.player(player, chocm.getX(), chocm.getY(), chocm.getWidth(), chocm.getHeight(), HitBox.ALL, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Is doggo"); moveAllowed = false; //Donker's house sign } else if(HitBox.player(player, 11*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Donker's House"); moveAllowed = false; //Donker's door } else if(HitBox.player(player, 9*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { //set screen<SUF> plx = player.getX(); ply = player.getY(); showNeeded = true; StillNPC donkerClone = new StillNPC("donker.png", mapLayer, 10, 10); game.setScreen(new House("DonkerHouse.tmx", game, this, player, cam, donkerClone, txtBox, shRen, batch, font)); //Paper's house sign } else if(HitBox.player(player, 17*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Paper's House"); moveAllowed = false; //Paper's door } else if(HitBox.player(player, 15*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { //set screen to paper's house plx = player.getX(); ply = player.getY(); showNeeded = true; paper = new StillNPC("doggo/paper.png", mapLayer, 10, 10); game.setScreen(new House("PaperHouse.tmx", game, this, player, cam, paper, txtBox, shRen, batch, font)); //Buggo's house sign } else if(HitBox.player(player, 23*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { txtBox = new TextBox(batch, shRen, font, "Buggo's House"); moveAllowed = false; //Buggo's door } else if(HitBox.player(player, 21*16, 4*16, 16, 16, HitBox.UP, HitBox.INTERACT)) { //set screen to buggo's house plx = player.getX(); ply = player.getY(); showNeeded = true; StillNPC buggoStill = new StillNPC("buggo/0.png", mapLayer, 10, 10); game.setScreen(new House("BuggoHouse.tmx", game, this, player, cam, buggoStill, txtBox, shRen, batch, font)); //End door } else if(HitBox.player(player, 21*16, 17*16, 32, 48, HitBox.ALL, HitBox.INTERACT)) { if(player.inventoryContains("gem 1") && player.inventoryContains("gem 2")) { plx = player.getX(); ply = player.getY(); showNeeded = true; game.setScreen(new EndArea(game, player, this)); } else { txtBox = new TextBox(batch, shRen, font, "*You do not have the required gems to open this door!*"); } } } @Override public void pause() { } @Override public void resize(int width, int height) { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { map.dispose(); renderer.dispose(); batch.dispose(); } }
178230_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gameobject.main; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; /** * * @author wdevoogd */ public class Recources { private BufferedImage[] images = new BufferedImage[10]; private BufferedImage projectiles = null; private BufferedImage bullets; private BufferedImage healthBarFull; private BufferedImage healthBarEmpty; public Recources() { try { projectiles = ImageIO.read(getClass().getResource("/projectiles.png")); healthBarEmpty = ImageIO.read(getClass().getResource("/healthbarE.png")); healthBarFull = ImageIO.read(getClass().getResource("/healthbarF.png")); bullets = ImageIO.read(getClass().getResource("/bullets.png")); } catch (IOException ex) { Logger.getLogger(Graphics.class.getName()).log(Level.SEVERE, null, ex); } images[0] = projectiles.getSubimage(0, 0, 50, 50); //big red bullet images[1] = projectiles.getSubimage(50, 0, 50, 50); //big green bullet images[2] = projectiles.getSubimage(150, 0, 50, 50); // big red laser images[3] = projectiles.getSubimage(200, 0, 50, 50); //big green laser images[4] = healthBarFull; images[5] = healthBarEmpty; images[6] = bullets.getSubimage(0, 0, 20, 20); //rood images[7] = bullets.getSubimage(20, 0, 20, 20); //groen images[8] = bullets.getSubimage(40, 0, 20, 20); //blauw images[9] = bullets.getSubimage(60, 0, 20, 20); //combo } public BufferedImage getImage(int i) { if (i < images.length) { return images[i]; } else { return images[0]; } } }
willemdv/spaceshooter
gameobject/main/Recources.java
613
/** * * @author wdevoogd */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gameobject.main; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; /** * * @author wdevoogd <SUF>*/ public class Recources { private BufferedImage[] images = new BufferedImage[10]; private BufferedImage projectiles = null; private BufferedImage bullets; private BufferedImage healthBarFull; private BufferedImage healthBarEmpty; public Recources() { try { projectiles = ImageIO.read(getClass().getResource("/projectiles.png")); healthBarEmpty = ImageIO.read(getClass().getResource("/healthbarE.png")); healthBarFull = ImageIO.read(getClass().getResource("/healthbarF.png")); bullets = ImageIO.read(getClass().getResource("/bullets.png")); } catch (IOException ex) { Logger.getLogger(Graphics.class.getName()).log(Level.SEVERE, null, ex); } images[0] = projectiles.getSubimage(0, 0, 50, 50); //big red bullet images[1] = projectiles.getSubimage(50, 0, 50, 50); //big green bullet images[2] = projectiles.getSubimage(150, 0, 50, 50); // big red laser images[3] = projectiles.getSubimage(200, 0, 50, 50); //big green laser images[4] = healthBarFull; images[5] = healthBarEmpty; images[6] = bullets.getSubimage(0, 0, 20, 20); //rood images[7] = bullets.getSubimage(20, 0, 20, 20); //groen images[8] = bullets.getSubimage(40, 0, 20, 20); //blauw images[9] = bullets.getSubimage(60, 0, 20, 20); //combo } public BufferedImage getImage(int i) { if (i < images.length) { return images[i]; } else { return images[0]; } } }
84249_0
package org.apache.jen3.reasoner.rulesys.builtins.n3.def.ic; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import org.apache.jen3.graph.Graph; import org.apache.jen3.graph.Node; import org.apache.jen3.reasoner.rulesys.builtins.n3.def.ic.result.ICCompositeConvert; import org.apache.jen3.reasoner.rulesys.builtins.n3.def.ic.result.ICConvert; public abstract class CompositeIC extends InputConstraint { private static final long serialVersionUID = -3276802685921580625L; private Cardinality size; private InputConstraint elementType; private List<InputConstraint> elements; private int curId; private ICTrace curTrace; private Graph curGraph; private ICCompositeConvert inputs; public CompositeIC(DefaultICs type) { super(type); } public CompositeIC(DefaultICs type, Cardinality size, InputConstraint elementType, List<InputConstraint> elements) { this.type = type; this.size = size; this.elementType = elementType; this.elements = elements; } public boolean hasSize() { return size != null; } public Cardinality getSize() { return size; } public void setSize(Cardinality size) { this.size = size; } public boolean hasElementType() { return elementType != null; } public InputConstraint getElementType() { return elementType; } public void setElementType(InputConstraint elementType) { this.elementType = elementType; } public boolean hasElements() { return elements != null && !elements.isEmpty(); } public void add(InputConstraint tr) { if (elements == null) elements = new ArrayList<>(); elements.add(tr); } public List<InputConstraint> getElements() { return elements; } public void setElements(List<InputConstraint> elements) { this.elements = elements; } @Override protected boolean doCheck(Node n, int id, Graph graph, ICTrace trace) { if (!checkCompositeType(n)) return false; init(id, trace, graph); return process(n, this::checkElFn, this::checkElTypeFn, trace); } // don't do separate check (avoid going over elements twice) // instead, just do all work in one go, incl. checking @Override protected ICConvert doConvert(Node n, int id, Graph graph, ICTrace trace) { if (!checkCompositeType(n)) return noMatch; init(id, trace, graph); return (process(n, this::convertElFn, this::convertElTypeFn, trace) ? inputs : noMatch); } // - checking private boolean checkElFn(InputConstraint d, Node ln) { return d.check(ln, curId, curGraph, curTrace); } private boolean checkElTypeFn(Node ln) { return elementType.check(ln, curId, curGraph, curTrace); } // - converting private boolean handleInput(ICConvert input) { if (input.isSuccess()) { inputs.add(input); return true; } else return false; } private boolean convertElFn(InputConstraint d, Node ln) { return handleInput(d.convert(ln, curId, curGraph, curTrace)); } private boolean convertElTypeFn(Node ln) { return handleInput(elementType.convert(ln, curId, curGraph, curTrace)); } private void init(int id, ICTrace trace, Graph graph) { this.curId = id; this.curTrace = trace; this.curGraph = graph; } protected abstract boolean checkCompositeType(Node n); protected abstract ICCompositeConvert getCompositeConvert(); protected abstract ICCompositeConvert getCompositeConvert(Node n); protected abstract List<Node> getCompositeElements(Node n); private boolean process(Node n, BiFunction<InputConstraint, Node, Boolean> elFn, Function<Node, Boolean> elDomFn, ICTrace trace) { List<Node> list = getCompositeElements(n); if (size != null && !size.matches(list.size(), true)) return false; Iterator<Node> listIt = list.iterator(); if (hasElements() || hasElementType()) { this.inputs = getCompositeConvert(); if (hasElements()) return processElements(listIt, elFn, trace); else if (hasElementType()) return processElementType(listIt, elDomFn, trace); } else this.inputs = getCompositeConvert(n); return true; } private boolean processElements(Iterator<Node> listIt, BiFunction<InputConstraint, Node, Boolean> fn, ICTrace trace) { Iterator<InputConstraint> it = elements.iterator(); while (it.hasNext()) { if (!listIt.hasNext()) return false; InputConstraint d = it.next(); Node ln = listIt.next(); if (!fn.apply(d, ln)) return false; } if (listIt.hasNext()) return false; return true; } private boolean processElementType(Iterator<Node> listIt, Function<Node, Boolean> fn, ICTrace trace) { while (listIt.hasNext()) { Node ln = listIt.next(); boolean ret = fn.apply(ln); if (!ret) return false; } return true; } public String toString() { String ret = "<" + type + (cardinality != null ? " (" + cardinality + ")" : ""); if (size != null) ret += " ; size = " + size; if (hasElementType()) ret += " ; elementType = " + elementType; if (hasElements()) ret += " ; elements = " + elements; ret += ">"; return ret; } }
william-vw/jen3
src/main/java/org/apache/jen3/reasoner/rulesys/builtins/n3/def/ic/CompositeIC.java
1,617
// don't do separate check (avoid going over elements twice)
line_comment
nl
package org.apache.jen3.reasoner.rulesys.builtins.n3.def.ic; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import org.apache.jen3.graph.Graph; import org.apache.jen3.graph.Node; import org.apache.jen3.reasoner.rulesys.builtins.n3.def.ic.result.ICCompositeConvert; import org.apache.jen3.reasoner.rulesys.builtins.n3.def.ic.result.ICConvert; public abstract class CompositeIC extends InputConstraint { private static final long serialVersionUID = -3276802685921580625L; private Cardinality size; private InputConstraint elementType; private List<InputConstraint> elements; private int curId; private ICTrace curTrace; private Graph curGraph; private ICCompositeConvert inputs; public CompositeIC(DefaultICs type) { super(type); } public CompositeIC(DefaultICs type, Cardinality size, InputConstraint elementType, List<InputConstraint> elements) { this.type = type; this.size = size; this.elementType = elementType; this.elements = elements; } public boolean hasSize() { return size != null; } public Cardinality getSize() { return size; } public void setSize(Cardinality size) { this.size = size; } public boolean hasElementType() { return elementType != null; } public InputConstraint getElementType() { return elementType; } public void setElementType(InputConstraint elementType) { this.elementType = elementType; } public boolean hasElements() { return elements != null && !elements.isEmpty(); } public void add(InputConstraint tr) { if (elements == null) elements = new ArrayList<>(); elements.add(tr); } public List<InputConstraint> getElements() { return elements; } public void setElements(List<InputConstraint> elements) { this.elements = elements; } @Override protected boolean doCheck(Node n, int id, Graph graph, ICTrace trace) { if (!checkCompositeType(n)) return false; init(id, trace, graph); return process(n, this::checkElFn, this::checkElTypeFn, trace); } // don't do<SUF> // instead, just do all work in one go, incl. checking @Override protected ICConvert doConvert(Node n, int id, Graph graph, ICTrace trace) { if (!checkCompositeType(n)) return noMatch; init(id, trace, graph); return (process(n, this::convertElFn, this::convertElTypeFn, trace) ? inputs : noMatch); } // - checking private boolean checkElFn(InputConstraint d, Node ln) { return d.check(ln, curId, curGraph, curTrace); } private boolean checkElTypeFn(Node ln) { return elementType.check(ln, curId, curGraph, curTrace); } // - converting private boolean handleInput(ICConvert input) { if (input.isSuccess()) { inputs.add(input); return true; } else return false; } private boolean convertElFn(InputConstraint d, Node ln) { return handleInput(d.convert(ln, curId, curGraph, curTrace)); } private boolean convertElTypeFn(Node ln) { return handleInput(elementType.convert(ln, curId, curGraph, curTrace)); } private void init(int id, ICTrace trace, Graph graph) { this.curId = id; this.curTrace = trace; this.curGraph = graph; } protected abstract boolean checkCompositeType(Node n); protected abstract ICCompositeConvert getCompositeConvert(); protected abstract ICCompositeConvert getCompositeConvert(Node n); protected abstract List<Node> getCompositeElements(Node n); private boolean process(Node n, BiFunction<InputConstraint, Node, Boolean> elFn, Function<Node, Boolean> elDomFn, ICTrace trace) { List<Node> list = getCompositeElements(n); if (size != null && !size.matches(list.size(), true)) return false; Iterator<Node> listIt = list.iterator(); if (hasElements() || hasElementType()) { this.inputs = getCompositeConvert(); if (hasElements()) return processElements(listIt, elFn, trace); else if (hasElementType()) return processElementType(listIt, elDomFn, trace); } else this.inputs = getCompositeConvert(n); return true; } private boolean processElements(Iterator<Node> listIt, BiFunction<InputConstraint, Node, Boolean> fn, ICTrace trace) { Iterator<InputConstraint> it = elements.iterator(); while (it.hasNext()) { if (!listIt.hasNext()) return false; InputConstraint d = it.next(); Node ln = listIt.next(); if (!fn.apply(d, ln)) return false; } if (listIt.hasNext()) return false; return true; } private boolean processElementType(Iterator<Node> listIt, Function<Node, Boolean> fn, ICTrace trace) { while (listIt.hasNext()) { Node ln = listIt.next(); boolean ret = fn.apply(ln); if (!ret) return false; } return true; } public String toString() { String ret = "<" + type + (cardinality != null ? " (" + cardinality + ")" : ""); if (size != null) ret += " ; size = " + size; if (hasElementType()) ret += " ; elementType = " + elementType; if (hasElements()) ret += " ; elements = " + elements; ret += ">"; return ret; } }
181382_10
/** * This algorithm finds the center(s) of a tree. * * <p>Time complexity: O(V+E) * * @author Original author: Jeffrey Xiao, https://github.com/jeffrey-xiao * @author Modifications by: William Fiset, [email protected] */ package com.williamfiset.algorithms.graphtheory.treealgorithms; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class TreeCenter { public static List<Integer> findTreeCenters(List<List<Integer>> tree) { final int n = tree.size(); int[] degree = new int[n]; // Find all leaf nodes List<Integer> leaves = new ArrayList<>(); for (int i = 0; i < n; i++) { List<Integer> edges = tree.get(i); degree[i] = edges.size(); if (degree[i] <= 1) { leaves.add(i); degree[i] = 0; } } int processedLeafs = leaves.size(); // Remove leaf nodes and decrease the degree of each node adding new leaf nodes progressively // until only the centers remain. while (processedLeafs < n) { List<Integer> newLeaves = new ArrayList<>(); for (int node : leaves) { for (int neighbor : tree.get(node)) { if (--degree[neighbor] == 1) { newLeaves.add(neighbor); } } degree[node] = 0; } processedLeafs += newLeaves.size(); leaves = newLeaves; } return leaves; } /** ********** TESTING ********* */ // Create an empty tree as a adjacency list. public static List<List<Integer>> createEmptyTree(int n) { List<List<Integer>> tree = new ArrayList<>(n); for (int i = 0; i < n; i++) tree.add(new LinkedList<>()); return tree; } public static void addUndirectedEdge(List<List<Integer>> tree, int from, int to) { tree.get(from).add(to); tree.get(to).add(from); } public static void main(String[] args) { List<List<Integer>> graph = createEmptyTree(9); addUndirectedEdge(graph, 0, 1); addUndirectedEdge(graph, 2, 1); addUndirectedEdge(graph, 2, 3); addUndirectedEdge(graph, 3, 4); addUndirectedEdge(graph, 5, 3); addUndirectedEdge(graph, 2, 6); addUndirectedEdge(graph, 6, 7); addUndirectedEdge(graph, 6, 8); // Centers are 2 System.out.println(findTreeCenters(graph)); // Centers are 0 List<List<Integer>> graph2 = createEmptyTree(1); System.out.println(findTreeCenters(graph2)); // Centers are 0,1 List<List<Integer>> graph3 = createEmptyTree(2); addUndirectedEdge(graph3, 0, 1); System.out.println(findTreeCenters(graph3)); // Centers are 1 List<List<Integer>> graph4 = createEmptyTree(3); addUndirectedEdge(graph4, 0, 1); addUndirectedEdge(graph4, 1, 2); System.out.println(findTreeCenters(graph4)); // Centers are 1,2 List<List<Integer>> graph5 = createEmptyTree(4); addUndirectedEdge(graph5, 0, 1); addUndirectedEdge(graph5, 1, 2); addUndirectedEdge(graph5, 2, 3); System.out.println(findTreeCenters(graph5)); // Centers are 2,3 List<List<Integer>> graph6 = createEmptyTree(7); addUndirectedEdge(graph6, 0, 1); addUndirectedEdge(graph6, 1, 2); addUndirectedEdge(graph6, 2, 3); addUndirectedEdge(graph6, 3, 4); addUndirectedEdge(graph6, 4, 5); addUndirectedEdge(graph6, 4, 6); System.out.println(findTreeCenters(graph6)); } }
williamfiset/Algorithms
src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenter.java
1,206
// Centers are 2,3
line_comment
nl
/** * This algorithm finds the center(s) of a tree. * * <p>Time complexity: O(V+E) * * @author Original author: Jeffrey Xiao, https://github.com/jeffrey-xiao * @author Modifications by: William Fiset, [email protected] */ package com.williamfiset.algorithms.graphtheory.treealgorithms; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class TreeCenter { public static List<Integer> findTreeCenters(List<List<Integer>> tree) { final int n = tree.size(); int[] degree = new int[n]; // Find all leaf nodes List<Integer> leaves = new ArrayList<>(); for (int i = 0; i < n; i++) { List<Integer> edges = tree.get(i); degree[i] = edges.size(); if (degree[i] <= 1) { leaves.add(i); degree[i] = 0; } } int processedLeafs = leaves.size(); // Remove leaf nodes and decrease the degree of each node adding new leaf nodes progressively // until only the centers remain. while (processedLeafs < n) { List<Integer> newLeaves = new ArrayList<>(); for (int node : leaves) { for (int neighbor : tree.get(node)) { if (--degree[neighbor] == 1) { newLeaves.add(neighbor); } } degree[node] = 0; } processedLeafs += newLeaves.size(); leaves = newLeaves; } return leaves; } /** ********** TESTING ********* */ // Create an empty tree as a adjacency list. public static List<List<Integer>> createEmptyTree(int n) { List<List<Integer>> tree = new ArrayList<>(n); for (int i = 0; i < n; i++) tree.add(new LinkedList<>()); return tree; } public static void addUndirectedEdge(List<List<Integer>> tree, int from, int to) { tree.get(from).add(to); tree.get(to).add(from); } public static void main(String[] args) { List<List<Integer>> graph = createEmptyTree(9); addUndirectedEdge(graph, 0, 1); addUndirectedEdge(graph, 2, 1); addUndirectedEdge(graph, 2, 3); addUndirectedEdge(graph, 3, 4); addUndirectedEdge(graph, 5, 3); addUndirectedEdge(graph, 2, 6); addUndirectedEdge(graph, 6, 7); addUndirectedEdge(graph, 6, 8); // Centers are 2 System.out.println(findTreeCenters(graph)); // Centers are 0 List<List<Integer>> graph2 = createEmptyTree(1); System.out.println(findTreeCenters(graph2)); // Centers are 0,1 List<List<Integer>> graph3 = createEmptyTree(2); addUndirectedEdge(graph3, 0, 1); System.out.println(findTreeCenters(graph3)); // Centers are 1 List<List<Integer>> graph4 = createEmptyTree(3); addUndirectedEdge(graph4, 0, 1); addUndirectedEdge(graph4, 1, 2); System.out.println(findTreeCenters(graph4)); // Centers are 1,2 List<List<Integer>> graph5 = createEmptyTree(4); addUndirectedEdge(graph5, 0, 1); addUndirectedEdge(graph5, 1, 2); addUndirectedEdge(graph5, 2, 3); System.out.println(findTreeCenters(graph5)); // Centers are<SUF> List<List<Integer>> graph6 = createEmptyTree(7); addUndirectedEdge(graph6, 0, 1); addUndirectedEdge(graph6, 1, 2); addUndirectedEdge(graph6, 2, 3); addUndirectedEdge(graph6, 3, 4); addUndirectedEdge(graph6, 4, 5); addUndirectedEdge(graph6, 4, 6); System.out.println(findTreeCenters(graph6)); } }
24053_11
package com.williamfiset.datastructures.binarysearchtree; import com.williamfiset.datastructures.utils.TreePrinter; import java.util.ArrayList; import java.util.Scanner; /** * Standard Splay Tree Implementation, supports generic data(must implement Comparable) * * <p>The Basic Concept of SplayTree is to keep frequently used nodes close to the root of the tree * It performs basic operations such as insertion,search,delete,findMin,findMax in O(log n) * amortized time Having frequently-used nodes near to the root can be useful in implementing many * algorithms. e.g: Implementing caches, garbage collection algorithms etc Primary disadvantage of * the splay tree can be the fact that its height can go linear. This causes the worst case running * times to go O(n) However, the amortized costs of this worst case situation is logarithmic, O(log * n) * * @author Ashiqur Rahman,https://github.com/ashiqursuperfly */ public class SplayTree<T extends Comparable<T>> { private BinaryTree<T> root; public static class BinaryTree<T extends Comparable<T>> implements TreePrinter.PrintableNode { private T data; private BinaryTree<T> leftChild, rightChild; public BinaryTree(T data) { if (data == null) { try { throw new Exception("Null data not allowed into tree"); } catch (Exception e) { e.printStackTrace(); } } else this.data = data; } @Override public BinaryTree<T> getLeft() { return leftChild; } public void setLeft(BinaryTree<T> leftChild) { this.leftChild = leftChild; } @Override public BinaryTree<T> getRight() { return rightChild; } public void setRight(BinaryTree<T> rightChild) { this.rightChild = rightChild; } @Override public String getText() { return data.toString(); } public T getData() { return data; } public void setData(T data) { if (data == null) { try { throw new Exception("Null data not allowed into tree"); } catch (Exception e) { e.printStackTrace(); } } else this.data = data; } @Override public String toString() { return TreePrinter.getTreeDisplay(this); } } /** Public Methods * */ public SplayTree() { this.root = null; } public SplayTree(BinaryTree<T> root) { this.root = root; } public BinaryTree<T> getRoot() { return root; } /** Searches a node and splays it on top,returns the new root * */ public BinaryTree<T> search(T node) { if (root == null) return null; this.root = splayUtil(root, node); return this.root.getData().compareTo(node) == 0 ? this.root : null; } /** Inserts a node into the tree and splays it on top, returns the new root* */ public BinaryTree<T> insert(T node) { if (root == null) { root = new BinaryTree<>(node); return root; } splay(node); ArrayList<BinaryTree<T>> l_r = split(node); BinaryTree<T> left = l_r.get(0); BinaryTree<T> right = l_r.get(1); root = new BinaryTree<>(node); root.setLeft(left); root.setRight(right); return root; } /** Deletes a node,returns the new root * */ public BinaryTree<T> delete(T node) { if (root == null) return null; BinaryTree<T> searchResult = splay(node); if (searchResult.getData().compareTo(node) != 0) return null; BinaryTree<T> leftSubtree = root.getLeft(); BinaryTree<T> rightSubtree = root.getRight(); // Set the 'to be deleted' key ready for garbage collection root.setLeft(null); root.setRight(null); root = join(leftSubtree, rightSubtree); return root; } /** To FindMax Of Entire Tree * */ public T findMax() { BinaryTree<T> temp = root; while (temp.getRight() != null) temp = temp.getRight(); return temp.getData(); } /** To FindMin Of Entire Tree * */ public T findMin() { BinaryTree<T> temp = root; while (temp.getLeft() != null) temp = temp.getLeft(); return temp.getData(); } /** * To FindMax Of Tree with specified root * */ public T findMax(BinaryTree<T> root) { BinaryTree<T> temp = root; while (temp.getRight() != null) temp = temp.getRight(); return temp.getData(); } /** * To FindMin Of Tree with specified root * */ public T findMin(BinaryTree<T> root) { BinaryTree<T> temp = root; while (temp.getLeft() != null) temp = temp.getLeft(); return temp.getData(); } @Override public String toString() { System.out.println("Elements:" + inorder(root, new ArrayList<>())); return (root != null) ? root.toString() : null; } /** Private Methods * */ private BinaryTree<T> rightRotate(BinaryTree<T> node) { BinaryTree<T> p = node.getLeft(); node.setLeft(p.getRight()); p.setRight(node); return p; } private BinaryTree<T> leftRotate(BinaryTree<T> node) { BinaryTree<T> p = node.getRight(); node.setRight(p.getLeft()); p.setLeft(node); return p; } private BinaryTree<T> splayUtil(BinaryTree<T> root, T key) { if (root == null || root.getData() == key) return root; if (root.getData().compareTo(key) > 0) { if (root.getLeft() == null) return root; if (root.getLeft().getData().compareTo(key) > 0) { root.getLeft().setLeft(splayUtil(root.getLeft().getLeft(), key)); root = rightRotate(root); } else if (root.getLeft().getData().compareTo(key) < 0) { root.getLeft().setRight(splayUtil(root.getLeft().getRight(), key)); if (root.getLeft().getRight() != null) root.setLeft(leftRotate(root.getLeft())); } return (root.getLeft() == null) ? root : rightRotate(root); } else { if (root.getRight() == null) return root; if (root.getRight().getData().compareTo(key) > 0) { root.getRight().setLeft(splayUtil(root.getRight().getLeft(), key)); if (root.getRight().getLeft() != null) root.setRight(rightRotate(root.getRight())); } else if (root.getRight().getData().compareTo(key) < 0) // Zag-Zag (Right Right) { root.getRight().setRight(splayUtil(root.getRight().getRight(), key)); root = leftRotate(root); } return (root.getRight() == null) ? root : leftRotate(root); } } private BinaryTree<T> splay(T node) { if (root == null) return null; this.root = splayUtil(root, node); return this.root; } private ArrayList<BinaryTree<T>> split(T node) { BinaryTree<T> right; BinaryTree<T> left; if (node.compareTo(root.getData()) > 0) { right = root.getRight(); left = root; left.setRight(null); } else { left = root.getLeft(); right = root; right.setLeft(null); } ArrayList<BinaryTree<T>> l_r = new ArrayList<>(); l_r.add(left); l_r.add(right); return l_r; } private BinaryTree<T> join(BinaryTree<T> L, BinaryTree<T> R) { if (L == null) { root = R; return R; } root = splayUtil(L, findMax(L)); root.setRight(R); return root; } private ArrayList<T> inorder(BinaryTree<T> root, ArrayList<T> sorted) { if (root == null) { return sorted; } inorder(root.getLeft(), sorted); sorted.add(root.getData()); inorder(root.getRight(), sorted); return sorted; } } class SplayTreeRun { public static void main(String[] args) { SplayTree<Integer> splayTree = new SplayTree<>(); Scanner sc = new Scanner(System.in); int[] data = {2, 29, 26, -1, 10, 0, 2, 11}; for (int i : data) { splayTree.insert(i); } while (true) { System.out.println("1. Insert 2. Delete 3. Search 4.FindMin 5.FindMax 6. PrintTree"); int c = sc.nextInt(); switch (c) { case 1: System.out.println("Enter Data :"); splayTree.insert(sc.nextInt()); break; case 2: System.out.println("Enter Element to be Deleted:"); splayTree.delete(sc.nextInt()); break; case 3: System.out.println("Enter Element to be Searched and Splayed:"); splayTree.search(sc.nextInt()); break; case 4: System.out.println("Min: " + splayTree.findMin()); break; case 5: System.out.println("Max: " + splayTree.findMax()); break; case 6: System.out.println(splayTree); break; } } } }
williamfiset/DEPRECATED-data-structures
com/williamfiset/datastructures/binarysearchtree/SplayTree.java
2,819
// Zag-Zag (Right Right)
line_comment
nl
package com.williamfiset.datastructures.binarysearchtree; import com.williamfiset.datastructures.utils.TreePrinter; import java.util.ArrayList; import java.util.Scanner; /** * Standard Splay Tree Implementation, supports generic data(must implement Comparable) * * <p>The Basic Concept of SplayTree is to keep frequently used nodes close to the root of the tree * It performs basic operations such as insertion,search,delete,findMin,findMax in O(log n) * amortized time Having frequently-used nodes near to the root can be useful in implementing many * algorithms. e.g: Implementing caches, garbage collection algorithms etc Primary disadvantage of * the splay tree can be the fact that its height can go linear. This causes the worst case running * times to go O(n) However, the amortized costs of this worst case situation is logarithmic, O(log * n) * * @author Ashiqur Rahman,https://github.com/ashiqursuperfly */ public class SplayTree<T extends Comparable<T>> { private BinaryTree<T> root; public static class BinaryTree<T extends Comparable<T>> implements TreePrinter.PrintableNode { private T data; private BinaryTree<T> leftChild, rightChild; public BinaryTree(T data) { if (data == null) { try { throw new Exception("Null data not allowed into tree"); } catch (Exception e) { e.printStackTrace(); } } else this.data = data; } @Override public BinaryTree<T> getLeft() { return leftChild; } public void setLeft(BinaryTree<T> leftChild) { this.leftChild = leftChild; } @Override public BinaryTree<T> getRight() { return rightChild; } public void setRight(BinaryTree<T> rightChild) { this.rightChild = rightChild; } @Override public String getText() { return data.toString(); } public T getData() { return data; } public void setData(T data) { if (data == null) { try { throw new Exception("Null data not allowed into tree"); } catch (Exception e) { e.printStackTrace(); } } else this.data = data; } @Override public String toString() { return TreePrinter.getTreeDisplay(this); } } /** Public Methods * */ public SplayTree() { this.root = null; } public SplayTree(BinaryTree<T> root) { this.root = root; } public BinaryTree<T> getRoot() { return root; } /** Searches a node and splays it on top,returns the new root * */ public BinaryTree<T> search(T node) { if (root == null) return null; this.root = splayUtil(root, node); return this.root.getData().compareTo(node) == 0 ? this.root : null; } /** Inserts a node into the tree and splays it on top, returns the new root* */ public BinaryTree<T> insert(T node) { if (root == null) { root = new BinaryTree<>(node); return root; } splay(node); ArrayList<BinaryTree<T>> l_r = split(node); BinaryTree<T> left = l_r.get(0); BinaryTree<T> right = l_r.get(1); root = new BinaryTree<>(node); root.setLeft(left); root.setRight(right); return root; } /** Deletes a node,returns the new root * */ public BinaryTree<T> delete(T node) { if (root == null) return null; BinaryTree<T> searchResult = splay(node); if (searchResult.getData().compareTo(node) != 0) return null; BinaryTree<T> leftSubtree = root.getLeft(); BinaryTree<T> rightSubtree = root.getRight(); // Set the 'to be deleted' key ready for garbage collection root.setLeft(null); root.setRight(null); root = join(leftSubtree, rightSubtree); return root; } /** To FindMax Of Entire Tree * */ public T findMax() { BinaryTree<T> temp = root; while (temp.getRight() != null) temp = temp.getRight(); return temp.getData(); } /** To FindMin Of Entire Tree * */ public T findMin() { BinaryTree<T> temp = root; while (temp.getLeft() != null) temp = temp.getLeft(); return temp.getData(); } /** * To FindMax Of Tree with specified root * */ public T findMax(BinaryTree<T> root) { BinaryTree<T> temp = root; while (temp.getRight() != null) temp = temp.getRight(); return temp.getData(); } /** * To FindMin Of Tree with specified root * */ public T findMin(BinaryTree<T> root) { BinaryTree<T> temp = root; while (temp.getLeft() != null) temp = temp.getLeft(); return temp.getData(); } @Override public String toString() { System.out.println("Elements:" + inorder(root, new ArrayList<>())); return (root != null) ? root.toString() : null; } /** Private Methods * */ private BinaryTree<T> rightRotate(BinaryTree<T> node) { BinaryTree<T> p = node.getLeft(); node.setLeft(p.getRight()); p.setRight(node); return p; } private BinaryTree<T> leftRotate(BinaryTree<T> node) { BinaryTree<T> p = node.getRight(); node.setRight(p.getLeft()); p.setLeft(node); return p; } private BinaryTree<T> splayUtil(BinaryTree<T> root, T key) { if (root == null || root.getData() == key) return root; if (root.getData().compareTo(key) > 0) { if (root.getLeft() == null) return root; if (root.getLeft().getData().compareTo(key) > 0) { root.getLeft().setLeft(splayUtil(root.getLeft().getLeft(), key)); root = rightRotate(root); } else if (root.getLeft().getData().compareTo(key) < 0) { root.getLeft().setRight(splayUtil(root.getLeft().getRight(), key)); if (root.getLeft().getRight() != null) root.setLeft(leftRotate(root.getLeft())); } return (root.getLeft() == null) ? root : rightRotate(root); } else { if (root.getRight() == null) return root; if (root.getRight().getData().compareTo(key) > 0) { root.getRight().setLeft(splayUtil(root.getRight().getLeft(), key)); if (root.getRight().getLeft() != null) root.setRight(rightRotate(root.getRight())); } else if (root.getRight().getData().compareTo(key) < 0) // Zag-Zag (Right<SUF> { root.getRight().setRight(splayUtil(root.getRight().getRight(), key)); root = leftRotate(root); } return (root.getRight() == null) ? root : leftRotate(root); } } private BinaryTree<T> splay(T node) { if (root == null) return null; this.root = splayUtil(root, node); return this.root; } private ArrayList<BinaryTree<T>> split(T node) { BinaryTree<T> right; BinaryTree<T> left; if (node.compareTo(root.getData()) > 0) { right = root.getRight(); left = root; left.setRight(null); } else { left = root.getLeft(); right = root; right.setLeft(null); } ArrayList<BinaryTree<T>> l_r = new ArrayList<>(); l_r.add(left); l_r.add(right); return l_r; } private BinaryTree<T> join(BinaryTree<T> L, BinaryTree<T> R) { if (L == null) { root = R; return R; } root = splayUtil(L, findMax(L)); root.setRight(R); return root; } private ArrayList<T> inorder(BinaryTree<T> root, ArrayList<T> sorted) { if (root == null) { return sorted; } inorder(root.getLeft(), sorted); sorted.add(root.getData()); inorder(root.getRight(), sorted); return sorted; } } class SplayTreeRun { public static void main(String[] args) { SplayTree<Integer> splayTree = new SplayTree<>(); Scanner sc = new Scanner(System.in); int[] data = {2, 29, 26, -1, 10, 0, 2, 11}; for (int i : data) { splayTree.insert(i); } while (true) { System.out.println("1. Insert 2. Delete 3. Search 4.FindMin 5.FindMax 6. PrintTree"); int c = sc.nextInt(); switch (c) { case 1: System.out.println("Enter Data :"); splayTree.insert(sc.nextInt()); break; case 2: System.out.println("Enter Element to be Deleted:"); splayTree.delete(sc.nextInt()); break; case 3: System.out.println("Enter Element to be Searched and Splayed:"); splayTree.search(sc.nextInt()); break; case 4: System.out.println("Min: " + splayTree.findMin()); break; case 5: System.out.println("Max: " + splayTree.findMax()); break; case 6: System.out.println(splayTree); break; } } } }
128260_5
/********************************************************************** * * Copyright (c) 2004 Olaf Willuhn * All rights reserved. * * This software is copyrighted work licensed under the terms of the * Jameica License. Please consult the file "LICENSE" for details. * **********************************************************************/ package de.willuhn.jameica.hbci.server; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.rmi.RemoteException; import java.security.SecureRandom; import java.sql.Connection; import de.willuhn.jameica.hbci.HBCI; import de.willuhn.jameica.hbci.rmi.HBCIDBService; import de.willuhn.jameica.system.Application; import de.willuhn.logging.Logger; import de.willuhn.util.Base64; /** * Implementierung des Datenbank-Supports fuer H2-Database (http://www.h2database.com). */ public class DBSupportH2Impl extends AbstractDBSupportImpl { /** * ct. */ public DBSupportH2Impl() { // H2-Datenbank verwendet uppercase Identifier Logger.info("switching dbservice to uppercase"); System.setProperty(HBCIDBServiceImpl.class.getName() + ".uppercase","true"); try { Method m = Class.forName("org.h2.engine.Constants").getMethod("getVersion",(Class[]) null); Logger.info("h2 version: " + m.invoke(null,(Object[])null)); } catch (Throwable t) { Logger.warn("unable to determine h2 version"); } } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcDriver() */ public String getJdbcDriver() { return "org.h2.Driver"; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcPassword() */ public String getJdbcPassword() { String password = HBCIDBService.SETTINGS.getString("database.driver.h2.encryption.encryptedpassword",null); try { // Existiert noch nicht. Also neu erstellen. if (password == null) { // Wir koennen als Passwort nicht so einfach das Masterpasswort // nehmen, weil der User es aendern kann. Wir koennen zwar // das Passwort der Datenbank aendern. Allerdings kriegen wir // hier nicht mit, wenn sich das Passwort geaendert hat. // Daher erzeugen wir ein selbst ein Passwort. Logger.info("generating new random password for database"); byte[] data = new byte[20]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.nextBytes(data); // Jetzt noch verschluesselt abspeichern Logger.info("encrypting password with system certificate"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Application.getSSLFactory().encrypt(new ByteArrayInputStream(data),bos); // Verschluesseltes Passwort als Base64 speichern HBCIDBService.SETTINGS.setAttribute("database.driver.h2.encryption.encryptedpassword",Base64.encode(bos.toByteArray())); // Entschluesseltes Passwort als Base64 zurueckliefern, damit keine Binaer-Daten drin sind. // Die Datenbank will es doppelt mit Leerzeichen getrennt haben. // Das erste ist fuer den User. Das zweite fuer die Verschluesselung. String encoded = Base64.encode(data); return encoded + " " + encoded; } Logger.debug("decrypting database password"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Application.getSSLFactory().decrypt(new ByteArrayInputStream(Base64.decode(password)),bos); String encoded = Base64.encode(bos.toByteArray()); return encoded + " " + encoded; } catch (Exception e) { throw new RuntimeException("error while determining database password",e); } } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcUrl() */ public String getJdbcUrl() { String url = "jdbc:h2:" + Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath() + "/h2db/hibiscus"; if (HBCIDBService.SETTINGS.getBoolean("database.driver.h2.encryption",true)) url += ";CIPHER=" + HBCIDBService.SETTINGS.getString("database.driver.h2.encryption.algorithm","XTEA"); if (HBCIDBService.SETTINGS.getBoolean("database.driver.h2.recover",false)) { Logger.warn("#############################################################"); Logger.warn("## DATABASE RECOVERY ACTIVATED ##"); Logger.warn("#############################################################"); url += ";RECOVER=1"; } String addon = HBCIDBService.SETTINGS.getString("database.driver.h2.parameters",null); if (addon != null) url += ";" + addon; return url; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcUsername() */ public String getJdbcUsername() { return "hibiscus"; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getScriptPrefix() */ public String getScriptPrefix() throws RemoteException { return "h2-"; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getSQLTimestamp(java.lang.String) */ public String getSQLTimestamp(String content) throws RemoteException { // Nicht noetig // return MessageFormat.format("DATEDIFF('MS','1970-01-01 00:00',{0})", new Object[]{content}); return content; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getInsertWithID() */ public boolean getInsertWithID() throws RemoteException { return false; } /** * @see de.willuhn.jameica.hbci.server.AbstractDBSupportImpl#checkConnection(java.sql.Connection) */ public void checkConnection(Connection conn) throws RemoteException { // brauchen wir bei nicht, da Embedded } } /********************************************************************* * $Log: DBSupportH2Impl.java,v $ * Revision 1.12 2010/11/02 12:02:19 willuhn * @R Support fuer McKoi entfernt. User, die noch dieses alte DB-Format nutzen, sollen erst auf Jameica 1.6/Hibiscus 1.8 (oder maximal Jameica 1.9/Hibiscus 1.11) wechseln, dort die Migration auf H2 durchfuehren und dann erst auf Hibiscus 1.12 updaten * * Revision 1.11 2009/06/02 15:49:41 willuhn * @N method to display h2 database version * * Revision 1.10 2009/05/28 22:39:01 willuhn * @N Option zum Aktivieren des Recover-Modus. Siehe http://www.onlinebanking-forum.de/phpBB2/viewtopic.php?p=57830#57830 * * Revision 1.9 2009/04/05 21:40:56 willuhn * @C checkConnection() nur noch alle hoechstens 10 Sekunden ausfuehren * * Revision 1.8 2008/12/30 15:21:40 willuhn * @N Umstellung auf neue Versionierung * * Revision 1.7 2007/12/06 17:57:21 willuhn * @N Erster Code fuer das neue Versionierungs-System * * Revision 1.6 2007/10/27 13:31:41 willuhn * @C Checksummen-Pruefung temporaer deaktiviert * * Revision 1.5 2007/10/02 16:08:55 willuhn * @C Bugfix mit dem falschen Spaltentyp nochmal ueberarbeitet * * Revision 1.4 2007/10/01 09:37:42 willuhn * @B H2: Felder vom Typ "TEXT" werden von H2 als InputStreamReader geliefert. Felder umsatz.kommentar und protokoll.nachricht auf "VARCHAR(1000)" geaendert und fuer Migration in den Gettern beides beruecksichtigt * * Revision 1.3 2007/08/23 13:07:38 willuhn * @C Uppercase-Verhalten nicht global sondern pro DBService konfigurierbar. Verhindert Fehler, wenn mehrere Plugins installiert sind * * Revision 1.2 2007/07/18 09:45:18 willuhn * @B Neue Version 1.8 in DB-Checks nachgezogen * * Revision 1.1 2007/06/25 11:21:19 willuhn * @N Support fuer H2-Datenbank (http://www.h2database.com/) * **********************************************************************/
willuhn/hibiscus
src/de/willuhn/jameica/hbci/server/DBSupportH2Impl.java
2,631
/** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcPassword() */
block_comment
nl
/********************************************************************** * * Copyright (c) 2004 Olaf Willuhn * All rights reserved. * * This software is copyrighted work licensed under the terms of the * Jameica License. Please consult the file "LICENSE" for details. * **********************************************************************/ package de.willuhn.jameica.hbci.server; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.rmi.RemoteException; import java.security.SecureRandom; import java.sql.Connection; import de.willuhn.jameica.hbci.HBCI; import de.willuhn.jameica.hbci.rmi.HBCIDBService; import de.willuhn.jameica.system.Application; import de.willuhn.logging.Logger; import de.willuhn.util.Base64; /** * Implementierung des Datenbank-Supports fuer H2-Database (http://www.h2database.com). */ public class DBSupportH2Impl extends AbstractDBSupportImpl { /** * ct. */ public DBSupportH2Impl() { // H2-Datenbank verwendet uppercase Identifier Logger.info("switching dbservice to uppercase"); System.setProperty(HBCIDBServiceImpl.class.getName() + ".uppercase","true"); try { Method m = Class.forName("org.h2.engine.Constants").getMethod("getVersion",(Class[]) null); Logger.info("h2 version: " + m.invoke(null,(Object[])null)); } catch (Throwable t) { Logger.warn("unable to determine h2 version"); } } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcDriver() */ public String getJdbcDriver() { return "org.h2.Driver"; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcPassword() <SUF>*/ public String getJdbcPassword() { String password = HBCIDBService.SETTINGS.getString("database.driver.h2.encryption.encryptedpassword",null); try { // Existiert noch nicht. Also neu erstellen. if (password == null) { // Wir koennen als Passwort nicht so einfach das Masterpasswort // nehmen, weil der User es aendern kann. Wir koennen zwar // das Passwort der Datenbank aendern. Allerdings kriegen wir // hier nicht mit, wenn sich das Passwort geaendert hat. // Daher erzeugen wir ein selbst ein Passwort. Logger.info("generating new random password for database"); byte[] data = new byte[20]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.nextBytes(data); // Jetzt noch verschluesselt abspeichern Logger.info("encrypting password with system certificate"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Application.getSSLFactory().encrypt(new ByteArrayInputStream(data),bos); // Verschluesseltes Passwort als Base64 speichern HBCIDBService.SETTINGS.setAttribute("database.driver.h2.encryption.encryptedpassword",Base64.encode(bos.toByteArray())); // Entschluesseltes Passwort als Base64 zurueckliefern, damit keine Binaer-Daten drin sind. // Die Datenbank will es doppelt mit Leerzeichen getrennt haben. // Das erste ist fuer den User. Das zweite fuer die Verschluesselung. String encoded = Base64.encode(data); return encoded + " " + encoded; } Logger.debug("decrypting database password"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Application.getSSLFactory().decrypt(new ByteArrayInputStream(Base64.decode(password)),bos); String encoded = Base64.encode(bos.toByteArray()); return encoded + " " + encoded; } catch (Exception e) { throw new RuntimeException("error while determining database password",e); } } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcUrl() */ public String getJdbcUrl() { String url = "jdbc:h2:" + Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath() + "/h2db/hibiscus"; if (HBCIDBService.SETTINGS.getBoolean("database.driver.h2.encryption",true)) url += ";CIPHER=" + HBCIDBService.SETTINGS.getString("database.driver.h2.encryption.algorithm","XTEA"); if (HBCIDBService.SETTINGS.getBoolean("database.driver.h2.recover",false)) { Logger.warn("#############################################################"); Logger.warn("## DATABASE RECOVERY ACTIVATED ##"); Logger.warn("#############################################################"); url += ";RECOVER=1"; } String addon = HBCIDBService.SETTINGS.getString("database.driver.h2.parameters",null); if (addon != null) url += ";" + addon; return url; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getJdbcUsername() */ public String getJdbcUsername() { return "hibiscus"; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getScriptPrefix() */ public String getScriptPrefix() throws RemoteException { return "h2-"; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getSQLTimestamp(java.lang.String) */ public String getSQLTimestamp(String content) throws RemoteException { // Nicht noetig // return MessageFormat.format("DATEDIFF('MS','1970-01-01 00:00',{0})", new Object[]{content}); return content; } /** * @see de.willuhn.jameica.hbci.rmi.DBSupport#getInsertWithID() */ public boolean getInsertWithID() throws RemoteException { return false; } /** * @see de.willuhn.jameica.hbci.server.AbstractDBSupportImpl#checkConnection(java.sql.Connection) */ public void checkConnection(Connection conn) throws RemoteException { // brauchen wir bei nicht, da Embedded } } /********************************************************************* * $Log: DBSupportH2Impl.java,v $ * Revision 1.12 2010/11/02 12:02:19 willuhn * @R Support fuer McKoi entfernt. User, die noch dieses alte DB-Format nutzen, sollen erst auf Jameica 1.6/Hibiscus 1.8 (oder maximal Jameica 1.9/Hibiscus 1.11) wechseln, dort die Migration auf H2 durchfuehren und dann erst auf Hibiscus 1.12 updaten * * Revision 1.11 2009/06/02 15:49:41 willuhn * @N method to display h2 database version * * Revision 1.10 2009/05/28 22:39:01 willuhn * @N Option zum Aktivieren des Recover-Modus. Siehe http://www.onlinebanking-forum.de/phpBB2/viewtopic.php?p=57830#57830 * * Revision 1.9 2009/04/05 21:40:56 willuhn * @C checkConnection() nur noch alle hoechstens 10 Sekunden ausfuehren * * Revision 1.8 2008/12/30 15:21:40 willuhn * @N Umstellung auf neue Versionierung * * Revision 1.7 2007/12/06 17:57:21 willuhn * @N Erster Code fuer das neue Versionierungs-System * * Revision 1.6 2007/10/27 13:31:41 willuhn * @C Checksummen-Pruefung temporaer deaktiviert * * Revision 1.5 2007/10/02 16:08:55 willuhn * @C Bugfix mit dem falschen Spaltentyp nochmal ueberarbeitet * * Revision 1.4 2007/10/01 09:37:42 willuhn * @B H2: Felder vom Typ "TEXT" werden von H2 als InputStreamReader geliefert. Felder umsatz.kommentar und protokoll.nachricht auf "VARCHAR(1000)" geaendert und fuer Migration in den Gettern beides beruecksichtigt * * Revision 1.3 2007/08/23 13:07:38 willuhn * @C Uppercase-Verhalten nicht global sondern pro DBService konfigurierbar. Verhindert Fehler, wenn mehrere Plugins installiert sind * * Revision 1.2 2007/07/18 09:45:18 willuhn * @B Neue Version 1.8 in DB-Checks nachgezogen * * Revision 1.1 2007/06/25 11:21:19 willuhn * @N Support fuer H2-Datenbank (http://www.h2database.com/) * **********************************************************************/
212230_2
/********************************************************************** * * Copyright (c) 2004 Olaf Willuhn * All rights reserved. * * This software is copyrighted work licensed under the terms of the * Jameica License. Please consult the file "LICENSE" for details. * **********************************************************************/ package de.willuhn.jameica.services; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import de.willuhn.boot.BootLoader; import de.willuhn.boot.Bootable; import de.willuhn.boot.SkipServiceException; import de.willuhn.jameica.security.JameicaHostnameVerifier; import de.willuhn.logging.Logger; /** * Initialisiert den Hostname-Verifier. */ public class HostnameVerifierService implements Bootable { /** * @see de.willuhn.boot.Bootable#depends() */ public Class[] depends() { return new Class[]{LogService.class, SecurityManagerService.class}; } /** * @see de.willuhn.boot.Bootable#init(de.willuhn.boot.BootLoader, de.willuhn.boot.Bootable) */ public void init(BootLoader loader, Bootable caller) throws SkipServiceException { HostnameVerifier parent = HttpsURLConnection.getDefaultHostnameVerifier(); Logger.info("applying jameica's hostname verifier"); HostnameVerifier verifier = new JameicaHostnameVerifier(parent); HttpsURLConnection.setDefaultHostnameVerifier(verifier); } /** * @see de.willuhn.boot.Bootable#shutdown() */ public void shutdown() { } } /********************************************************************** * $Log: HostnameVerifierService.java,v $ * Revision 1.1 2011/09/14 11:57:14 willuhn * @N HostnameVerifier in separate Klasse ausgelagert * @C Beim Erstellen eines neuen Master-Passwortes dieses sofort ververwenden und nicht nochmal mit getPasswort erfragen * **********************************************************************/
willuhn/jameica
src/de/willuhn/jameica/services/HostnameVerifierService.java
583
/** * @see de.willuhn.boot.Bootable#depends() */
block_comment
nl
/********************************************************************** * * Copyright (c) 2004 Olaf Willuhn * All rights reserved. * * This software is copyrighted work licensed under the terms of the * Jameica License. Please consult the file "LICENSE" for details. * **********************************************************************/ package de.willuhn.jameica.services; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import de.willuhn.boot.BootLoader; import de.willuhn.boot.Bootable; import de.willuhn.boot.SkipServiceException; import de.willuhn.jameica.security.JameicaHostnameVerifier; import de.willuhn.logging.Logger; /** * Initialisiert den Hostname-Verifier. */ public class HostnameVerifierService implements Bootable { /** * @see de.willuhn.boot.Bootable#depends() <SUF>*/ public Class[] depends() { return new Class[]{LogService.class, SecurityManagerService.class}; } /** * @see de.willuhn.boot.Bootable#init(de.willuhn.boot.BootLoader, de.willuhn.boot.Bootable) */ public void init(BootLoader loader, Bootable caller) throws SkipServiceException { HostnameVerifier parent = HttpsURLConnection.getDefaultHostnameVerifier(); Logger.info("applying jameica's hostname verifier"); HostnameVerifier verifier = new JameicaHostnameVerifier(parent); HttpsURLConnection.setDefaultHostnameVerifier(verifier); } /** * @see de.willuhn.boot.Bootable#shutdown() */ public void shutdown() { } } /********************************************************************** * $Log: HostnameVerifierService.java,v $ * Revision 1.1 2011/09/14 11:57:14 willuhn * @N HostnameVerifier in separate Klasse ausgelagert * @C Beim Erstellen eines neuen Master-Passwortes dieses sofort ververwenden und nicht nochmal mit getPasswort erfragen * **********************************************************************/
172796_38
package io.sloeber.ui.monitor.views; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.io.FileUtils; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.FontRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.themes.ITheme; import org.eclipse.ui.themes.IThemeManager; import io.sloeber.core.api.ISerialUser; import io.sloeber.core.api.Serial; import io.sloeber.core.api.SerialManager; import io.sloeber.ui.Activator; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; import io.sloeber.ui.listeners.ProjectExplorerListener; import io.sloeber.ui.monitor.internal.SerialListener; /** * SerialMonitor implements the view that shows the serial monitor. Serial * monitor get sits data from serial Listener. 1 serial listener is created per * serial connection. * */ @SuppressWarnings({"unused"}) public class SerialMonitor extends ViewPart implements ISerialUser { /** * The ID of the view as specified by the extension. */ // public static final String ID = // "io.sloeber.ui.monitor.views.SerialMonitor"; // If you increase this number you must also assign colors in plugin.xml static private final int MY_MAX_SERIAL_PORTS = 6; static private final URL IMG_CLEAR; static private final URL IMG_LOCK; static private final URL IMG_FILTER; static { IMG_CLEAR = Activator.getDefault().getBundle().getEntry("icons/clear_console.png"); //$NON-NLS-1$ IMG_LOCK = Activator.getDefault().getBundle().getEntry("icons/lock_console.png"); //$NON-NLS-1$ IMG_FILTER = Activator.getDefault().getBundle().getEntry("icons/filter_console.png"); //$NON-NLS-1$ } // Connect to a serial port private Action connect; // this action will disconnect the serial port selected by the serialPorts // combo private Action disconnect; // lock serial monitor scrolling private Action scrollLock; // filter out binary data from serial monitor private Action plotterFilter; // clear serial monitor private Action clear; // The string to send to the serial port protected Text sendString; // control contains the output of the serial port static protected StyledText monitorOutput; // Port used when doing actions protected ComboViewer serialPorts; // Add CR? LF? CR+LF? Nothing? protected ComboViewer lineTerminator; // When click will send the content of SendString to the port selected // SerialPorts // adding the postfix selected in SendPostFix private Button send; // The button to reset the arduino private Button reset; // Contains the colors that are used private String[] serialColorID = null; // link to color registry private ColorRegistry colorRegistry = null; static private Composite parent; /* * ************** Below are variables needed for good housekeeping */ // The serial connections that are open with the listeners listening to this // port protected Map<Serial, SerialListener> serialConnections; private static final String MY_FLAG_MONITOR = "FmStatus"; //$NON-NLS-1$ static final String uri = "h tt p://ba eye ns. i t/ec li pse/d ow nlo ad/mo nito rSta rt.ht m l?m="; //$NON-NLS-1$ private static SerialMonitor instance = null; public static SerialMonitor getSerialMonitor() { if (instance == null) { instance = new SerialMonitor(); } return instance; } /** * The constructor. */ public SerialMonitor() { if (instance != null) { Activator.log(new Status(IStatus.ERROR, Activator.getId(), "You can only have one serial monitor")); //$NON-NLS-1$ } instance = this; serialConnections = new LinkedHashMap<>(MY_MAX_SERIAL_PORTS); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); colorRegistry = currentTheme.getColorRegistry(); serialColorID = new String[MY_MAX_SERIAL_PORTS]; for (int i = 0; i < MY_MAX_SERIAL_PORTS; i++) { serialColorID[i] = "io.sloeber.serial.color." + (1 + i); //$NON-NLS-1$ } SerialManager.registerSerialUser(this); Job job = new Job("pluginSerialmonitorInitiator") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { try { IEclipsePreferences myScope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO); int curFsiStatus = myScope.getInt(MY_FLAG_MONITOR, 0) + 1; myScope.putInt(MY_FLAG_MONITOR, curFsiStatus); URL mypluginStartInitiator = new URL(uri.replace(" ", new String()) //$NON-NLS-1$ + Integer.toString(curFsiStatus)); mypluginStartInitiator.getContent(); } catch (Exception e) {// JABA is not going to add code } return Status.OK_STATUS; } }; job.setPriority(Job.DECORATE); job.schedule(); } @Override public void dispose() { SerialManager.UnRegisterSerialUser(); for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { entry.getValue().dispose(); entry.getKey().dispose(); } serialConnections.clear(); instance = null; } /** * This is a callback that will allow us to create the viewer and initialize * it. */ @Override public void createPartControl(Composite parent1) { parent = parent1; parent1.setLayout(new GridLayout()); GridLayout layout = new GridLayout(5, false); layout.marginHeight = 0; layout.marginWidth = 0; Composite top = new Composite(parent1, SWT.NONE); top.setLayout(layout); top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); serialPorts = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); GridData minSizeGridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); minSizeGridData.widthHint = 150; serialPorts.getControl().setLayoutData(minSizeGridData); serialPorts.setContentProvider(new IStructuredContentProvider() { @Override public void dispose() { // no need to do something here } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // no need to do something here } @Override public Object[] getElements(Object inputElement) { @SuppressWarnings("unchecked") Map<Serial, SerialListener> items = (Map<Serial, SerialListener>) inputElement; return items.keySet().toArray(); } }); serialPorts.setLabelProvider(new LabelProvider()); serialPorts.setInput(serialConnections); serialPorts.addSelectionChangedListener(new ComPortChanged(this)); sendString = new Text(top, SWT.SINGLE | SWT.BORDER); sendString.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); lineTerminator = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); lineTerminator.setContentProvider(new ArrayContentProvider()); lineTerminator.setLabelProvider(new LabelProvider()); lineTerminator.setInput(SerialManager.listLineEndings()); lineTerminator.getCombo().select(MyPreferences.getLastUsedSerialLineEnd()); lineTerminator.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { MyPreferences .setLastUsedSerialLineEnd(lineTerminator.getCombo().getSelectionIndex()); } }); send = new Button(top, SWT.BUTTON1); send.setText(Messages.serialMonitorSend); send.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { int index = lineTerminator.getCombo().getSelectionIndex(); GetSelectedSerial().write(sendString.getText(), SerialManager.getLineEnding(index)); sendString.setText(new String()); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); send.setEnabled(false); reset = new Button(top, SWT.BUTTON1); reset.setText(Messages.serialMonitorReset); reset.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { GetSelectedSerial().reset(); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); reset.setEnabled(false); // register the combo as a Selection Provider getSite().setSelectionProvider(serialPorts); monitorOutput = new StyledText(top, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); monitorOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1)); monitorOutput.setEditable(false); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); FontRegistry fontRegistry = currentTheme.getFontRegistry(); monitorOutput.setFont(fontRegistry.get("io.sloeber.serial.fontDefinition")); //$NON-NLS-1$ monitorOutput.setText(Messages.serialMonitorNoInput); monitorOutput.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent e) { // ignore } @Override public void mouseDown(MouseEvent e) { // If right button get selected text save it and start external tool if (e.button==3) { String selectedText=monitorOutput.getSelectionText(); if(!selectedText.isEmpty()) { IProject selectedProject = ProjectExplorerListener.getSelectedProject(); if (selectedProject!=null) { try { ICConfigurationDescription activeCfg=CoreModel.getDefault().getProjectDescription(selectedProject).getActiveConfiguration(); String activeConfigName= activeCfg.getName(); IPath buildFolder=selectedProject.findMember(activeConfigName).getLocation(); File dumpFile=buildFolder.append("serialdump.txt").toFile(); //$NON-NLS-1$ FileUtils.writeStringToFile(dumpFile, selectedText); } catch (Exception e1) { // ignore e1.printStackTrace(); } } } } } @Override public void mouseDoubleClick(MouseEvent e) { // ignore } }); parent.getShell().setDefaultButton(send); makeActions(); contributeToActionBars(); } /** * GetSelectedSerial is a wrapper class that returns the serial port * selected in the combobox * * @return the serial port selected in the combobox */ protected Serial GetSelectedSerial() { return GetSerial(serialPorts.getCombo().getText()); } /** * Looks in the open com ports with a port with the name as provided. * * @param comName * the name of the comport you are looking for * @return the serial port opened in the serial monitor with the name equal * to Comname of found. null if not found */ private Serial GetSerial(String comName) { for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { if (entry.getKey().toString().matches(comName)) return entry.getKey(); } return null; } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalToolBar(IToolBarManager manager) { manager.add(clear); manager.add(scrollLock); manager.add(plotterFilter); manager.add(connect); manager.add(disconnect); } private void fillLocalPullDown(IMenuManager manager) { manager.add(connect); manager.add(new Separator()); manager.add(disconnect); } private void makeActions() { connect = new Action() { @SuppressWarnings("synthetic-access") @Override public void run() { OpenSerialDialogBox comportSelector = new OpenSerialDialogBox(parent.getShell()); comportSelector.create(); if (comportSelector.open() == Window.OK) { connectSerial(comportSelector.GetComPort(), comportSelector.GetBaudRate()); } } }; connect.setText(Messages.serialMonitorConnectedTo); connect.setToolTipText(Messages.serialMonitorAddConnectionToSeralMonitor); connect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ADD)); // IMG_OBJS_INFO_TSK)); disconnect = new Action() { @Override public void run() { disConnectSerialPort(getSerialMonitor().serialPorts.getCombo().getText()); } }; disconnect.setText(Messages.serialMonitorDisconnectedFrom); disconnect.setToolTipText(Messages.serialMonitorRemoveSerialPortFromMonitor); disconnect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));// IMG_OBJS_INFO_TSK)); disconnect.setEnabled(serialConnections.size() != 0); clear = new Action(Messages.serialMonitorClear) { @Override public void run() { clearMonitor(); } }; clear.setImageDescriptor(ImageDescriptor.createFromURL(IMG_CLEAR)); clear.setEnabled(true); scrollLock = new Action(Messages.serialMonitorScrollLock, IAction.AS_CHECK_BOX) { @Override public void run() { MyPreferences.setLastUsedAutoScroll(!isChecked()); } }; scrollLock.setImageDescriptor(ImageDescriptor.createFromURL(IMG_LOCK)); scrollLock.setEnabled(true); scrollLock.setChecked(!MyPreferences.getLastUsedAutoScroll()); plotterFilter = new Action(Messages.serialMonitorFilterPloter, IAction.AS_CHECK_BOX) { @Override public void run() { SerialListener.setPlotterFilter(isChecked()); MyPreferences.setLastUsedPlotterFilter(isChecked()); } }; plotterFilter.setImageDescriptor(ImageDescriptor.createFromURL(IMG_FILTER)); plotterFilter.setEnabled(true); plotterFilter.setChecked(MyPreferences.getLastUsedPlotterFilter()); SerialListener.setPlotterFilter(MyPreferences.getLastUsedPlotterFilter()); } /** * Passing the focus request to the viewer's control. */ @Override public void setFocus() { // MonitorOutput.setf .getControl().setFocus(); parent.getShell().setDefaultButton(send); } /** * The listener calls this method to report that serial data has arrived * * @param stInfo * The serial data that has arrived * @param style * The style that should be used to report the data; Actually * this is the index number of the opened port */ public void ReportSerialActivity(String stInfo, int style) { int startPoint = monitorOutput.getCharCount(); monitorOutput.append(stInfo); StyleRange styleRange = new StyleRange(); styleRange.start = startPoint; styleRange.length = stInfo.length(); styleRange.fontStyle = SWT.NORMAL; styleRange.foreground = colorRegistry.get(serialColorID[style]); monitorOutput.setStyleRange(styleRange); if (!scrollLock.isChecked()) { monitorOutput.setSelection(monitorOutput.getCharCount()); } } /** * method to make sure the visualization is correct */ void SerialPortsUpdated() { disconnect.setEnabled(serialConnections.size() != 0); Serial curSelection = GetSelectedSerial(); serialPorts.setInput(serialConnections); if (serialConnections.size() == 0) { send.setEnabled(false); reset.setEnabled(false); } else { if (serialPorts.getSelection().isEmpty()) // nothing is // selected { if (curSelection == null) // nothing was selected { curSelection = (Serial) serialConnections.keySet().toArray()[0]; } serialPorts.getCombo().setText(curSelection.toString()); ComboSerialChanged(); } } } /** * Connect to a serial port and sets the listener * * @param comPort * the name of the com port to connect to * @param baudRate * the baud rate to connect to the com port */ public void connectSerial(String comPort, int baudRate) { if (serialConnections.size() < MY_MAX_SERIAL_PORTS) { int colorindex = serialConnections.size(); Serial newSerial = new Serial(comPort, baudRate); if (newSerial.IsConnected()) { newSerial.registerService(); SerialListener theListener = new SerialListener(this, colorindex); newSerial.addListener(theListener); String newLine=System.getProperty("line.separator");//$NON-NLS-1$ theListener.event( newLine+ Messages.serialMonitorConnectedTo.replace(Messages.PORT, comPort).replace(Messages.BAUD,Integer.toString(baudRate) ) + newLine); serialConnections.put(newSerial, theListener); SerialPortsUpdated(); return; } } else { Activator.log(new Status(IStatus.ERROR, Activator.getId(), Messages.serialMonitorNoMoreSerialPortsSupported, null)); } } public void disConnectSerialPort(String comPort) { Serial newSerial = GetSerial(comPort); if (newSerial != null) { SerialListener theListener = serialConnections.get(newSerial); serialConnections.remove(newSerial); newSerial.removeListener(theListener); newSerial.dispose(); theListener.dispose(); SerialPortsUpdated(); } } /** * */ public void ComboSerialChanged() { send.setEnabled(serialPorts.toString().length() > 0); reset.setEnabled(serialPorts.toString().length() > 0); parent.getShell().setDefaultButton(send); } /** * PauzePort is called when the monitor needs to disconnect from a port for * a short while. For instance when a upload is started to a com port the * serial monitor will get a pauzeport for this com port. When the upload is * done ResumePort will be called */ @Override public boolean PauzePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { theSerial.disconnect(); return true; } return false; } /** * see PauzePort */ @Override public void ResumePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { if (MyPreferences.getCleanSerialMonitorAfterUpload()) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { monitorOutput.setText(new String()); } }); } theSerial.connect(15); } } public static List<String> getMonitorContent() { int numLines =monitorOutput.getContent().getLineCount(); List<String>ret=new ArrayList<>(); for(int curLine=1;curLine<numLines;curLine++) { ret.add(monitorOutput.getContent().getLine(curLine-1)); } return ret; } public static void clearMonitor() { monitorOutput.setText(new String()); } }
wimjongman/arduino-eclipse-plugin
io.sloeber.ui/src/io/sloeber/ui/monitor/views/SerialMonitor.java
6,413
/** * see PauzePort */
block_comment
nl
package io.sloeber.ui.monitor.views; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.io.FileUtils; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.FontRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.themes.ITheme; import org.eclipse.ui.themes.IThemeManager; import io.sloeber.core.api.ISerialUser; import io.sloeber.core.api.Serial; import io.sloeber.core.api.SerialManager; import io.sloeber.ui.Activator; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; import io.sloeber.ui.listeners.ProjectExplorerListener; import io.sloeber.ui.monitor.internal.SerialListener; /** * SerialMonitor implements the view that shows the serial monitor. Serial * monitor get sits data from serial Listener. 1 serial listener is created per * serial connection. * */ @SuppressWarnings({"unused"}) public class SerialMonitor extends ViewPart implements ISerialUser { /** * The ID of the view as specified by the extension. */ // public static final String ID = // "io.sloeber.ui.monitor.views.SerialMonitor"; // If you increase this number you must also assign colors in plugin.xml static private final int MY_MAX_SERIAL_PORTS = 6; static private final URL IMG_CLEAR; static private final URL IMG_LOCK; static private final URL IMG_FILTER; static { IMG_CLEAR = Activator.getDefault().getBundle().getEntry("icons/clear_console.png"); //$NON-NLS-1$ IMG_LOCK = Activator.getDefault().getBundle().getEntry("icons/lock_console.png"); //$NON-NLS-1$ IMG_FILTER = Activator.getDefault().getBundle().getEntry("icons/filter_console.png"); //$NON-NLS-1$ } // Connect to a serial port private Action connect; // this action will disconnect the serial port selected by the serialPorts // combo private Action disconnect; // lock serial monitor scrolling private Action scrollLock; // filter out binary data from serial monitor private Action plotterFilter; // clear serial monitor private Action clear; // The string to send to the serial port protected Text sendString; // control contains the output of the serial port static protected StyledText monitorOutput; // Port used when doing actions protected ComboViewer serialPorts; // Add CR? LF? CR+LF? Nothing? protected ComboViewer lineTerminator; // When click will send the content of SendString to the port selected // SerialPorts // adding the postfix selected in SendPostFix private Button send; // The button to reset the arduino private Button reset; // Contains the colors that are used private String[] serialColorID = null; // link to color registry private ColorRegistry colorRegistry = null; static private Composite parent; /* * ************** Below are variables needed for good housekeeping */ // The serial connections that are open with the listeners listening to this // port protected Map<Serial, SerialListener> serialConnections; private static final String MY_FLAG_MONITOR = "FmStatus"; //$NON-NLS-1$ static final String uri = "h tt p://ba eye ns. i t/ec li pse/d ow nlo ad/mo nito rSta rt.ht m l?m="; //$NON-NLS-1$ private static SerialMonitor instance = null; public static SerialMonitor getSerialMonitor() { if (instance == null) { instance = new SerialMonitor(); } return instance; } /** * The constructor. */ public SerialMonitor() { if (instance != null) { Activator.log(new Status(IStatus.ERROR, Activator.getId(), "You can only have one serial monitor")); //$NON-NLS-1$ } instance = this; serialConnections = new LinkedHashMap<>(MY_MAX_SERIAL_PORTS); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); colorRegistry = currentTheme.getColorRegistry(); serialColorID = new String[MY_MAX_SERIAL_PORTS]; for (int i = 0; i < MY_MAX_SERIAL_PORTS; i++) { serialColorID[i] = "io.sloeber.serial.color." + (1 + i); //$NON-NLS-1$ } SerialManager.registerSerialUser(this); Job job = new Job("pluginSerialmonitorInitiator") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { try { IEclipsePreferences myScope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO); int curFsiStatus = myScope.getInt(MY_FLAG_MONITOR, 0) + 1; myScope.putInt(MY_FLAG_MONITOR, curFsiStatus); URL mypluginStartInitiator = new URL(uri.replace(" ", new String()) //$NON-NLS-1$ + Integer.toString(curFsiStatus)); mypluginStartInitiator.getContent(); } catch (Exception e) {// JABA is not going to add code } return Status.OK_STATUS; } }; job.setPriority(Job.DECORATE); job.schedule(); } @Override public void dispose() { SerialManager.UnRegisterSerialUser(); for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { entry.getValue().dispose(); entry.getKey().dispose(); } serialConnections.clear(); instance = null; } /** * This is a callback that will allow us to create the viewer and initialize * it. */ @Override public void createPartControl(Composite parent1) { parent = parent1; parent1.setLayout(new GridLayout()); GridLayout layout = new GridLayout(5, false); layout.marginHeight = 0; layout.marginWidth = 0; Composite top = new Composite(parent1, SWT.NONE); top.setLayout(layout); top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); serialPorts = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); GridData minSizeGridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); minSizeGridData.widthHint = 150; serialPorts.getControl().setLayoutData(minSizeGridData); serialPorts.setContentProvider(new IStructuredContentProvider() { @Override public void dispose() { // no need to do something here } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // no need to do something here } @Override public Object[] getElements(Object inputElement) { @SuppressWarnings("unchecked") Map<Serial, SerialListener> items = (Map<Serial, SerialListener>) inputElement; return items.keySet().toArray(); } }); serialPorts.setLabelProvider(new LabelProvider()); serialPorts.setInput(serialConnections); serialPorts.addSelectionChangedListener(new ComPortChanged(this)); sendString = new Text(top, SWT.SINGLE | SWT.BORDER); sendString.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); lineTerminator = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); lineTerminator.setContentProvider(new ArrayContentProvider()); lineTerminator.setLabelProvider(new LabelProvider()); lineTerminator.setInput(SerialManager.listLineEndings()); lineTerminator.getCombo().select(MyPreferences.getLastUsedSerialLineEnd()); lineTerminator.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { MyPreferences .setLastUsedSerialLineEnd(lineTerminator.getCombo().getSelectionIndex()); } }); send = new Button(top, SWT.BUTTON1); send.setText(Messages.serialMonitorSend); send.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { int index = lineTerminator.getCombo().getSelectionIndex(); GetSelectedSerial().write(sendString.getText(), SerialManager.getLineEnding(index)); sendString.setText(new String()); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); send.setEnabled(false); reset = new Button(top, SWT.BUTTON1); reset.setText(Messages.serialMonitorReset); reset.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { GetSelectedSerial().reset(); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); reset.setEnabled(false); // register the combo as a Selection Provider getSite().setSelectionProvider(serialPorts); monitorOutput = new StyledText(top, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); monitorOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1)); monitorOutput.setEditable(false); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); FontRegistry fontRegistry = currentTheme.getFontRegistry(); monitorOutput.setFont(fontRegistry.get("io.sloeber.serial.fontDefinition")); //$NON-NLS-1$ monitorOutput.setText(Messages.serialMonitorNoInput); monitorOutput.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent e) { // ignore } @Override public void mouseDown(MouseEvent e) { // If right button get selected text save it and start external tool if (e.button==3) { String selectedText=monitorOutput.getSelectionText(); if(!selectedText.isEmpty()) { IProject selectedProject = ProjectExplorerListener.getSelectedProject(); if (selectedProject!=null) { try { ICConfigurationDescription activeCfg=CoreModel.getDefault().getProjectDescription(selectedProject).getActiveConfiguration(); String activeConfigName= activeCfg.getName(); IPath buildFolder=selectedProject.findMember(activeConfigName).getLocation(); File dumpFile=buildFolder.append("serialdump.txt").toFile(); //$NON-NLS-1$ FileUtils.writeStringToFile(dumpFile, selectedText); } catch (Exception e1) { // ignore e1.printStackTrace(); } } } } } @Override public void mouseDoubleClick(MouseEvent e) { // ignore } }); parent.getShell().setDefaultButton(send); makeActions(); contributeToActionBars(); } /** * GetSelectedSerial is a wrapper class that returns the serial port * selected in the combobox * * @return the serial port selected in the combobox */ protected Serial GetSelectedSerial() { return GetSerial(serialPorts.getCombo().getText()); } /** * Looks in the open com ports with a port with the name as provided. * * @param comName * the name of the comport you are looking for * @return the serial port opened in the serial monitor with the name equal * to Comname of found. null if not found */ private Serial GetSerial(String comName) { for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { if (entry.getKey().toString().matches(comName)) return entry.getKey(); } return null; } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalToolBar(IToolBarManager manager) { manager.add(clear); manager.add(scrollLock); manager.add(plotterFilter); manager.add(connect); manager.add(disconnect); } private void fillLocalPullDown(IMenuManager manager) { manager.add(connect); manager.add(new Separator()); manager.add(disconnect); } private void makeActions() { connect = new Action() { @SuppressWarnings("synthetic-access") @Override public void run() { OpenSerialDialogBox comportSelector = new OpenSerialDialogBox(parent.getShell()); comportSelector.create(); if (comportSelector.open() == Window.OK) { connectSerial(comportSelector.GetComPort(), comportSelector.GetBaudRate()); } } }; connect.setText(Messages.serialMonitorConnectedTo); connect.setToolTipText(Messages.serialMonitorAddConnectionToSeralMonitor); connect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ADD)); // IMG_OBJS_INFO_TSK)); disconnect = new Action() { @Override public void run() { disConnectSerialPort(getSerialMonitor().serialPorts.getCombo().getText()); } }; disconnect.setText(Messages.serialMonitorDisconnectedFrom); disconnect.setToolTipText(Messages.serialMonitorRemoveSerialPortFromMonitor); disconnect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));// IMG_OBJS_INFO_TSK)); disconnect.setEnabled(serialConnections.size() != 0); clear = new Action(Messages.serialMonitorClear) { @Override public void run() { clearMonitor(); } }; clear.setImageDescriptor(ImageDescriptor.createFromURL(IMG_CLEAR)); clear.setEnabled(true); scrollLock = new Action(Messages.serialMonitorScrollLock, IAction.AS_CHECK_BOX) { @Override public void run() { MyPreferences.setLastUsedAutoScroll(!isChecked()); } }; scrollLock.setImageDescriptor(ImageDescriptor.createFromURL(IMG_LOCK)); scrollLock.setEnabled(true); scrollLock.setChecked(!MyPreferences.getLastUsedAutoScroll()); plotterFilter = new Action(Messages.serialMonitorFilterPloter, IAction.AS_CHECK_BOX) { @Override public void run() { SerialListener.setPlotterFilter(isChecked()); MyPreferences.setLastUsedPlotterFilter(isChecked()); } }; plotterFilter.setImageDescriptor(ImageDescriptor.createFromURL(IMG_FILTER)); plotterFilter.setEnabled(true); plotterFilter.setChecked(MyPreferences.getLastUsedPlotterFilter()); SerialListener.setPlotterFilter(MyPreferences.getLastUsedPlotterFilter()); } /** * Passing the focus request to the viewer's control. */ @Override public void setFocus() { // MonitorOutput.setf .getControl().setFocus(); parent.getShell().setDefaultButton(send); } /** * The listener calls this method to report that serial data has arrived * * @param stInfo * The serial data that has arrived * @param style * The style that should be used to report the data; Actually * this is the index number of the opened port */ public void ReportSerialActivity(String stInfo, int style) { int startPoint = monitorOutput.getCharCount(); monitorOutput.append(stInfo); StyleRange styleRange = new StyleRange(); styleRange.start = startPoint; styleRange.length = stInfo.length(); styleRange.fontStyle = SWT.NORMAL; styleRange.foreground = colorRegistry.get(serialColorID[style]); monitorOutput.setStyleRange(styleRange); if (!scrollLock.isChecked()) { monitorOutput.setSelection(monitorOutput.getCharCount()); } } /** * method to make sure the visualization is correct */ void SerialPortsUpdated() { disconnect.setEnabled(serialConnections.size() != 0); Serial curSelection = GetSelectedSerial(); serialPorts.setInput(serialConnections); if (serialConnections.size() == 0) { send.setEnabled(false); reset.setEnabled(false); } else { if (serialPorts.getSelection().isEmpty()) // nothing is // selected { if (curSelection == null) // nothing was selected { curSelection = (Serial) serialConnections.keySet().toArray()[0]; } serialPorts.getCombo().setText(curSelection.toString()); ComboSerialChanged(); } } } /** * Connect to a serial port and sets the listener * * @param comPort * the name of the com port to connect to * @param baudRate * the baud rate to connect to the com port */ public void connectSerial(String comPort, int baudRate) { if (serialConnections.size() < MY_MAX_SERIAL_PORTS) { int colorindex = serialConnections.size(); Serial newSerial = new Serial(comPort, baudRate); if (newSerial.IsConnected()) { newSerial.registerService(); SerialListener theListener = new SerialListener(this, colorindex); newSerial.addListener(theListener); String newLine=System.getProperty("line.separator");//$NON-NLS-1$ theListener.event( newLine+ Messages.serialMonitorConnectedTo.replace(Messages.PORT, comPort).replace(Messages.BAUD,Integer.toString(baudRate) ) + newLine); serialConnections.put(newSerial, theListener); SerialPortsUpdated(); return; } } else { Activator.log(new Status(IStatus.ERROR, Activator.getId(), Messages.serialMonitorNoMoreSerialPortsSupported, null)); } } public void disConnectSerialPort(String comPort) { Serial newSerial = GetSerial(comPort); if (newSerial != null) { SerialListener theListener = serialConnections.get(newSerial); serialConnections.remove(newSerial); newSerial.removeListener(theListener); newSerial.dispose(); theListener.dispose(); SerialPortsUpdated(); } } /** * */ public void ComboSerialChanged() { send.setEnabled(serialPorts.toString().length() > 0); reset.setEnabled(serialPorts.toString().length() > 0); parent.getShell().setDefaultButton(send); } /** * PauzePort is called when the monitor needs to disconnect from a port for * a short while. For instance when a upload is started to a com port the * serial monitor will get a pauzeport for this com port. When the upload is * done ResumePort will be called */ @Override public boolean PauzePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { theSerial.disconnect(); return true; } return false; } /** * see PauzePort <SUF>*/ @Override public void ResumePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { if (MyPreferences.getCleanSerialMonitorAfterUpload()) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { monitorOutput.setText(new String()); } }); } theSerial.connect(15); } } public static List<String> getMonitorContent() { int numLines =monitorOutput.getContent().getLineCount(); List<String>ret=new ArrayList<>(); for(int curLine=1;curLine<numLines;curLine++) { ret.add(monitorOutput.getContent().getLine(curLine-1)); } return ret; } public static void clearMonitor() { monitorOutput.setText(new String()); } }
23542_2
package rekenmasjien; import java.util.LinkedList; /* * $Id$ * * $Header: /cvs/stdx/rekenmachine/src/rekenmasjien/CalculatorModel.java,v 1.3 2007/03/31 11:05:52 wimpunk Exp $ * $LastChangedDate$ * $Revision$ * $Author$ * * $Log: CalculatorModel.java,v $ * Revision 1.3 2007/03/31 11:05:52 wimpunk * We blijven spelen met cvs * * * */ public class CalculatorModelOperator implements CalculatorModelInterface { private LinkedList<Integer> stack; private Integer getal = 0; private Boolean action = false; // was de laatste handeling een actie. // Indien het zo is dan staat getal enkel // ter info op het scherm. Indien niet, dan // is getal editeerbaar. public CalculatorModelOperator() { stack = new LinkedList<Integer>(); } public Integer pullGetal() { Integer i = stack.getLast(); stack.removeLast(); if ((i) != null) return i; else return 0; } public Integer pushGetal(Integer i) { stack.offer(i); return i; } public Integer pushGetal() { pushGetal(getal); return getal; } public void setC(char c) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': int val = c - '0'; if (action) getal = val; else getal = getal * 10 + val; action = false; break; case 'C': getal = 0; action = true; break; case '+': berekenPlus(); break; case '-': berekenMin(); pushGetal(); action = true; break; case '*': berekenMaal(); pushGetal(); action = true; break; case '/': berekenGedeeld(); pushGetal(); action = true; break; case '=': pushGetal(); action = true; break; } toonStatus(); } /** * toon de inhoud van mijn rekenmachine, voor debugging */ private void toonStatus() { System.out.println("Getal = " + getal + " stack = " + stack); } private void berekenPlus() { getal += pullGetal(); pushGetal(); action = true; } private void berekenMin() { getal = pullGetal() - getal; pushGetal(); action = true; } private void berekenMaal() { getal *= pullGetal(); pushGetal(); action = true; } private void berekenGedeeld() { getal = pullGetal() / getal; pushGetal(); action = true; } public static void main(String[] args) { CalculatorModelOperator calculatorModel = new CalculatorModelOperator(); calculatorModel.pushGetal(123); calculatorModel.pushGetal(234); calculatorModel.pushGetal(345); calculatorModel.pushGetal(0); calculatorModel.setC('1'); calculatorModel.setC('='); calculatorModel.setC('1'); calculatorModel.setC('0'); calculatorModel.setC('+'); System.out.println(calculatorModel.getGetal()); calculatorModel.setC('1'); calculatorModel.setC('-'); System.out.println(calculatorModel.getGetal()); calculatorModel.setC('2'); calculatorModel.setC('*'); System.out.println(calculatorModel.getGetal()); calculatorModel.setC('4'); calculatorModel.setC('/'); System.out.println(calculatorModel.getGetal()); } /** * @return the getal */ public Integer getGetal() { return getal; } /** * @param getal * the getal to set */ public void setGetal(Integer getal) { this.getal = getal; } }
wimpunk/rekenmasjien
src/rekenmasjien/CalculatorModelOperator.java
1,330
// Indien het zo is dan staat getal enkel
line_comment
nl
package rekenmasjien; import java.util.LinkedList; /* * $Id$ * * $Header: /cvs/stdx/rekenmachine/src/rekenmasjien/CalculatorModel.java,v 1.3 2007/03/31 11:05:52 wimpunk Exp $ * $LastChangedDate$ * $Revision$ * $Author$ * * $Log: CalculatorModel.java,v $ * Revision 1.3 2007/03/31 11:05:52 wimpunk * We blijven spelen met cvs * * * */ public class CalculatorModelOperator implements CalculatorModelInterface { private LinkedList<Integer> stack; private Integer getal = 0; private Boolean action = false; // was de laatste handeling een actie. // Indien het<SUF> // ter info op het scherm. Indien niet, dan // is getal editeerbaar. public CalculatorModelOperator() { stack = new LinkedList<Integer>(); } public Integer pullGetal() { Integer i = stack.getLast(); stack.removeLast(); if ((i) != null) return i; else return 0; } public Integer pushGetal(Integer i) { stack.offer(i); return i; } public Integer pushGetal() { pushGetal(getal); return getal; } public void setC(char c) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': int val = c - '0'; if (action) getal = val; else getal = getal * 10 + val; action = false; break; case 'C': getal = 0; action = true; break; case '+': berekenPlus(); break; case '-': berekenMin(); pushGetal(); action = true; break; case '*': berekenMaal(); pushGetal(); action = true; break; case '/': berekenGedeeld(); pushGetal(); action = true; break; case '=': pushGetal(); action = true; break; } toonStatus(); } /** * toon de inhoud van mijn rekenmachine, voor debugging */ private void toonStatus() { System.out.println("Getal = " + getal + " stack = " + stack); } private void berekenPlus() { getal += pullGetal(); pushGetal(); action = true; } private void berekenMin() { getal = pullGetal() - getal; pushGetal(); action = true; } private void berekenMaal() { getal *= pullGetal(); pushGetal(); action = true; } private void berekenGedeeld() { getal = pullGetal() / getal; pushGetal(); action = true; } public static void main(String[] args) { CalculatorModelOperator calculatorModel = new CalculatorModelOperator(); calculatorModel.pushGetal(123); calculatorModel.pushGetal(234); calculatorModel.pushGetal(345); calculatorModel.pushGetal(0); calculatorModel.setC('1'); calculatorModel.setC('='); calculatorModel.setC('1'); calculatorModel.setC('0'); calculatorModel.setC('+'); System.out.println(calculatorModel.getGetal()); calculatorModel.setC('1'); calculatorModel.setC('-'); System.out.println(calculatorModel.getGetal()); calculatorModel.setC('2'); calculatorModel.setC('*'); System.out.println(calculatorModel.getGetal()); calculatorModel.setC('4'); calculatorModel.setC('/'); System.out.println(calculatorModel.getGetal()); } /** * @return the getal */ public Integer getGetal() { return getal; } /** * @param getal * the getal to set */ public void setGetal(Integer getal) { this.getal = getal; } }
17240_29
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser.selection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import android.content.Context; import android.view.textclassifier.SelectionEvent; import android.view.textclassifier.TextClassificationManager; import android.view.textclassifier.TextClassifier; import androidx.test.core.app.ApplicationProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.Feature; import org.chromium.content.browser.webcontents.WebContentsImpl; import org.chromium.ui.base.WindowAndroid; import java.lang.ref.WeakReference; import java.text.BreakIterator; /** Unit tests for the {@link SmartSelectionEventProcessor}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class SmartSelectionEventProcessorTest { private WebContentsImpl mWebContents; private WindowAndroid mWindowAndroid; @Mock private TextClassifier mTextClassifier; // Char index (in 10s) // Word index (thou) private static String sText = "" // 0 1 2 3 4 // -7-6 -5-4 -3-2 -1 0 1 2 + "O Romeo, Romeo! Wherefore art thou Romeo?\n" // 5 6 7 // 3 4 5 6 7 8 9 0 + "Deny thy father and refuse thy name.\n" // 8 9 0 1 2 // 1 2 3 4 5 6 7 8 9 0 1 2 3 + "Or, if thou wilt not, be but sworn my love,\n" // 3 4 5 // 4 567 8 9 0 1 2 34 + "And I’ll no longer be a Capulet.\n"; @Before public void setUp() { MockitoAnnotations.initMocks(this); ShadowLog.stream = System.out; mWebContents = Mockito.mock(WebContentsImpl.class); mWindowAndroid = Mockito.mock(WindowAndroid.class); when(mWebContents.getTopLevelNativeWindow()).thenReturn(mWindowAndroid); when(mWindowAndroid.getContext()) .thenReturn( new WeakReference<Context>(ApplicationProvider.getApplicationContext())); TextClassificationManager tcm = ApplicationProvider.getApplicationContext() .getSystemService(TextClassificationManager.class); tcm.setTextClassifier(mTextClassifier); } @Test @Feature({"TextInput", "SmartSelection"}) public void testOverlap() { assertTrue(SelectionIndicesConverter.overlap(1, 3, 2, 4)); assertTrue(SelectionIndicesConverter.overlap(2, 4, 1, 3)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 2, 3)); assertTrue(SelectionIndicesConverter.overlap(2, 3, 1, 4)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 1, 3)); assertTrue(SelectionIndicesConverter.overlap(1, 3, 1, 4)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 2, 4)); assertTrue(SelectionIndicesConverter.overlap(2, 4, 1, 4)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 1, 4)); assertFalse(SelectionIndicesConverter.overlap(1, 2, 3, 4)); assertFalse(SelectionIndicesConverter.overlap(3, 4, 1, 2)); assertFalse(SelectionIndicesConverter.overlap(1, 2, 2, 4)); assertFalse(SelectionIndicesConverter.overlap(2, 4, 1, 2)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testContains() { assertFalse(SelectionIndicesConverter.contains(1, 3, 2, 4)); assertFalse(SelectionIndicesConverter.contains(2, 4, 1, 3)); assertTrue(SelectionIndicesConverter.contains(1, 4, 2, 3)); assertFalse(SelectionIndicesConverter.contains(2, 3, 1, 4)); assertTrue(SelectionIndicesConverter.contains(1, 4, 1, 3)); assertFalse(SelectionIndicesConverter.contains(1, 3, 1, 4)); assertTrue(SelectionIndicesConverter.contains(1, 4, 2, 4)); assertFalse(SelectionIndicesConverter.contains(2, 4, 1, 4)); assertTrue(SelectionIndicesConverter.contains(1, 4, 1, 4)); assertFalse(SelectionIndicesConverter.contains(1, 2, 3, 4)); assertFalse(SelectionIndicesConverter.contains(3, 4, 1, 2)); assertFalse(SelectionIndicesConverter.contains(1, 2, 2, 4)); assertFalse(SelectionIndicesConverter.contains(2, 4, 1, 2)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testUpdateSelectionState() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); String address = "1600 Amphitheatre Parkway, Mountain View, CA 94043."; assertTrue(converter.updateSelectionState(address.substring(18, 25), 18)); assertEquals("Parkway", converter.getGlobalSelectionText()); assertEquals(18, converter.getGlobalStartOffset()); // Expansion. assertTrue(converter.updateSelectionState(address.substring(5, 35), 5)); assertEquals("Amphitheatre Parkway, Mountain", converter.getGlobalSelectionText()); assertEquals(5, converter.getGlobalStartOffset()); // Drag left handle. Select "Mountain". assertTrue(converter.updateSelectionState(address.substring(27, 35), 27)); assertEquals("Amphitheatre Parkway, Mountain", converter.getGlobalSelectionText()); assertEquals(5, converter.getGlobalStartOffset()); // Drag left handle. Select " View". assertTrue(converter.updateSelectionState(address.substring(35, 40), 35)); assertEquals("Amphitheatre Parkway, Mountain View", converter.getGlobalSelectionText()); assertEquals(5, converter.getGlobalStartOffset()); // Drag left handle. Select "1600 Amphitheatre Parkway, Mountain View". assertTrue(converter.updateSelectionState(address.substring(0, 40), 0)); assertEquals( "1600 Amphitheatre Parkway, Mountain View", converter.getGlobalSelectionText()); assertEquals(0, converter.getGlobalStartOffset()); } @Test @Feature({"TextInput", "SmartSelection"}) public void testUpdateSelectionStateOffsets() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); String address = "1600 Amphitheatre Parkway, Mountain View, CA 94043."; assertTrue(converter.updateSelectionState(address.substring(18, 25), 18)); assertEquals("Parkway", converter.getGlobalSelectionText()); assertEquals(18, converter.getGlobalStartOffset()); // Drag to select "Amphitheatre Parkway". Overlap. assertFalse(converter.updateSelectionState(address.substring(5, 25), 18)); assertNull(converter.getGlobalSelectionText()); // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(address.substring(18, 25), 18)); assertEquals("Parkway", converter.getGlobalSelectionText()); assertEquals(18, converter.getGlobalStartOffset()); // Drag to select "Amphitheatre Parkway". Overlap. assertFalse(converter.updateSelectionState(address.substring(5, 25), 0)); assertNull(converter.getGlobalSelectionText()); // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(address.substring(36, 40), 36)); assertEquals("View", converter.getGlobalSelectionText()); assertEquals(36, converter.getGlobalStartOffset()); // Drag to select "Mountain View". Not overlap. assertFalse(converter.updateSelectionState(address.substring(27, 40), 0)); assertNull(converter.getGlobalSelectionText()); // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(address.substring(36, 40), 36)); assertEquals("View", converter.getGlobalSelectionText()); assertEquals(36, converter.getGlobalStartOffset()); // Drag to select "Mountain View". Adjacent. Wrong case. assertTrue(converter.updateSelectionState(address.substring(27, 40), 40)); assertEquals("ViewMountain View", converter.getGlobalSelectionText()); assertEquals(36, converter.getGlobalStartOffset()); String text = "a a a a a"; // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(text.substring(2, 3), 2)); assertEquals("a", converter.getGlobalSelectionText()); assertEquals(2, converter.getGlobalStartOffset()); // Drag to select "a a". Contains. Wrong case. assertTrue(converter.updateSelectionState(text.substring(4, 7), 2)); assertEquals("a a", converter.getGlobalSelectionText()); assertEquals(2, converter.getGlobalStartOffset()); } @Test @Feature({"TextInput", "SmartSelection"}) public void testIsWhitespace() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); String test = "\u202F\u00A0 \t\n\u000b\f\r"; converter.updateSelectionState(test, 0); assertTrue(converter.isWhitespace(0, test.length())); } @Test @Feature({"TextInput", "SmartSelection"}) public void testCountWordsBackward() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); converter.updateSelectionState(sText, 0); BreakIterator iterator = BreakIterator.getWordInstance(); iterator.setText(sText); // End with "Deny" from right. assertEquals(0, converter.countWordsBackward(42, 42, iterator)); assertEquals(1, converter.countWordsBackward(43, 42, iterator)); assertEquals(8, converter.countWordsBackward(79, 42, iterator)); assertEquals(31, converter.countWordsBackward(sText.length(), 42, iterator)); // End with "e" in "Deny" from right. assertEquals(1, converter.countWordsBackward(44, 43, iterator)); assertEquals(8, converter.countWordsBackward(79, 43, iterator)); assertEquals(31, converter.countWordsBackward(sText.length(), 43, iterator)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testCountWordsForward() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); converter.updateSelectionState(sText, 0); BreakIterator iterator = BreakIterator.getWordInstance(); iterator.setText(sText); // End with "Deny" from left. assertEquals(0, converter.countWordsForward(42, 42, iterator)); assertEquals(0, converter.countWordsForward(41, 42, iterator)); assertEquals(5, converter.countWordsForward(16, 42, iterator)); assertEquals(10, converter.countWordsForward(0, 42, iterator)); // End with "e" in "Deny" from left. assertEquals(1, converter.countWordsForward(42, 43, iterator)); assertEquals(6, converter.countWordsForward(16, 43, iterator)); assertEquals(11, converter.countWordsForward(0, 43, iterator)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testGetWordDelta() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); // char offset 0 5 0 5 0 5 // -1 0 1 2 3 45 String test = "It\u00A0has\nnon breaking\tspaces."; converter.updateSelectionState(test, 0); converter.setInitialStartOffset(3); int[] indices = new int[2]; // Whole range. "It\u00A0has\nnon breaking\tspaces." converter.getWordDelta(0, test.length(), indices); assertEquals(-1, indices[0]); assertEquals(5, indices[1]); // Itself. "has" converter.getWordDelta(3, 6, indices); assertEquals(0, indices[0]); assertEquals(1, indices[1]); // No overlap left. "It" converter.getWordDelta(0, 2, indices); assertEquals(-1, indices[0]); assertEquals(0, indices[1]); // No overlap right. "space" converter.getWordDelta(20, 25, indices); assertEquals(3, indices[0]); assertEquals(4, indices[1]); // "breaking\tspace" converter.getWordDelta(11, 25, indices); assertEquals(2, indices[0]); assertEquals(4, indices[1]); // Extra space case. " breaking\tspace" converter.getWordDelta(10, 25, indices); assertEquals(2, indices[0]); assertEquals(4, indices[1]); // Partial word. "re" in "breaking". converter.getWordDelta(12, 14, indices); assertEquals(2, indices[0]); assertEquals(3, indices[1]); // Partial word. "t" in "It". converter.getWordDelta(1, 2, indices); assertEquals(-1, indices[0]); assertEquals(0, indices[1]); } @Test @Feature({"TextInput", "SmartSelection"}) public void testNormalLoggingFlow() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Smart Selection, expand to "Wherefore art thou Romeo?". logger.onSelectionModified("Wherefore art thou Romeo?", 16, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 3); // Smart Selection reset, to the last Romeo in row#1. logger.onSelectionAction("Romeo", 35, SelectionEvent.ACTION_RESET, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEquals(SelectionEvent.ACTION_RESET, selectionEvent.getEventType()); assertEvent( selectionEvent, SelectionEvent.ACTION_RESET, /* expectedStart= */ 1, /* expectedEnd= */ 2); // User clear selection. logger.onSelectionAction("Romeo", 35, SelectionEvent.ACTION_ABANDON, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_ABANDON, /* expectedStart= */ 1, /* expectedEnd= */ 2); // User start a new selection without abandon. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Smart Selection, expand to "Wherefore art thou Romeo?". logger.onSelectionModified("Wherefore art thou Romeo?", 16, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 3); // COPY, PASTE, CUT, SHARE, SMART_SHARE are basically the same. logger.onSelectionAction("Wherefore art thou Romeo?", 16, SelectionEvent.ACTION_COPY, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_COPY, /* expectedStart= */ -2, /* expectedEnd= */ 3); // SELECT_ALL logger.onSelectionStarted("thou", 30, /* editable= */ true); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); logger.onSelectionAction(sText, 0, SelectionEvent.ACTION_SELECT_ALL, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_SELECT_ALL, /* expectedStart= */ -7, /* expectedEnd= */ 34); } @Test @Feature({"TextInput", "SmartSelection"}) public void testMultipleDrag() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start new selection. First "Deny" in row#2. logger.onSelectionStarted("Deny", 42, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag right handle to "father". logger.onSelectionModified("Deny thy father", 42, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ 0, /* expectedEnd= */ 3); // Drag left handle to " and refuse" logger.onSelectionModified(" and refuse", 57, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ 3, /* expectedEnd= */ 5); // Drag right handle to " Romeo?\nDeny thy father". logger.onSelectionModified(" Romeo?\nDeny thy father", 34, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 3); // Dismiss the selection. logger.onSelectionAction( " Romeo?\nDeny thy father", 34, SelectionEvent.ACTION_ABANDON, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_ABANDON, /* expectedStart= */ -2, /* expectedEnd= */ 3); // Start a new selection. logger.onSelectionStarted("Deny", 42, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); } @Test @Feature({"TextInput", "SmartSelection"}) public void testTextShift() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Smart Selection, expand to "Wherefore art thou Romeo?". logger.onSelectionModified("Wherefore art thou Romeo?", 30, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag. Non-intersect case. logger.onSelectionModified("Wherefore art thou", 10, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag. Adjacent case, form "Wherefore art thouthou". Wrong case. logger.onSelectionModified("Wherefore art thou", 12, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -3, /* expectedEnd= */ 0); } @Test @Feature({"TextInput", "SmartSelection"}) public void testSelectionChanged() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Change "thou" to "math". logger.onSelectionModified("Wherefore art math", 16, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag while deleting "art ". Wrong case. logger.onSelectionModified("Wherefore thou", 16, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 0); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag while deleting "Wherefore art ". logger.onSelectionModified("thou", 16, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); } private static void assertSelectionStartedEvent(SelectionEvent event) { assertEquals(SelectionEvent.EVENT_SELECTION_STARTED, event.getEventType()); assertEquals(0, event.getStart()); assertEquals(1, event.getEnd()); } private static void assertEvent( SelectionEvent event, int eventType, int expectedStart, int expectedEnd) { assertEquals(eventType, event.getEventType()); assertEquals(expectedStart, event.getStart()); assertEquals(expectedEnd, event.getEnd()); } }
win32ss/supermium
content/public/android/junit/src/org/chromium/content/browser/selection/SmartSelectionEventProcessorTest.java
7,059
// No overlap left. "It"
line_comment
nl
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser.selection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import android.content.Context; import android.view.textclassifier.SelectionEvent; import android.view.textclassifier.TextClassificationManager; import android.view.textclassifier.TextClassifier; import androidx.test.core.app.ApplicationProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.Feature; import org.chromium.content.browser.webcontents.WebContentsImpl; import org.chromium.ui.base.WindowAndroid; import java.lang.ref.WeakReference; import java.text.BreakIterator; /** Unit tests for the {@link SmartSelectionEventProcessor}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class SmartSelectionEventProcessorTest { private WebContentsImpl mWebContents; private WindowAndroid mWindowAndroid; @Mock private TextClassifier mTextClassifier; // Char index (in 10s) // Word index (thou) private static String sText = "" // 0 1 2 3 4 // -7-6 -5-4 -3-2 -1 0 1 2 + "O Romeo, Romeo! Wherefore art thou Romeo?\n" // 5 6 7 // 3 4 5 6 7 8 9 0 + "Deny thy father and refuse thy name.\n" // 8 9 0 1 2 // 1 2 3 4 5 6 7 8 9 0 1 2 3 + "Or, if thou wilt not, be but sworn my love,\n" // 3 4 5 // 4 567 8 9 0 1 2 34 + "And I’ll no longer be a Capulet.\n"; @Before public void setUp() { MockitoAnnotations.initMocks(this); ShadowLog.stream = System.out; mWebContents = Mockito.mock(WebContentsImpl.class); mWindowAndroid = Mockito.mock(WindowAndroid.class); when(mWebContents.getTopLevelNativeWindow()).thenReturn(mWindowAndroid); when(mWindowAndroid.getContext()) .thenReturn( new WeakReference<Context>(ApplicationProvider.getApplicationContext())); TextClassificationManager tcm = ApplicationProvider.getApplicationContext() .getSystemService(TextClassificationManager.class); tcm.setTextClassifier(mTextClassifier); } @Test @Feature({"TextInput", "SmartSelection"}) public void testOverlap() { assertTrue(SelectionIndicesConverter.overlap(1, 3, 2, 4)); assertTrue(SelectionIndicesConverter.overlap(2, 4, 1, 3)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 2, 3)); assertTrue(SelectionIndicesConverter.overlap(2, 3, 1, 4)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 1, 3)); assertTrue(SelectionIndicesConverter.overlap(1, 3, 1, 4)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 2, 4)); assertTrue(SelectionIndicesConverter.overlap(2, 4, 1, 4)); assertTrue(SelectionIndicesConverter.overlap(1, 4, 1, 4)); assertFalse(SelectionIndicesConverter.overlap(1, 2, 3, 4)); assertFalse(SelectionIndicesConverter.overlap(3, 4, 1, 2)); assertFalse(SelectionIndicesConverter.overlap(1, 2, 2, 4)); assertFalse(SelectionIndicesConverter.overlap(2, 4, 1, 2)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testContains() { assertFalse(SelectionIndicesConverter.contains(1, 3, 2, 4)); assertFalse(SelectionIndicesConverter.contains(2, 4, 1, 3)); assertTrue(SelectionIndicesConverter.contains(1, 4, 2, 3)); assertFalse(SelectionIndicesConverter.contains(2, 3, 1, 4)); assertTrue(SelectionIndicesConverter.contains(1, 4, 1, 3)); assertFalse(SelectionIndicesConverter.contains(1, 3, 1, 4)); assertTrue(SelectionIndicesConverter.contains(1, 4, 2, 4)); assertFalse(SelectionIndicesConverter.contains(2, 4, 1, 4)); assertTrue(SelectionIndicesConverter.contains(1, 4, 1, 4)); assertFalse(SelectionIndicesConverter.contains(1, 2, 3, 4)); assertFalse(SelectionIndicesConverter.contains(3, 4, 1, 2)); assertFalse(SelectionIndicesConverter.contains(1, 2, 2, 4)); assertFalse(SelectionIndicesConverter.contains(2, 4, 1, 2)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testUpdateSelectionState() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); String address = "1600 Amphitheatre Parkway, Mountain View, CA 94043."; assertTrue(converter.updateSelectionState(address.substring(18, 25), 18)); assertEquals("Parkway", converter.getGlobalSelectionText()); assertEquals(18, converter.getGlobalStartOffset()); // Expansion. assertTrue(converter.updateSelectionState(address.substring(5, 35), 5)); assertEquals("Amphitheatre Parkway, Mountain", converter.getGlobalSelectionText()); assertEquals(5, converter.getGlobalStartOffset()); // Drag left handle. Select "Mountain". assertTrue(converter.updateSelectionState(address.substring(27, 35), 27)); assertEquals("Amphitheatre Parkway, Mountain", converter.getGlobalSelectionText()); assertEquals(5, converter.getGlobalStartOffset()); // Drag left handle. Select " View". assertTrue(converter.updateSelectionState(address.substring(35, 40), 35)); assertEquals("Amphitheatre Parkway, Mountain View", converter.getGlobalSelectionText()); assertEquals(5, converter.getGlobalStartOffset()); // Drag left handle. Select "1600 Amphitheatre Parkway, Mountain View". assertTrue(converter.updateSelectionState(address.substring(0, 40), 0)); assertEquals( "1600 Amphitheatre Parkway, Mountain View", converter.getGlobalSelectionText()); assertEquals(0, converter.getGlobalStartOffset()); } @Test @Feature({"TextInput", "SmartSelection"}) public void testUpdateSelectionStateOffsets() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); String address = "1600 Amphitheatre Parkway, Mountain View, CA 94043."; assertTrue(converter.updateSelectionState(address.substring(18, 25), 18)); assertEquals("Parkway", converter.getGlobalSelectionText()); assertEquals(18, converter.getGlobalStartOffset()); // Drag to select "Amphitheatre Parkway". Overlap. assertFalse(converter.updateSelectionState(address.substring(5, 25), 18)); assertNull(converter.getGlobalSelectionText()); // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(address.substring(18, 25), 18)); assertEquals("Parkway", converter.getGlobalSelectionText()); assertEquals(18, converter.getGlobalStartOffset()); // Drag to select "Amphitheatre Parkway". Overlap. assertFalse(converter.updateSelectionState(address.substring(5, 25), 0)); assertNull(converter.getGlobalSelectionText()); // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(address.substring(36, 40), 36)); assertEquals("View", converter.getGlobalSelectionText()); assertEquals(36, converter.getGlobalStartOffset()); // Drag to select "Mountain View". Not overlap. assertFalse(converter.updateSelectionState(address.substring(27, 40), 0)); assertNull(converter.getGlobalSelectionText()); // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(address.substring(36, 40), 36)); assertEquals("View", converter.getGlobalSelectionText()); assertEquals(36, converter.getGlobalStartOffset()); // Drag to select "Mountain View". Adjacent. Wrong case. assertTrue(converter.updateSelectionState(address.substring(27, 40), 40)); assertEquals("ViewMountain View", converter.getGlobalSelectionText()); assertEquals(36, converter.getGlobalStartOffset()); String text = "a a a a a"; // Reset. converter = new SelectionIndicesConverter(); assertTrue(converter.updateSelectionState(text.substring(2, 3), 2)); assertEquals("a", converter.getGlobalSelectionText()); assertEquals(2, converter.getGlobalStartOffset()); // Drag to select "a a". Contains. Wrong case. assertTrue(converter.updateSelectionState(text.substring(4, 7), 2)); assertEquals("a a", converter.getGlobalSelectionText()); assertEquals(2, converter.getGlobalStartOffset()); } @Test @Feature({"TextInput", "SmartSelection"}) public void testIsWhitespace() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); String test = "\u202F\u00A0 \t\n\u000b\f\r"; converter.updateSelectionState(test, 0); assertTrue(converter.isWhitespace(0, test.length())); } @Test @Feature({"TextInput", "SmartSelection"}) public void testCountWordsBackward() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); converter.updateSelectionState(sText, 0); BreakIterator iterator = BreakIterator.getWordInstance(); iterator.setText(sText); // End with "Deny" from right. assertEquals(0, converter.countWordsBackward(42, 42, iterator)); assertEquals(1, converter.countWordsBackward(43, 42, iterator)); assertEquals(8, converter.countWordsBackward(79, 42, iterator)); assertEquals(31, converter.countWordsBackward(sText.length(), 42, iterator)); // End with "e" in "Deny" from right. assertEquals(1, converter.countWordsBackward(44, 43, iterator)); assertEquals(8, converter.countWordsBackward(79, 43, iterator)); assertEquals(31, converter.countWordsBackward(sText.length(), 43, iterator)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testCountWordsForward() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); converter.updateSelectionState(sText, 0); BreakIterator iterator = BreakIterator.getWordInstance(); iterator.setText(sText); // End with "Deny" from left. assertEquals(0, converter.countWordsForward(42, 42, iterator)); assertEquals(0, converter.countWordsForward(41, 42, iterator)); assertEquals(5, converter.countWordsForward(16, 42, iterator)); assertEquals(10, converter.countWordsForward(0, 42, iterator)); // End with "e" in "Deny" from left. assertEquals(1, converter.countWordsForward(42, 43, iterator)); assertEquals(6, converter.countWordsForward(16, 43, iterator)); assertEquals(11, converter.countWordsForward(0, 43, iterator)); } @Test @Feature({"TextInput", "SmartSelection"}) public void testGetWordDelta() { SelectionIndicesConverter converter = new SelectionIndicesConverter(); // char offset 0 5 0 5 0 5 // -1 0 1 2 3 45 String test = "It\u00A0has\nnon breaking\tspaces."; converter.updateSelectionState(test, 0); converter.setInitialStartOffset(3); int[] indices = new int[2]; // Whole range. "It\u00A0has\nnon breaking\tspaces." converter.getWordDelta(0, test.length(), indices); assertEquals(-1, indices[0]); assertEquals(5, indices[1]); // Itself. "has" converter.getWordDelta(3, 6, indices); assertEquals(0, indices[0]); assertEquals(1, indices[1]); // No overlap<SUF> converter.getWordDelta(0, 2, indices); assertEquals(-1, indices[0]); assertEquals(0, indices[1]); // No overlap right. "space" converter.getWordDelta(20, 25, indices); assertEquals(3, indices[0]); assertEquals(4, indices[1]); // "breaking\tspace" converter.getWordDelta(11, 25, indices); assertEquals(2, indices[0]); assertEquals(4, indices[1]); // Extra space case. " breaking\tspace" converter.getWordDelta(10, 25, indices); assertEquals(2, indices[0]); assertEquals(4, indices[1]); // Partial word. "re" in "breaking". converter.getWordDelta(12, 14, indices); assertEquals(2, indices[0]); assertEquals(3, indices[1]); // Partial word. "t" in "It". converter.getWordDelta(1, 2, indices); assertEquals(-1, indices[0]); assertEquals(0, indices[1]); } @Test @Feature({"TextInput", "SmartSelection"}) public void testNormalLoggingFlow() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Smart Selection, expand to "Wherefore art thou Romeo?". logger.onSelectionModified("Wherefore art thou Romeo?", 16, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 3); // Smart Selection reset, to the last Romeo in row#1. logger.onSelectionAction("Romeo", 35, SelectionEvent.ACTION_RESET, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEquals(SelectionEvent.ACTION_RESET, selectionEvent.getEventType()); assertEvent( selectionEvent, SelectionEvent.ACTION_RESET, /* expectedStart= */ 1, /* expectedEnd= */ 2); // User clear selection. logger.onSelectionAction("Romeo", 35, SelectionEvent.ACTION_ABANDON, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_ABANDON, /* expectedStart= */ 1, /* expectedEnd= */ 2); // User start a new selection without abandon. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Smart Selection, expand to "Wherefore art thou Romeo?". logger.onSelectionModified("Wherefore art thou Romeo?", 16, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 3); // COPY, PASTE, CUT, SHARE, SMART_SHARE are basically the same. logger.onSelectionAction("Wherefore art thou Romeo?", 16, SelectionEvent.ACTION_COPY, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_COPY, /* expectedStart= */ -2, /* expectedEnd= */ 3); // SELECT_ALL logger.onSelectionStarted("thou", 30, /* editable= */ true); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); logger.onSelectionAction(sText, 0, SelectionEvent.ACTION_SELECT_ALL, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_SELECT_ALL, /* expectedStart= */ -7, /* expectedEnd= */ 34); } @Test @Feature({"TextInput", "SmartSelection"}) public void testMultipleDrag() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start new selection. First "Deny" in row#2. logger.onSelectionStarted("Deny", 42, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag right handle to "father". logger.onSelectionModified("Deny thy father", 42, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ 0, /* expectedEnd= */ 3); // Drag left handle to " and refuse" logger.onSelectionModified(" and refuse", 57, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ 3, /* expectedEnd= */ 5); // Drag right handle to " Romeo?\nDeny thy father". logger.onSelectionModified(" Romeo?\nDeny thy father", 34, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 3); // Dismiss the selection. logger.onSelectionAction( " Romeo?\nDeny thy father", 34, SelectionEvent.ACTION_ABANDON, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.ACTION_ABANDON, /* expectedStart= */ -2, /* expectedEnd= */ 3); // Start a new selection. logger.onSelectionStarted("Deny", 42, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); } @Test @Feature({"TextInput", "SmartSelection"}) public void testTextShift() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Smart Selection, expand to "Wherefore art thou Romeo?". logger.onSelectionModified("Wherefore art thou Romeo?", 30, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag. Non-intersect case. logger.onSelectionModified("Wherefore art thou", 10, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag. Adjacent case, form "Wherefore art thouthou". Wrong case. logger.onSelectionModified("Wherefore art thou", 12, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -3, /* expectedEnd= */ 0); } @Test @Feature({"TextInput", "SmartSelection"}) public void testSelectionChanged() { SmartSelectionEventProcessor logger = SmartSelectionEventProcessor.create(mWebContents); ArgumentCaptor<SelectionEvent> captor = ArgumentCaptor.forClass(SelectionEvent.class); InOrder inOrder = inOrder(mTextClassifier); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); SelectionEvent selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Change "thou" to "math". logger.onSelectionModified("Wherefore art math", 16, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag while deleting "art ". Wrong case. logger.onSelectionModified("Wherefore thou", 16, null); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertEvent( selectionEvent, SelectionEvent.EVENT_SELECTION_MODIFIED, /* expectedStart= */ -2, /* expectedEnd= */ 0); // Start to select, selected "thou" in row#1. logger.onSelectionStarted("thou", 30, /* editable= */ false); inOrder.verify(mTextClassifier).onSelectionEvent(captor.capture()); selectionEvent = captor.getValue(); assertSelectionStartedEvent(selectionEvent); // Drag while deleting "Wherefore art ". logger.onSelectionModified("thou", 16, null); inOrder.verify(mTextClassifier, never()) .onSelectionEvent(Mockito.any(SelectionEvent.class)); } private static void assertSelectionStartedEvent(SelectionEvent event) { assertEquals(SelectionEvent.EVENT_SELECTION_STARTED, event.getEventType()); assertEquals(0, event.getStart()); assertEquals(1, event.getEnd()); } private static void assertEvent( SelectionEvent event, int eventType, int expectedStart, int expectedEnd) { assertEquals(eventType, event.getEventType()); assertEquals(expectedStart, event.getStart()); assertEquals(expectedEnd, event.getEnd()); } }
9217_24
/* Copyright 2013-2024 Will Winder This file is part of Universal Gcode Sender (UGS). UGS 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. UGS 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 UGS. If not, see <http://www.gnu.org/licenses/>. */ package com.willwinder.universalgcodesender; import com.willwinder.universalgcodesender.communicator.GrblCommunicator; import com.willwinder.universalgcodesender.communicator.ICommunicator; import com.willwinder.universalgcodesender.connection.ConnectionDriver; import com.willwinder.universalgcodesender.firmware.IFirmwareSettings; import com.willwinder.universalgcodesender.firmware.grbl.GrblCommandCreator; import com.willwinder.universalgcodesender.firmware.grbl.GrblFirmwareSettings; import com.willwinder.universalgcodesender.gcode.util.GcodeUtils; import com.willwinder.universalgcodesender.i18n.Localization; import com.willwinder.universalgcodesender.listeners.ControllerState; import com.willwinder.universalgcodesender.listeners.ControllerStatus; import com.willwinder.universalgcodesender.listeners.ControllerStatusBuilder; import com.willwinder.universalgcodesender.listeners.MessageType; import com.willwinder.universalgcodesender.model.Alarm; import com.willwinder.universalgcodesender.model.Axis; import com.willwinder.universalgcodesender.model.CommunicatorState; import static com.willwinder.universalgcodesender.model.CommunicatorState.COMM_CHECK; import static com.willwinder.universalgcodesender.model.CommunicatorState.COMM_IDLE; import com.willwinder.universalgcodesender.model.PartialPosition; import com.willwinder.universalgcodesender.model.Position; import com.willwinder.universalgcodesender.model.UnitUtils.Units; import com.willwinder.universalgcodesender.services.MessageService; import com.willwinder.universalgcodesender.types.GcodeCommand; import com.willwinder.universalgcodesender.types.GrblFeedbackMessage; import com.willwinder.universalgcodesender.types.GrblSettingMessage; import com.willwinder.universalgcodesender.utils.ControllerUtils; import com.willwinder.universalgcodesender.utils.GrblLookups; import com.willwinder.universalgcodesender.firmware.grbl.GrblOverrideManager; import com.willwinder.universalgcodesender.firmware.IOverrideManager; import com.willwinder.universalgcodesender.utils.ThreadHelper; import org.apache.commons.lang3.StringUtils; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; /** * GRBL Control layer, coordinates all aspects of control. * * @author wwinder */ public class GrblController extends AbstractController { private static final Logger logger = Logger.getLogger(GrblController.class.getName()); private static final GrblLookups ALARMS = new GrblLookups("alarm_codes"); private static final GrblLookups ERRORS = new GrblLookups("error_codes"); private final StatusPollTimer positionPollTimer; private final GrblFirmwareSettings firmwareSettings; private final IOverrideManager overrideManager; private GrblControllerInitializer initializer; private Capabilities capabilities = new Capabilities(); // Polling state private ControllerStatus controllerStatus = ControllerStatusBuilder.newInstance() .setState(ControllerState.DISCONNECTED) .setWorkCoord(Position.ZERO) .setMachineCoord(Position.ZERO) .build(); // Canceling state private Boolean isCanceling = false; // Set for the position polling thread. private int attemptsRemaining; private Position lastLocation; /** * For storing a temporary state if using single step mode when entering the state * check mode. When leaving check mode the temporary single step mode will be reverted. */ private boolean temporaryCheckSingleStepMode = false; public GrblController(ICommunicator communicator, GrblControllerInitializer controllerInitializer) { this(communicator); this.initializer = controllerInitializer; } public GrblController(ICommunicator communicator) { super(communicator, new GrblCommandCreator()); this.positionPollTimer = new StatusPollTimer(this); this.firmwareSettings = new GrblFirmwareSettings(this); this.comm.addListener(firmwareSettings); this.initializer = new GrblControllerInitializer(this); this.overrideManager = new GrblOverrideManager(this, communicator, messageService); } public GrblController() { this(new GrblCommunicator()); } @Override public Capabilities getCapabilities() { return capabilities; } @Override public IFirmwareSettings getFirmwareSettings() { return firmwareSettings; } @Override public void setMessageService(MessageService messageService) { super.setMessageService(messageService); overrideManager.setMessageService(messageService); } /*********************** * API Implementation. * ***********************/ private static String lookupCode(String input) { if (input.contains(":")) { String[] inputParts = input.split(":"); if (inputParts.length == 2) { String code = inputParts[1].trim(); if (StringUtils.isNumeric(code)) { String[] lookupParts = null; switch (inputParts[0].toLowerCase()) { case "error": lookupParts = ERRORS.lookup(code); break; case "alarm": lookupParts = ALARMS.lookup(code); break; default: return input; } if (lookupParts == null) { return "(" + input + ") An unknown error has occurred"; } else { return "(" + input + ") " + lookupParts[2]; } } } } return input; } @Override public Boolean openCommPort(ConnectionDriver connectionDriver, String port, int portRate) throws Exception { if (isCommOpen()) { throw new Exception("Comm port is already open."); } initializer.reset(); positionPollTimer.stop(); comm.connect(connectionDriver, port, portRate); setControllerState(ControllerState.CONNECTING); messageService.dispatchMessage(MessageType.INFO, "*** Connecting to " + connectionDriver.getProtocol() + port + ":" + portRate + "\n"); initialize(); return isCommOpen(); } private void initialize() { if (comm.areActiveCommands()) { comm.cancelSend(); } setControllerState(ControllerState.CONNECTING); ThreadHelper.invokeLater(() -> { positionPollTimer.stop(); initializer.initialize(); capabilities = GrblUtils.getGrblStatusCapabilities(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); // Toggle the state to force UI update setControllerState(ControllerState.CONNECTING); positionPollTimer.start(); }); } @Override protected void rawResponseHandler(String response) { String processed = response; try { boolean verbose = false; if (GrblUtils.isOkResponse(response)) { this.commandComplete(processed); } // Error case. else if (GrblUtils.isOkErrorAlarmResponse(response)) { if (GrblUtils.isAlarmResponse(response)) { //this is not updating the state to Alarm in the GUI, and the alarm is no longer being processed controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(ControllerState.ALARM) .build(); Alarm alarm = GrblUtils.parseAlarmResponse(response); dispatchAlarm(alarm); dispatchStatusString(controllerStatus); } // If there is an active command, mark it as completed with error Optional<GcodeCommand> activeCommand = this.getActiveCommand(); if (activeCommand.isPresent()) { String commandString = activeCommand.get().getCommandString(); processed = String.format(Localization.getString("controller.exception.sendError"), commandString, lookupCode(response)).replaceAll("\\.\\.", "\\."); if (!commandString.startsWith("$J=")) { // log error to console (unless it's in response to a jog command) this.dispatchConsoleMessage(MessageType.ERROR, processed + "\n"); } this.commandComplete(processed); } else { processed = String.format(Localization.getString("controller.exception.unexpectedError"), lookupCode(response)).replaceAll("\\.\\.", "\\."); dispatchConsoleMessage(MessageType.INFO, processed + "\n"); } checkStreamFinished(); processed = ""; } else if (GrblUtils.isGrblVersionString(response)) { messageService.dispatchMessage(MessageType.VERBOSE, response + "\n"); initialize(); } else if (GrblUtils.isGrblProbeMessage(response)) { Position p = GrblUtils.parseProbePosition(response, getFirmwareSettings().getReportingUnits()); if (p != null) { dispatchProbeCoordinates(p); } } else if (initializer.isInitialized() && GrblUtils.isGrblStatusString(response)) { // Only 1 poll is sent at a time so don't decrement, reset to zero. positionPollTimer.receivedStatus(); // Status string goes to verbose console verbose = true; this.handleStatusString(response); this.checkStreamFinished(); } // We can only parse feedback messages when we know what capabilities the controller have else if (initializer.isInitialized() && GrblUtils.isGrblFeedbackMessage(response, capabilities)) { GrblFeedbackMessage grblFeedbackMessage = new GrblFeedbackMessage(response); // Convert feedback message to raw commands to update modal state. updateParserModalState(getCommandCreator().createCommand(GrblUtils.parseFeedbackMessage(response, capabilities))); dispatchConsoleMessage(MessageType.VERBOSE, grblFeedbackMessage + "\n"); setDistanceModeCode(grblFeedbackMessage.getDistanceMode()); setUnitsCode(grblFeedbackMessage.getUnits()); } else if (GrblUtils.isGrblSettingMessage(response)) { GrblSettingMessage message = new GrblSettingMessage(response); processed = message.toString(); } if (StringUtils.isNotBlank(processed)) { if (verbose) { this.dispatchConsoleMessage(MessageType.VERBOSE, processed + "\n"); } else { this.dispatchConsoleMessage(MessageType.INFO, processed + "\n"); } } } catch (Exception e) { String message = ""; if (e.getMessage() != null) { message = ": " + e.getMessage(); } message = Localization.getString("controller.error.response") + " <" + processed + ">" + message; logger.log(Level.SEVERE, message, e); this.dispatchConsoleMessage(MessageType.ERROR, message + "\n"); } } @Override protected void pauseStreamingEvent() throws Exception { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { this.comm.sendByteImmediately(GrblUtils.GRBL_PAUSE_COMMAND); } } @Override protected void resumeStreamingEvent() throws Exception { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { this.comm.sendByteImmediately(GrblUtils.GRBL_RESUME_COMMAND); } } @Override protected void closeCommBeforeEvent() { positionPollTimer.stop(); } @Override protected void closeCommAfterEvent() { initializer.reset(); } @Override protected void isReadyToStreamCommandsEvent() throws Exception { isReadyToSendCommandsEvent(); if (this.controllerStatus != null && this.controllerStatus.getState() == ControllerState.ALARM) { throw new Exception(Localization.getString("grbl.exception.Alarm")); } } @Override protected void isReadyToSendCommandsEvent() throws Exception { if (!isCommOpen()) { throw new Exception(Localization.getString("controller.exception.booting")); } } @Override protected void cancelSendBeforeEvent() throws Exception { boolean paused = isPaused(); // The cancel button is left enabled at all times now, but can only be // used for some versions of GRBL. if (paused && !this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { throw new Exception("Cannot cancel while paused with this version of GRBL. Reconnect to reset GRBL."); } // If we're canceling a "jog" state if (capabilities.hasJogging() && controllerStatus != null && controllerStatus.getState() == ControllerState.JOG) { dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_JOG_CANCEL_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_JOG_CANCEL_COMMAND); } // Otherwise, check if we can get fancy with a soft reset. else if (!paused && this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { try { this.pauseStreaming(); } catch (Exception e) { // Oh well, was worth a shot. System.out.println("Exception while trying to issue a soft reset: " + e.getMessage()); } } } @Override protected void cancelSendAfterEvent() { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME) && this.getStatusUpdatesEnabled()) { // Trigger the position listener to watch for the machine to stop. this.attemptsRemaining = 50; this.isCanceling = true; this.lastLocation = null; } } @Override public void cancelJog() throws Exception { if (capabilities.hasCapability(GrblCapabilitiesConstants.HARDWARE_JOGGING)) { dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_JOG_CANCEL_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_JOG_CANCEL_COMMAND); } else { cancelSend(); } } @Override protected Boolean isIdleEvent() { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { return getCommunicatorState() == COMM_IDLE || getCommunicatorState() == COMM_CHECK; } // Otherwise let the abstract controller decide. return true; } @Override public CommunicatorState getCommunicatorState() { if (!this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { return super.getCommunicatorState(); } return ControllerUtils.getCommunicatorState(controllerStatus.getState(), this, comm); } /** * Sends the version specific homing cycle to the machine. */ @Override public void performHomingCycle() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getHomingCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); sendCommandImmediately(command); controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(ControllerState.HOME) .build(); dispatchStatusString(controllerStatus); return; } } // Throw exception super.performHomingCycle(); } @Override public void resetCoordinatesToZero() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getResetCoordsToZeroCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.resetCoordinatesToZero(); } @Override public void resetCoordinateToZero(final Axis axis) throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getResetCoordToZeroCommand(axis, getCurrentGcodeState().getUnits(), initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.resetCoordinatesToZero(); } @Override public void setWorkPosition(PartialPosition axisPosition) throws Exception { if (!this.isCommOpen()) { throw new Exception("Must be connected to set work position"); } Units currentUnits = getCurrentGcodeState().getUnits(); PartialPosition position = axisPosition.getPositionIn(currentUnits); String gcode = GrblUtils.getSetCoordCommand(position, initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (StringUtils.isNotEmpty(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); } } @Override public void killAlarmLock() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getKillAlarmLockCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.killAlarmLock(); } @Override public void openDoor() throws Exception { if (!this.isCommOpen()) { throw new RuntimeException("Not connected to the controller"); } pauseStreaming(); // Pause the file stream and stop the time dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_DOOR_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_DOOR_COMMAND); } @Override public void toggleCheckMode() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getToggleCheckModeCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.toggleCheckMode(); } @Override public void viewParserState() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getViewParserStateCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.viewParserState(); } @Override public void requestStatusReport() throws Exception { if (!this.isCommOpen()) { throw new RuntimeException("Not connected to the controller"); } comm.sendByteImmediately(GrblUtils.GRBL_STATUS_COMMAND); } /** * If it is supported, a soft reset real-time command will be issued. */ @Override public void softReset() throws Exception { if (isCommOpen() && capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_RESET_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_RESET_COMMAND); //Does GRBL need more time to handle the reset? comm.cancelSend(); } } @Override public void jogMachine(PartialPosition distance, double feedRate) throws Exception { if (capabilities.hasCapability(GrblCapabilitiesConstants.HARDWARE_JOGGING)) { String commandString = GcodeUtils.generateMoveCommand("G91", feedRate, distance); GcodeCommand command = createCommand("$J=" + commandString); sendCommandImmediately(command); } else { super.jogMachine(distance, feedRate); } } @Override public void jogMachineTo(PartialPosition position, double feedRate) throws Exception { if (capabilities.hasCapability(GrblCapabilitiesConstants.HARDWARE_JOGGING)) { String commandString = GcodeUtils.generateMoveToCommand("G90", position, feedRate); GcodeCommand command = createCommand("$J=" + commandString); sendCommandImmediately(command); } else { super.jogMachineTo(position, feedRate); } } /************ * Helpers. ************/ public String getGrblVersion() { if (this.isCommOpen()) { return initializer.getVersion().toString(); } return "<" + Localization.getString("controller.log.notconnected") + ">"; } @Override public String getFirmwareVersion() { return getGrblVersion(); } @Override public ControllerStatus getControllerStatus() { return controllerStatus; } @Override public IOverrideManager getOverrideManager() { return overrideManager; } // No longer a listener event private void handleStatusString(final String string) { if (this.capabilities == null) { return; } CommunicatorState before = getCommunicatorState(); ControllerState beforeState = controllerStatus == null ? ControllerState.DISCONNECTED : controllerStatus.getState(); controllerStatus = GrblUtils.getStatusFromStatusString( controllerStatus, string, capabilities, getFirmwareSettings().getReportingUnits()); // Add extra axis capabilities if the status report contains ABC axes detectAxisCapabilityFromControllerStatus(Axis.A, CapabilitiesConstants.A_AXIS); detectAxisCapabilityFromControllerStatus(Axis.B, CapabilitiesConstants.B_AXIS); detectAxisCapabilityFromControllerStatus(Axis.C, CapabilitiesConstants.C_AXIS); // GRBL 1.1 jog complete transition if (beforeState == ControllerState.JOG && controllerStatus.getState() == ControllerState.IDLE) { this.comm.cancelSend(); } // Set and restore the step mode when transitioning from CHECK mode to IDLE. if (before == COMM_CHECK && getCommunicatorState() != COMM_CHECK) { setSingleStepMode(temporaryCheckSingleStepMode); } else if (before != COMM_CHECK && getCommunicatorState() == COMM_CHECK) { temporaryCheckSingleStepMode = getSingleStepMode(); setSingleStepMode(true); } // Prior to GRBL v1.1 the GUI is required to keep checking locations // to verify that the machine has come to a complete stop after // pausing. if (isCanceling) { if (attemptsRemaining > 0 && lastLocation != null) { attemptsRemaining--; // If the machine goes into idle, we no longer need to cancel. if (controllerStatus.getState() == ControllerState.IDLE || controllerStatus.getState() == ControllerState.CHECK) { isCanceling = false; } // Otherwise check if the machine is Hold/Queue and stopped. else if ((controllerStatus.getState() == ControllerState.HOLD || controllerStatus.getState() == ControllerState.DOOR) && lastLocation.equals(this.controllerStatus.getMachineCoord())) { try { this.issueSoftReset(); } catch (Exception e) { this.dispatchConsoleMessage(MessageType.ERROR, e.getMessage() + "\n"); } isCanceling = false; } if (isCanceling && attemptsRemaining == 0) { this.dispatchConsoleMessage(MessageType.ERROR, Localization.getString("grbl.exception.cancelReset") + "\n"); } } lastLocation = new Position(this.controllerStatus.getMachineCoord()); } dispatchStatusString(controllerStatus); } /** * Checks the controller status machine and work coordinate if they contain coordinates for the given axis. * If found the capability for that axis will be added. * * @param axis the axis to check * @param capability the capability to add if found */ private void detectAxisCapabilityFromControllerStatus(Axis axis, String capability) { boolean hasAxisCoordinate = (controllerStatus.getMachineCoord() != null && !Double.isNaN(controllerStatus.getMachineCoord().get(axis))) || (controllerStatus.getWorkCoord() != null && !Double.isNaN(controllerStatus.getWorkCoord().get(axis))); if (!capabilities.hasAxis(axis) && hasAxisCoordinate) { capabilities.addCapability(capability); } } @Override protected void setControllerState(ControllerState controllerState) { controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(controllerState) .build(); dispatchStatusString(controllerStatus); } @Override public boolean getStatusUpdatesEnabled() { return positionPollTimer.isEnabled(); } @Override public void setStatusUpdatesEnabled(boolean enabled) { positionPollTimer.setEnabled(enabled); } @Override public int getStatusUpdateRate() { return positionPollTimer.getUpdateInterval(); } @Override public void setStatusUpdateRate(int rate) { positionPollTimer.setUpdateInterval(rate); } }
winder/Universal-G-Code-Sender
ugs-core/src/com/willwinder/universalgcodesender/GrblController.java
7,217
/************ * Helpers. ************/
block_comment
nl
/* Copyright 2013-2024 Will Winder This file is part of Universal Gcode Sender (UGS). UGS 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. UGS 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 UGS. If not, see <http://www.gnu.org/licenses/>. */ package com.willwinder.universalgcodesender; import com.willwinder.universalgcodesender.communicator.GrblCommunicator; import com.willwinder.universalgcodesender.communicator.ICommunicator; import com.willwinder.universalgcodesender.connection.ConnectionDriver; import com.willwinder.universalgcodesender.firmware.IFirmwareSettings; import com.willwinder.universalgcodesender.firmware.grbl.GrblCommandCreator; import com.willwinder.universalgcodesender.firmware.grbl.GrblFirmwareSettings; import com.willwinder.universalgcodesender.gcode.util.GcodeUtils; import com.willwinder.universalgcodesender.i18n.Localization; import com.willwinder.universalgcodesender.listeners.ControllerState; import com.willwinder.universalgcodesender.listeners.ControllerStatus; import com.willwinder.universalgcodesender.listeners.ControllerStatusBuilder; import com.willwinder.universalgcodesender.listeners.MessageType; import com.willwinder.universalgcodesender.model.Alarm; import com.willwinder.universalgcodesender.model.Axis; import com.willwinder.universalgcodesender.model.CommunicatorState; import static com.willwinder.universalgcodesender.model.CommunicatorState.COMM_CHECK; import static com.willwinder.universalgcodesender.model.CommunicatorState.COMM_IDLE; import com.willwinder.universalgcodesender.model.PartialPosition; import com.willwinder.universalgcodesender.model.Position; import com.willwinder.universalgcodesender.model.UnitUtils.Units; import com.willwinder.universalgcodesender.services.MessageService; import com.willwinder.universalgcodesender.types.GcodeCommand; import com.willwinder.universalgcodesender.types.GrblFeedbackMessage; import com.willwinder.universalgcodesender.types.GrblSettingMessage; import com.willwinder.universalgcodesender.utils.ControllerUtils; import com.willwinder.universalgcodesender.utils.GrblLookups; import com.willwinder.universalgcodesender.firmware.grbl.GrblOverrideManager; import com.willwinder.universalgcodesender.firmware.IOverrideManager; import com.willwinder.universalgcodesender.utils.ThreadHelper; import org.apache.commons.lang3.StringUtils; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; /** * GRBL Control layer, coordinates all aspects of control. * * @author wwinder */ public class GrblController extends AbstractController { private static final Logger logger = Logger.getLogger(GrblController.class.getName()); private static final GrblLookups ALARMS = new GrblLookups("alarm_codes"); private static final GrblLookups ERRORS = new GrblLookups("error_codes"); private final StatusPollTimer positionPollTimer; private final GrblFirmwareSettings firmwareSettings; private final IOverrideManager overrideManager; private GrblControllerInitializer initializer; private Capabilities capabilities = new Capabilities(); // Polling state private ControllerStatus controllerStatus = ControllerStatusBuilder.newInstance() .setState(ControllerState.DISCONNECTED) .setWorkCoord(Position.ZERO) .setMachineCoord(Position.ZERO) .build(); // Canceling state private Boolean isCanceling = false; // Set for the position polling thread. private int attemptsRemaining; private Position lastLocation; /** * For storing a temporary state if using single step mode when entering the state * check mode. When leaving check mode the temporary single step mode will be reverted. */ private boolean temporaryCheckSingleStepMode = false; public GrblController(ICommunicator communicator, GrblControllerInitializer controllerInitializer) { this(communicator); this.initializer = controllerInitializer; } public GrblController(ICommunicator communicator) { super(communicator, new GrblCommandCreator()); this.positionPollTimer = new StatusPollTimer(this); this.firmwareSettings = new GrblFirmwareSettings(this); this.comm.addListener(firmwareSettings); this.initializer = new GrblControllerInitializer(this); this.overrideManager = new GrblOverrideManager(this, communicator, messageService); } public GrblController() { this(new GrblCommunicator()); } @Override public Capabilities getCapabilities() { return capabilities; } @Override public IFirmwareSettings getFirmwareSettings() { return firmwareSettings; } @Override public void setMessageService(MessageService messageService) { super.setMessageService(messageService); overrideManager.setMessageService(messageService); } /*********************** * API Implementation. * ***********************/ private static String lookupCode(String input) { if (input.contains(":")) { String[] inputParts = input.split(":"); if (inputParts.length == 2) { String code = inputParts[1].trim(); if (StringUtils.isNumeric(code)) { String[] lookupParts = null; switch (inputParts[0].toLowerCase()) { case "error": lookupParts = ERRORS.lookup(code); break; case "alarm": lookupParts = ALARMS.lookup(code); break; default: return input; } if (lookupParts == null) { return "(" + input + ") An unknown error has occurred"; } else { return "(" + input + ") " + lookupParts[2]; } } } } return input; } @Override public Boolean openCommPort(ConnectionDriver connectionDriver, String port, int portRate) throws Exception { if (isCommOpen()) { throw new Exception("Comm port is already open."); } initializer.reset(); positionPollTimer.stop(); comm.connect(connectionDriver, port, portRate); setControllerState(ControllerState.CONNECTING); messageService.dispatchMessage(MessageType.INFO, "*** Connecting to " + connectionDriver.getProtocol() + port + ":" + portRate + "\n"); initialize(); return isCommOpen(); } private void initialize() { if (comm.areActiveCommands()) { comm.cancelSend(); } setControllerState(ControllerState.CONNECTING); ThreadHelper.invokeLater(() -> { positionPollTimer.stop(); initializer.initialize(); capabilities = GrblUtils.getGrblStatusCapabilities(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); // Toggle the state to force UI update setControllerState(ControllerState.CONNECTING); positionPollTimer.start(); }); } @Override protected void rawResponseHandler(String response) { String processed = response; try { boolean verbose = false; if (GrblUtils.isOkResponse(response)) { this.commandComplete(processed); } // Error case. else if (GrblUtils.isOkErrorAlarmResponse(response)) { if (GrblUtils.isAlarmResponse(response)) { //this is not updating the state to Alarm in the GUI, and the alarm is no longer being processed controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(ControllerState.ALARM) .build(); Alarm alarm = GrblUtils.parseAlarmResponse(response); dispatchAlarm(alarm); dispatchStatusString(controllerStatus); } // If there is an active command, mark it as completed with error Optional<GcodeCommand> activeCommand = this.getActiveCommand(); if (activeCommand.isPresent()) { String commandString = activeCommand.get().getCommandString(); processed = String.format(Localization.getString("controller.exception.sendError"), commandString, lookupCode(response)).replaceAll("\\.\\.", "\\."); if (!commandString.startsWith("$J=")) { // log error to console (unless it's in response to a jog command) this.dispatchConsoleMessage(MessageType.ERROR, processed + "\n"); } this.commandComplete(processed); } else { processed = String.format(Localization.getString("controller.exception.unexpectedError"), lookupCode(response)).replaceAll("\\.\\.", "\\."); dispatchConsoleMessage(MessageType.INFO, processed + "\n"); } checkStreamFinished(); processed = ""; } else if (GrblUtils.isGrblVersionString(response)) { messageService.dispatchMessage(MessageType.VERBOSE, response + "\n"); initialize(); } else if (GrblUtils.isGrblProbeMessage(response)) { Position p = GrblUtils.parseProbePosition(response, getFirmwareSettings().getReportingUnits()); if (p != null) { dispatchProbeCoordinates(p); } } else if (initializer.isInitialized() && GrblUtils.isGrblStatusString(response)) { // Only 1 poll is sent at a time so don't decrement, reset to zero. positionPollTimer.receivedStatus(); // Status string goes to verbose console verbose = true; this.handleStatusString(response); this.checkStreamFinished(); } // We can only parse feedback messages when we know what capabilities the controller have else if (initializer.isInitialized() && GrblUtils.isGrblFeedbackMessage(response, capabilities)) { GrblFeedbackMessage grblFeedbackMessage = new GrblFeedbackMessage(response); // Convert feedback message to raw commands to update modal state. updateParserModalState(getCommandCreator().createCommand(GrblUtils.parseFeedbackMessage(response, capabilities))); dispatchConsoleMessage(MessageType.VERBOSE, grblFeedbackMessage + "\n"); setDistanceModeCode(grblFeedbackMessage.getDistanceMode()); setUnitsCode(grblFeedbackMessage.getUnits()); } else if (GrblUtils.isGrblSettingMessage(response)) { GrblSettingMessage message = new GrblSettingMessage(response); processed = message.toString(); } if (StringUtils.isNotBlank(processed)) { if (verbose) { this.dispatchConsoleMessage(MessageType.VERBOSE, processed + "\n"); } else { this.dispatchConsoleMessage(MessageType.INFO, processed + "\n"); } } } catch (Exception e) { String message = ""; if (e.getMessage() != null) { message = ": " + e.getMessage(); } message = Localization.getString("controller.error.response") + " <" + processed + ">" + message; logger.log(Level.SEVERE, message, e); this.dispatchConsoleMessage(MessageType.ERROR, message + "\n"); } } @Override protected void pauseStreamingEvent() throws Exception { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { this.comm.sendByteImmediately(GrblUtils.GRBL_PAUSE_COMMAND); } } @Override protected void resumeStreamingEvent() throws Exception { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { this.comm.sendByteImmediately(GrblUtils.GRBL_RESUME_COMMAND); } } @Override protected void closeCommBeforeEvent() { positionPollTimer.stop(); } @Override protected void closeCommAfterEvent() { initializer.reset(); } @Override protected void isReadyToStreamCommandsEvent() throws Exception { isReadyToSendCommandsEvent(); if (this.controllerStatus != null && this.controllerStatus.getState() == ControllerState.ALARM) { throw new Exception(Localization.getString("grbl.exception.Alarm")); } } @Override protected void isReadyToSendCommandsEvent() throws Exception { if (!isCommOpen()) { throw new Exception(Localization.getString("controller.exception.booting")); } } @Override protected void cancelSendBeforeEvent() throws Exception { boolean paused = isPaused(); // The cancel button is left enabled at all times now, but can only be // used for some versions of GRBL. if (paused && !this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { throw new Exception("Cannot cancel while paused with this version of GRBL. Reconnect to reset GRBL."); } // If we're canceling a "jog" state if (capabilities.hasJogging() && controllerStatus != null && controllerStatus.getState() == ControllerState.JOG) { dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_JOG_CANCEL_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_JOG_CANCEL_COMMAND); } // Otherwise, check if we can get fancy with a soft reset. else if (!paused && this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { try { this.pauseStreaming(); } catch (Exception e) { // Oh well, was worth a shot. System.out.println("Exception while trying to issue a soft reset: " + e.getMessage()); } } } @Override protected void cancelSendAfterEvent() { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME) && this.getStatusUpdatesEnabled()) { // Trigger the position listener to watch for the machine to stop. this.attemptsRemaining = 50; this.isCanceling = true; this.lastLocation = null; } } @Override public void cancelJog() throws Exception { if (capabilities.hasCapability(GrblCapabilitiesConstants.HARDWARE_JOGGING)) { dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_JOG_CANCEL_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_JOG_CANCEL_COMMAND); } else { cancelSend(); } } @Override protected Boolean isIdleEvent() { if (this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { return getCommunicatorState() == COMM_IDLE || getCommunicatorState() == COMM_CHECK; } // Otherwise let the abstract controller decide. return true; } @Override public CommunicatorState getCommunicatorState() { if (!this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { return super.getCommunicatorState(); } return ControllerUtils.getCommunicatorState(controllerStatus.getState(), this, comm); } /** * Sends the version specific homing cycle to the machine. */ @Override public void performHomingCycle() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getHomingCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); sendCommandImmediately(command); controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(ControllerState.HOME) .build(); dispatchStatusString(controllerStatus); return; } } // Throw exception super.performHomingCycle(); } @Override public void resetCoordinatesToZero() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getResetCoordsToZeroCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.resetCoordinatesToZero(); } @Override public void resetCoordinateToZero(final Axis axis) throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getResetCoordToZeroCommand(axis, getCurrentGcodeState().getUnits(), initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.resetCoordinatesToZero(); } @Override public void setWorkPosition(PartialPosition axisPosition) throws Exception { if (!this.isCommOpen()) { throw new Exception("Must be connected to set work position"); } Units currentUnits = getCurrentGcodeState().getUnits(); PartialPosition position = axisPosition.getPositionIn(currentUnits); String gcode = GrblUtils.getSetCoordCommand(position, initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (StringUtils.isNotEmpty(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); } } @Override public void killAlarmLock() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getKillAlarmLockCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.killAlarmLock(); } @Override public void openDoor() throws Exception { if (!this.isCommOpen()) { throw new RuntimeException("Not connected to the controller"); } pauseStreaming(); // Pause the file stream and stop the time dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_DOOR_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_DOOR_COMMAND); } @Override public void toggleCheckMode() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getToggleCheckModeCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.toggleCheckMode(); } @Override public void viewParserState() throws Exception { if (this.isCommOpen()) { String gcode = GrblUtils.getViewParserStateCommand(initializer.getVersion().getVersionNumber(), initializer.getVersion().getVersionLetter()); if (!"".equals(gcode)) { GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); return; } } // Throw exception super.viewParserState(); } @Override public void requestStatusReport() throws Exception { if (!this.isCommOpen()) { throw new RuntimeException("Not connected to the controller"); } comm.sendByteImmediately(GrblUtils.GRBL_STATUS_COMMAND); } /** * If it is supported, a soft reset real-time command will be issued. */ @Override public void softReset() throws Exception { if (isCommOpen() && capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { dispatchConsoleMessage(MessageType.VERBOSE, String.format(">>> 0x%02x\n", GrblUtils.GRBL_RESET_COMMAND)); comm.sendByteImmediately(GrblUtils.GRBL_RESET_COMMAND); //Does GRBL need more time to handle the reset? comm.cancelSend(); } } @Override public void jogMachine(PartialPosition distance, double feedRate) throws Exception { if (capabilities.hasCapability(GrblCapabilitiesConstants.HARDWARE_JOGGING)) { String commandString = GcodeUtils.generateMoveCommand("G91", feedRate, distance); GcodeCommand command = createCommand("$J=" + commandString); sendCommandImmediately(command); } else { super.jogMachine(distance, feedRate); } } @Override public void jogMachineTo(PartialPosition position, double feedRate) throws Exception { if (capabilities.hasCapability(GrblCapabilitiesConstants.HARDWARE_JOGGING)) { String commandString = GcodeUtils.generateMoveToCommand("G90", position, feedRate); GcodeCommand command = createCommand("$J=" + commandString); sendCommandImmediately(command); } else { super.jogMachineTo(position, feedRate); } } /************ * Helpers. <SUF>*/ public String getGrblVersion() { if (this.isCommOpen()) { return initializer.getVersion().toString(); } return "<" + Localization.getString("controller.log.notconnected") + ">"; } @Override public String getFirmwareVersion() { return getGrblVersion(); } @Override public ControllerStatus getControllerStatus() { return controllerStatus; } @Override public IOverrideManager getOverrideManager() { return overrideManager; } // No longer a listener event private void handleStatusString(final String string) { if (this.capabilities == null) { return; } CommunicatorState before = getCommunicatorState(); ControllerState beforeState = controllerStatus == null ? ControllerState.DISCONNECTED : controllerStatus.getState(); controllerStatus = GrblUtils.getStatusFromStatusString( controllerStatus, string, capabilities, getFirmwareSettings().getReportingUnits()); // Add extra axis capabilities if the status report contains ABC axes detectAxisCapabilityFromControllerStatus(Axis.A, CapabilitiesConstants.A_AXIS); detectAxisCapabilityFromControllerStatus(Axis.B, CapabilitiesConstants.B_AXIS); detectAxisCapabilityFromControllerStatus(Axis.C, CapabilitiesConstants.C_AXIS); // GRBL 1.1 jog complete transition if (beforeState == ControllerState.JOG && controllerStatus.getState() == ControllerState.IDLE) { this.comm.cancelSend(); } // Set and restore the step mode when transitioning from CHECK mode to IDLE. if (before == COMM_CHECK && getCommunicatorState() != COMM_CHECK) { setSingleStepMode(temporaryCheckSingleStepMode); } else if (before != COMM_CHECK && getCommunicatorState() == COMM_CHECK) { temporaryCheckSingleStepMode = getSingleStepMode(); setSingleStepMode(true); } // Prior to GRBL v1.1 the GUI is required to keep checking locations // to verify that the machine has come to a complete stop after // pausing. if (isCanceling) { if (attemptsRemaining > 0 && lastLocation != null) { attemptsRemaining--; // If the machine goes into idle, we no longer need to cancel. if (controllerStatus.getState() == ControllerState.IDLE || controllerStatus.getState() == ControllerState.CHECK) { isCanceling = false; } // Otherwise check if the machine is Hold/Queue and stopped. else if ((controllerStatus.getState() == ControllerState.HOLD || controllerStatus.getState() == ControllerState.DOOR) && lastLocation.equals(this.controllerStatus.getMachineCoord())) { try { this.issueSoftReset(); } catch (Exception e) { this.dispatchConsoleMessage(MessageType.ERROR, e.getMessage() + "\n"); } isCanceling = false; } if (isCanceling && attemptsRemaining == 0) { this.dispatchConsoleMessage(MessageType.ERROR, Localization.getString("grbl.exception.cancelReset") + "\n"); } } lastLocation = new Position(this.controllerStatus.getMachineCoord()); } dispatchStatusString(controllerStatus); } /** * Checks the controller status machine and work coordinate if they contain coordinates for the given axis. * If found the capability for that axis will be added. * * @param axis the axis to check * @param capability the capability to add if found */ private void detectAxisCapabilityFromControllerStatus(Axis axis, String capability) { boolean hasAxisCoordinate = (controllerStatus.getMachineCoord() != null && !Double.isNaN(controllerStatus.getMachineCoord().get(axis))) || (controllerStatus.getWorkCoord() != null && !Double.isNaN(controllerStatus.getWorkCoord().get(axis))); if (!capabilities.hasAxis(axis) && hasAxisCoordinate) { capabilities.addCapability(capability); } } @Override protected void setControllerState(ControllerState controllerState) { controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(controllerState) .build(); dispatchStatusString(controllerStatus); } @Override public boolean getStatusUpdatesEnabled() { return positionPollTimer.isEnabled(); } @Override public void setStatusUpdatesEnabled(boolean enabled) { positionPollTimer.setEnabled(enabled); } @Override public int getStatusUpdateRate() { return positionPollTimer.getUpdateInterval(); } @Override public void setStatusUpdateRate(int rate) { positionPollTimer.setUpdateInterval(rate); } }
26130_11
package com.tinkerpop.blueprints.versioned.impl.gc; import com.tinkerpop.blueprints.versioned.GarbageCollector; import com.tinkerpop.blueprints.versioned.exceptions.VersionNoLongerAvailableException; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicLong; /** * */ public class LowerboundGC implements GarbageCollector { /** * The ticks locked by a view */ final protected ConcurrentSkipListMap<Long, AtomicLong> locks = new ConcurrentSkipListMap<Long, AtomicLong>(); private long update(long tick, boolean increment) { // get the refcounter AtomicLong rc = locks.get(tick); // there is non, so we add one if(rc == null) { // initialize new reference counter final AtomicLong refCounter = new AtomicLong(); // if someone put one in the meantime, rc != null rc = locks.putIfAbsent(tick, refCounter); if(rc == null) rc = refCounter; } // now that we have a reference counter, update it if (increment) return rc.incrementAndGet(); // TODO safely remove rc from locks return rc.decrementAndGet(); } @Override public void lock(long tick) throws VersionNoLongerAvailableException { // TODO check boundaries update(tick, true); } /** * * * @param tick * @return true of the {@link LowerboundGC#gcUpperbound()} value has changed */ @Override public boolean release(long tick) { final long rc = update(tick, false); if (rc == 0) { // TODO concurrently set the GC upperbound.. grr ? } return true; } // values up to this tick can be GC'd public long gcUpperbound() { // TODO ja, ok, maar nu ook er voor zorgen dat locking tijdens GC goed gaat // dwz. Zodra GC begint, markeer try { return locks.firstKey(); } catch (NoSuchElementException e) { return Long.MAX_VALUE; } } // times as lock as this tick can be locked public long lockLowerbound() { return 0; } }
wires/blueprints-versionedgraph
src/main/java/com/tinkerpop/blueprints/versioned/impl/gc/LowerboundGC.java
645
// TODO ja, ok, maar nu ook er voor zorgen dat locking tijdens GC goed gaat
line_comment
nl
package com.tinkerpop.blueprints.versioned.impl.gc; import com.tinkerpop.blueprints.versioned.GarbageCollector; import com.tinkerpop.blueprints.versioned.exceptions.VersionNoLongerAvailableException; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicLong; /** * */ public class LowerboundGC implements GarbageCollector { /** * The ticks locked by a view */ final protected ConcurrentSkipListMap<Long, AtomicLong> locks = new ConcurrentSkipListMap<Long, AtomicLong>(); private long update(long tick, boolean increment) { // get the refcounter AtomicLong rc = locks.get(tick); // there is non, so we add one if(rc == null) { // initialize new reference counter final AtomicLong refCounter = new AtomicLong(); // if someone put one in the meantime, rc != null rc = locks.putIfAbsent(tick, refCounter); if(rc == null) rc = refCounter; } // now that we have a reference counter, update it if (increment) return rc.incrementAndGet(); // TODO safely remove rc from locks return rc.decrementAndGet(); } @Override public void lock(long tick) throws VersionNoLongerAvailableException { // TODO check boundaries update(tick, true); } /** * * * @param tick * @return true of the {@link LowerboundGC#gcUpperbound()} value has changed */ @Override public boolean release(long tick) { final long rc = update(tick, false); if (rc == 0) { // TODO concurrently set the GC upperbound.. grr ? } return true; } // values up to this tick can be GC'd public long gcUpperbound() { // TODO ja,<SUF> // dwz. Zodra GC begint, markeer try { return locks.firstKey(); } catch (NoSuchElementException e) { return Long.MAX_VALUE; } } // times as lock as this tick can be locked public long lockLowerbound() { return 0; } }
73843_15
/* * 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.joor; import android.os.Build; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** * A wrapper for an {@link Object} or {@link Class} upon which reflective calls * can be made. * <p> * An example of using <code>Reflect</code> is <code><pre> * // Static import all reflection methods to decrease verbosity * import static org.joor.Reflect.*; * * // Wrap an Object / Class / class name with the on() method: * on("java.lang.String") * // Invoke constructors using the create() method: * .create("Hello World") * // Invoke methods using the call() method: * .call("toString") * // Retrieve the wrapped object * * @author Lukas Eder * @author Irek Matysiewicz * @author Thomas Darimont */ public class Reflect { // --------------------------------------------------------------------- // Static API used as entrance points to the fluent API // --------------------------------------------------------------------- /** * Wrap a class name. * <p> * This is the same as calling <code>on(Class.forName(name))</code> * * @param name A fully qualified class name * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name) throws ReflectException { return on(forName(name)); } /** * Wrap a class name, loading it via a given class loader. * <p> * This is the same as calling * <code>on(Class.forName(name, classLoader))</code> * * @param name A fully qualified class name. * @param classLoader The class loader in whose context the class should be * loaded. * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name, ClassLoader classLoader) throws ReflectException { return on(forName(name, classLoader)); } /** * Wrap a class. * <p> * Use this when you want to access static fields and methods on a * {@link Class} object, or as a basis for constructing objects of that * class using {@link #create(Object...)} * * @param clazz The class to be wrapped * @return A wrapped class object, to be used for further reflection. */ public static Reflect on(Class<?> clazz) { return new Reflect(clazz); } /** * Wrap an object. * <p> * Use this when you want to access instance fields and methods on any * {@link Object} * * @param object The object to be wrapped * @return A wrapped object, to be used for further reflection. */ public static Reflect on(Object object) { return new Reflect(object == null ? Object.class : object.getClass(), object); } private static Reflect on(Class<?> type, Object object) { return new Reflect(type, object); } /** * Conveniently render an {@link AccessibleObject} accessible. * <p> * To prevent {@link SecurityException}, this is only done if the argument * object and its declaring class are non-public. * * @param accessible The object to render accessible * @return The argument object rendered accessible */ public static <T extends AccessibleObject> T accessible(T accessible) { if (accessible == null) { return null; } if (accessible instanceof Member) { Member member = (Member) accessible; if (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return accessible; } } // [jOOQ #3392] The accessible flag is set to false by default, also for public members. if (!accessible.isAccessible()) { accessible.setAccessible(true); } return accessible; } // --------------------------------------------------------------------- // Members // --------------------------------------------------------------------- /** * The type of the wrapped object. */ private final Class<?> type; /** * The wrapped object. */ private final Object object; // --------------------------------------------------------------------- // Constructors // --------------------------------------------------------------------- private Reflect(Class<?> type) { this(type, type); } private Reflect(Class<?> type, Object object) { this.type = type; this.object = object; } // --------------------------------------------------------------------- // Fluent Reflection API // --------------------------------------------------------------------- /** * Get the wrapped object * * @param <T> A convenience generic parameter for automatic unsafe casting */ @SuppressWarnings("unchecked") public <T> T get() { return (T) object; } /** * Set a field value. * <p> * This is roughly equivalent to {@link Field#set(Object, Object)}. If the * wrapped object is a {@link Class}, then this will set a value to a static * member field. If the wrapped object is any other {@link Object}, then * this will set a value to an instance member field. * <p> * This method is also capable of setting the value of (static) final * fields. This may be convenient in situations where no * {@link SecurityManager} is expected to prevent this, but do note that * (especially static) final fields may already have been inlined by the * javac and/or JIT and relevant code deleted from the runtime verison of * your program, so setting these fields might not have any effect on your * execution. * <p> * For restrictions of usage regarding setting values on final fields check: * <a href= * "http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection">http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection</a> * ... and <a href= * "http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html">http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html</a> * * @param name The field name * @param value The new field value * @return The same wrapped object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect set(String name, Object value) throws ReflectException { try { Field field = field0(name); if ((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL) { // Note (d4vidi): this is an important change, compared to the original implementation!!! // See here: https://stackoverflow.com/a/64378131/453052 // Field modifiersField = Field.class.getDeclaredField("modifiers"); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Field modifiersField = Field.class.getDeclaredField("accessFlags"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } } field.set(object, unwrap(value)); return this; } catch (Exception e) { throw new ReflectException(e); } } /** * Get a field value. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will get a value from a static * member field. If the wrapped object is any other {@link Object}, then * this will get a value from an instance member field. * <p> * If you want to "navigate" to a wrapped version of the field, use * {@link #field(String)} instead. * * @param name The field name * @return The field value * @throws ReflectException If any reflection exception occurred. * @see #field(String) */ public <T> T get(String name) throws ReflectException { return field(name).<T>get(); } /** * Get a wrapped field. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will wrap a static member field. If * the wrapped object is any other {@link Object}, then this wrap an * instance member field. * * @param name The field name * @return The wrapped field * @throws ReflectException If any reflection exception occurred. */ public Reflect field(String name) throws ReflectException { try { Field field = field0(name); return on(field.getType(), field.get(object)); } catch (Exception e) { throw new ReflectException(e); } } private Field field0(String name) throws ReflectException { Class<?> t = type(); // Try getting a public field try { return accessible(t.getField(name)); } // Try again, getting a non-public field catch (NoSuchFieldException e) { do { try { return accessible(t.getDeclaredField(name)); } catch (NoSuchFieldException ignore) {} t = t.getSuperclass(); } while (t != null); throw new ReflectException(e); } } /** * Get a Map containing field names and wrapped values for the fields' * values. * <p> * If the wrapped object is a {@link Class}, then this will return static * fields. If the wrapped object is any other {@link Object}, then this will * return instance fields. * <p> * These two calls are equivalent <code><pre> * on(object).field("myField"); * on(object).fields().get("myField"); * </pre></code> * * @return A map containing field names and wrapped values. */ public Map<String, Reflect> fields() { Map<String, Reflect> result = new LinkedHashMap<String, Reflect>(); Class<?> t = type(); do { for (Field field : t.getDeclaredFields()) { if (type != object ^ Modifier.isStatic(field.getModifiers())) { String name = field.getName(); if (!result.containsKey(name)) result.put(name, field(name)); } } t = t.getSuperclass(); } while (t != null); return result; } /** * Call a method by its name. * <p> * This is a convenience method for calling * <code>call(name, new Object[0])</code> * * @param name The method name * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. * @see #call(String, Object...) */ public Reflect call(String name) throws ReflectException { return call(name, new Object[0]); } /** * Call a method by its name. * <p> * This is roughly equivalent to {@link Method#invoke(Object, Object...)}. * If the wrapped object is a {@link Class}, then this will invoke a static * method. If the wrapped object is any other {@link Object}, then this will * invoke an instance method. * <p> * Just like {@link Method#invoke(Object, Object...)}, this will try to wrap * primitive types or unwrap primitive type wrappers if applicable. If * several methods are applicable, by that rule, the first one encountered * is called. i.e. when calling <code><pre> * on(...).call("method", 1, 1); * </pre></code> The first of the following methods will be called: * <code><pre> * public void method(int param1, Integer param2); * public void method(Integer param1, int param2); * public void method(Number param1, Number param2); * public void method(Number param1, Object param2); * public void method(int param1, Object param2); * </pre></code> * <p> * The best matching method is searched for with the following strategy: * <ol> * <li>public method with exact signature match in class hierarchy</li> * <li>non-public method with exact signature match on declaring class</li> * <li>public method with similar signature in class hierarchy</li> * <li>non-public method with similar signature on declaring class</li> * </ol> * * @param name The method name * @param args The method arguments * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect call(String name, Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" method, i.e. the one with exact // matching argument types try { Method method = exactMethod(name, types); return on(method, object, args); } // If there is no exact match, try to find a method that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { try { Method method = similarMethod(name, types); return on(method, object, args); } catch (NoSuchMethodException e1) { throw new ReflectException(e1); } } } /** * Searches a method with the exact same signature as desired. * <p> * If a public method is found in the class hierarchy, this method is returned. * Otherwise a private method with the exact same signature is returned. * If no exact match could be found, we let the {@code NoSuchMethodException} pass through. */ private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with exact signature match in class hierarchy try { return t.getMethod(name, types); } // second priority: find a private method with exact signature match on declaring class catch (NoSuchMethodException e) { do { try { return t.getDeclaredMethod(name, types); } catch (NoSuchMethodException ignore) {} t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException(); } } /** * Searches a method with a similar signature as desired using * {@link #isSimilarSignature(java.lang.reflect.Method, String, Class[])}. * <p> * First public methods are searched in the class hierarchy, then private * methods on the declaring class. If a method could be found, it is * returned, otherwise a {@code NoSuchMethodException} is thrown. */ private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with a "similar" signature in class hierarchy // similar interpreted in when primitive argument types are converted to their wrappers for (Method method : t.getMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } // second priority: find a non-public method with a "similar" signature on declaring class do { for (Method method : t.getDeclaredMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found on type " + type() + "."); } /** * Determines if a method has a "similar" signature, especially if wrapping * primitive argument types would result in an exactly matching signature. */ private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) { return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); } /** * Call a constructor. * <p> * This is a convenience method for calling * <code>create(new Object[0])</code> * * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #create(Object...) */ public Reflect create() throws ReflectException { return create(new Object[0]); } /** * Call a constructor. * <p> * This is roughly equivalent to {@link Constructor#newInstance(Object...)}. * If the wrapped object is a {@link Class}, then this will create a new * object of that class. If the wrapped object is any other {@link Object}, * then this will create a new object of the same type. * <p> * Just like {@link Constructor#newInstance(Object...)}, this will try to * wrap primitive types or unwrap primitive type wrappers if applicable. If * several constructors are applicable, by that rule, the first one * encountered is called. i.e. when calling <code><pre> * on(C.class).create(1, 1); * </pre></code> The first of the following constructors will be applied: * <code><pre> * public C(int param1, Integer param2); * public C(Integer param1, int param2); * public C(Number param1, Number param2); * public C(Number param1, Object param2); * public C(int param1, Object param2); * </pre></code> * * @param args The constructor arguments * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect create(Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" constructor, i.e. the one with exact // matching argument types try { Constructor<?> constructor = type().getDeclaredConstructor(types); return on(constructor, args); } // If there is no exact match, try to find one that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { for (Constructor<?> constructor : type().getDeclaredConstructors()) { if (match(constructor.getParameterTypes(), types)) { return on(constructor, args); } } throw new ReflectException(e); } } /** * Create a proxy for the wrapped object allowing to typesafely invoke * methods on it using a custom interface * * @param proxyType The interface type that is implemented by the proxy * @return A proxy for the wrapped object */ @SuppressWarnings("unchecked") public <P> P as(final Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @SuppressWarnings("null") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); // Actual method name matches always come first try { return on(type, object).call(name, args).get(); } // [#14] Emulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler); } /** * Get the POJO property name of an getter/setter */ private static String property(String string) { int length = string.length(); if (length == 0) { return ""; } else if (length == 1) { return string.toLowerCase(Locale.ROOT); } else { return string.substring(0, 1).toLowerCase(Locale.ROOT) + string.substring(1); } } // --------------------------------------------------------------------- // Object API // --------------------------------------------------------------------- /** * Check whether two arrays of types match, converting primitive types to * their corresponding wrappers. */ private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) { if (declaredTypes.length == actualTypes.length) { for (int i = 0; i < actualTypes.length; i++) { if (actualTypes[i] == NULL.class) continue; if (wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) continue; return false; } return true; } else { return false; } } /** * {@inheritDoc} */ @Override public int hashCode() { return object.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof Reflect) { return object.equals(((Reflect) obj).get()); } return false; } /** * {@inheritDoc} */ @Override public String toString() { return object.toString(); } // --------------------------------------------------------------------- // Utility methods // --------------------------------------------------------------------- /** * Wrap an object created from a constructor */ private static Reflect on(Constructor<?> constructor, Object... args) throws ReflectException { try { return on(constructor.getDeclaringClass(), accessible(constructor).newInstance(args)); } catch (Exception e) { throw new ReflectException(e); } } /** * Wrap an object returned from a method */ private static Reflect on(Method method, Object object, Object... args) throws ReflectException { try { accessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { return on(method.invoke(object, args)); } } catch (Exception e) { throw new ReflectException(e); } } /** * Unwrap an object */ private static Object unwrap(Object object) { if (object instanceof Reflect) { return ((Reflect) object).get(); } return object; } /** * Get an array of types for an array of objects * * @see Object#getClass() */ private static Class<?>[] types(Object... values) { if (values == null) { return new Class[0]; } Class<?>[] result = new Class[values.length]; for (int i = 0; i < values.length; i++) { Object value = values[i]; result[i] = value == null ? NULL.class : value.getClass(); } return result; } /** * Load a class * * @see Class#forName(String) */ private static Class<?> forName(String name) throws ReflectException { try { return Class.forName(name); } catch (Exception e) { throw new ReflectException(e); } } private static Class<?> forName(String name, ClassLoader classLoader) throws ReflectException { try { return Class.forName(name, true, classLoader); } catch (Exception e) { throw new ReflectException(e); } } /** * Get the type of the wrapped object. * * @see Object#getClass() */ public Class<?> type() { return type; } /** * Get a wrapper type for a primitive type, or the argument type itself, if * it is not a primitive type. */ public static Class<?> wrapper(Class<?> type) { if (type == null) { return null; } else if (type.isPrimitive()) { if (boolean.class == type) { return Boolean.class; } else if (int.class == type) { return Integer.class; } else if (long.class == type) { return Long.class; } else if (short.class == type) { return Short.class; } else if (byte.class == type) { return Byte.class; } else if (double.class == type) { return Double.class; } else if (float.class == type) { return Float.class; } else if (char.class == type) { return Character.class; } else if (void.class == type) { return Void.class; } } return type; } private static class NULL {} }
wix/Detox
detox/android/detox/src/main/java/org/joor/Reflect.java
7,166
// See here: https://stackoverflow.com/a/64378131/453052
line_comment
nl
/* * 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.joor; import android.os.Build; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** * A wrapper for an {@link Object} or {@link Class} upon which reflective calls * can be made. * <p> * An example of using <code>Reflect</code> is <code><pre> * // Static import all reflection methods to decrease verbosity * import static org.joor.Reflect.*; * * // Wrap an Object / Class / class name with the on() method: * on("java.lang.String") * // Invoke constructors using the create() method: * .create("Hello World") * // Invoke methods using the call() method: * .call("toString") * // Retrieve the wrapped object * * @author Lukas Eder * @author Irek Matysiewicz * @author Thomas Darimont */ public class Reflect { // --------------------------------------------------------------------- // Static API used as entrance points to the fluent API // --------------------------------------------------------------------- /** * Wrap a class name. * <p> * This is the same as calling <code>on(Class.forName(name))</code> * * @param name A fully qualified class name * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name) throws ReflectException { return on(forName(name)); } /** * Wrap a class name, loading it via a given class loader. * <p> * This is the same as calling * <code>on(Class.forName(name, classLoader))</code> * * @param name A fully qualified class name. * @param classLoader The class loader in whose context the class should be * loaded. * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name, ClassLoader classLoader) throws ReflectException { return on(forName(name, classLoader)); } /** * Wrap a class. * <p> * Use this when you want to access static fields and methods on a * {@link Class} object, or as a basis for constructing objects of that * class using {@link #create(Object...)} * * @param clazz The class to be wrapped * @return A wrapped class object, to be used for further reflection. */ public static Reflect on(Class<?> clazz) { return new Reflect(clazz); } /** * Wrap an object. * <p> * Use this when you want to access instance fields and methods on any * {@link Object} * * @param object The object to be wrapped * @return A wrapped object, to be used for further reflection. */ public static Reflect on(Object object) { return new Reflect(object == null ? Object.class : object.getClass(), object); } private static Reflect on(Class<?> type, Object object) { return new Reflect(type, object); } /** * Conveniently render an {@link AccessibleObject} accessible. * <p> * To prevent {@link SecurityException}, this is only done if the argument * object and its declaring class are non-public. * * @param accessible The object to render accessible * @return The argument object rendered accessible */ public static <T extends AccessibleObject> T accessible(T accessible) { if (accessible == null) { return null; } if (accessible instanceof Member) { Member member = (Member) accessible; if (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return accessible; } } // [jOOQ #3392] The accessible flag is set to false by default, also for public members. if (!accessible.isAccessible()) { accessible.setAccessible(true); } return accessible; } // --------------------------------------------------------------------- // Members // --------------------------------------------------------------------- /** * The type of the wrapped object. */ private final Class<?> type; /** * The wrapped object. */ private final Object object; // --------------------------------------------------------------------- // Constructors // --------------------------------------------------------------------- private Reflect(Class<?> type) { this(type, type); } private Reflect(Class<?> type, Object object) { this.type = type; this.object = object; } // --------------------------------------------------------------------- // Fluent Reflection API // --------------------------------------------------------------------- /** * Get the wrapped object * * @param <T> A convenience generic parameter for automatic unsafe casting */ @SuppressWarnings("unchecked") public <T> T get() { return (T) object; } /** * Set a field value. * <p> * This is roughly equivalent to {@link Field#set(Object, Object)}. If the * wrapped object is a {@link Class}, then this will set a value to a static * member field. If the wrapped object is any other {@link Object}, then * this will set a value to an instance member field. * <p> * This method is also capable of setting the value of (static) final * fields. This may be convenient in situations where no * {@link SecurityManager} is expected to prevent this, but do note that * (especially static) final fields may already have been inlined by the * javac and/or JIT and relevant code deleted from the runtime verison of * your program, so setting these fields might not have any effect on your * execution. * <p> * For restrictions of usage regarding setting values on final fields check: * <a href= * "http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection">http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection</a> * ... and <a href= * "http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html">http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html</a> * * @param name The field name * @param value The new field value * @return The same wrapped object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect set(String name, Object value) throws ReflectException { try { Field field = field0(name); if ((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL) { // Note (d4vidi): this is an important change, compared to the original implementation!!! // See here:<SUF> // Field modifiersField = Field.class.getDeclaredField("modifiers"); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Field modifiersField = Field.class.getDeclaredField("accessFlags"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } } field.set(object, unwrap(value)); return this; } catch (Exception e) { throw new ReflectException(e); } } /** * Get a field value. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will get a value from a static * member field. If the wrapped object is any other {@link Object}, then * this will get a value from an instance member field. * <p> * If you want to "navigate" to a wrapped version of the field, use * {@link #field(String)} instead. * * @param name The field name * @return The field value * @throws ReflectException If any reflection exception occurred. * @see #field(String) */ public <T> T get(String name) throws ReflectException { return field(name).<T>get(); } /** * Get a wrapped field. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will wrap a static member field. If * the wrapped object is any other {@link Object}, then this wrap an * instance member field. * * @param name The field name * @return The wrapped field * @throws ReflectException If any reflection exception occurred. */ public Reflect field(String name) throws ReflectException { try { Field field = field0(name); return on(field.getType(), field.get(object)); } catch (Exception e) { throw new ReflectException(e); } } private Field field0(String name) throws ReflectException { Class<?> t = type(); // Try getting a public field try { return accessible(t.getField(name)); } // Try again, getting a non-public field catch (NoSuchFieldException e) { do { try { return accessible(t.getDeclaredField(name)); } catch (NoSuchFieldException ignore) {} t = t.getSuperclass(); } while (t != null); throw new ReflectException(e); } } /** * Get a Map containing field names and wrapped values for the fields' * values. * <p> * If the wrapped object is a {@link Class}, then this will return static * fields. If the wrapped object is any other {@link Object}, then this will * return instance fields. * <p> * These two calls are equivalent <code><pre> * on(object).field("myField"); * on(object).fields().get("myField"); * </pre></code> * * @return A map containing field names and wrapped values. */ public Map<String, Reflect> fields() { Map<String, Reflect> result = new LinkedHashMap<String, Reflect>(); Class<?> t = type(); do { for (Field field : t.getDeclaredFields()) { if (type != object ^ Modifier.isStatic(field.getModifiers())) { String name = field.getName(); if (!result.containsKey(name)) result.put(name, field(name)); } } t = t.getSuperclass(); } while (t != null); return result; } /** * Call a method by its name. * <p> * This is a convenience method for calling * <code>call(name, new Object[0])</code> * * @param name The method name * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. * @see #call(String, Object...) */ public Reflect call(String name) throws ReflectException { return call(name, new Object[0]); } /** * Call a method by its name. * <p> * This is roughly equivalent to {@link Method#invoke(Object, Object...)}. * If the wrapped object is a {@link Class}, then this will invoke a static * method. If the wrapped object is any other {@link Object}, then this will * invoke an instance method. * <p> * Just like {@link Method#invoke(Object, Object...)}, this will try to wrap * primitive types or unwrap primitive type wrappers if applicable. If * several methods are applicable, by that rule, the first one encountered * is called. i.e. when calling <code><pre> * on(...).call("method", 1, 1); * </pre></code> The first of the following methods will be called: * <code><pre> * public void method(int param1, Integer param2); * public void method(Integer param1, int param2); * public void method(Number param1, Number param2); * public void method(Number param1, Object param2); * public void method(int param1, Object param2); * </pre></code> * <p> * The best matching method is searched for with the following strategy: * <ol> * <li>public method with exact signature match in class hierarchy</li> * <li>non-public method with exact signature match on declaring class</li> * <li>public method with similar signature in class hierarchy</li> * <li>non-public method with similar signature on declaring class</li> * </ol> * * @param name The method name * @param args The method arguments * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect call(String name, Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" method, i.e. the one with exact // matching argument types try { Method method = exactMethod(name, types); return on(method, object, args); } // If there is no exact match, try to find a method that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { try { Method method = similarMethod(name, types); return on(method, object, args); } catch (NoSuchMethodException e1) { throw new ReflectException(e1); } } } /** * Searches a method with the exact same signature as desired. * <p> * If a public method is found in the class hierarchy, this method is returned. * Otherwise a private method with the exact same signature is returned. * If no exact match could be found, we let the {@code NoSuchMethodException} pass through. */ private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with exact signature match in class hierarchy try { return t.getMethod(name, types); } // second priority: find a private method with exact signature match on declaring class catch (NoSuchMethodException e) { do { try { return t.getDeclaredMethod(name, types); } catch (NoSuchMethodException ignore) {} t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException(); } } /** * Searches a method with a similar signature as desired using * {@link #isSimilarSignature(java.lang.reflect.Method, String, Class[])}. * <p> * First public methods are searched in the class hierarchy, then private * methods on the declaring class. If a method could be found, it is * returned, otherwise a {@code NoSuchMethodException} is thrown. */ private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with a "similar" signature in class hierarchy // similar interpreted in when primitive argument types are converted to their wrappers for (Method method : t.getMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } // second priority: find a non-public method with a "similar" signature on declaring class do { for (Method method : t.getDeclaredMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found on type " + type() + "."); } /** * Determines if a method has a "similar" signature, especially if wrapping * primitive argument types would result in an exactly matching signature. */ private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) { return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); } /** * Call a constructor. * <p> * This is a convenience method for calling * <code>create(new Object[0])</code> * * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #create(Object...) */ public Reflect create() throws ReflectException { return create(new Object[0]); } /** * Call a constructor. * <p> * This is roughly equivalent to {@link Constructor#newInstance(Object...)}. * If the wrapped object is a {@link Class}, then this will create a new * object of that class. If the wrapped object is any other {@link Object}, * then this will create a new object of the same type. * <p> * Just like {@link Constructor#newInstance(Object...)}, this will try to * wrap primitive types or unwrap primitive type wrappers if applicable. If * several constructors are applicable, by that rule, the first one * encountered is called. i.e. when calling <code><pre> * on(C.class).create(1, 1); * </pre></code> The first of the following constructors will be applied: * <code><pre> * public C(int param1, Integer param2); * public C(Integer param1, int param2); * public C(Number param1, Number param2); * public C(Number param1, Object param2); * public C(int param1, Object param2); * </pre></code> * * @param args The constructor arguments * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect create(Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" constructor, i.e. the one with exact // matching argument types try { Constructor<?> constructor = type().getDeclaredConstructor(types); return on(constructor, args); } // If there is no exact match, try to find one that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { for (Constructor<?> constructor : type().getDeclaredConstructors()) { if (match(constructor.getParameterTypes(), types)) { return on(constructor, args); } } throw new ReflectException(e); } } /** * Create a proxy for the wrapped object allowing to typesafely invoke * methods on it using a custom interface * * @param proxyType The interface type that is implemented by the proxy * @return A proxy for the wrapped object */ @SuppressWarnings("unchecked") public <P> P as(final Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @SuppressWarnings("null") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); // Actual method name matches always come first try { return on(type, object).call(name, args).get(); } // [#14] Emulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler); } /** * Get the POJO property name of an getter/setter */ private static String property(String string) { int length = string.length(); if (length == 0) { return ""; } else if (length == 1) { return string.toLowerCase(Locale.ROOT); } else { return string.substring(0, 1).toLowerCase(Locale.ROOT) + string.substring(1); } } // --------------------------------------------------------------------- // Object API // --------------------------------------------------------------------- /** * Check whether two arrays of types match, converting primitive types to * their corresponding wrappers. */ private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) { if (declaredTypes.length == actualTypes.length) { for (int i = 0; i < actualTypes.length; i++) { if (actualTypes[i] == NULL.class) continue; if (wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) continue; return false; } return true; } else { return false; } } /** * {@inheritDoc} */ @Override public int hashCode() { return object.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof Reflect) { return object.equals(((Reflect) obj).get()); } return false; } /** * {@inheritDoc} */ @Override public String toString() { return object.toString(); } // --------------------------------------------------------------------- // Utility methods // --------------------------------------------------------------------- /** * Wrap an object created from a constructor */ private static Reflect on(Constructor<?> constructor, Object... args) throws ReflectException { try { return on(constructor.getDeclaringClass(), accessible(constructor).newInstance(args)); } catch (Exception e) { throw new ReflectException(e); } } /** * Wrap an object returned from a method */ private static Reflect on(Method method, Object object, Object... args) throws ReflectException { try { accessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { return on(method.invoke(object, args)); } } catch (Exception e) { throw new ReflectException(e); } } /** * Unwrap an object */ private static Object unwrap(Object object) { if (object instanceof Reflect) { return ((Reflect) object).get(); } return object; } /** * Get an array of types for an array of objects * * @see Object#getClass() */ private static Class<?>[] types(Object... values) { if (values == null) { return new Class[0]; } Class<?>[] result = new Class[values.length]; for (int i = 0; i < values.length; i++) { Object value = values[i]; result[i] = value == null ? NULL.class : value.getClass(); } return result; } /** * Load a class * * @see Class#forName(String) */ private static Class<?> forName(String name) throws ReflectException { try { return Class.forName(name); } catch (Exception e) { throw new ReflectException(e); } } private static Class<?> forName(String name, ClassLoader classLoader) throws ReflectException { try { return Class.forName(name, true, classLoader); } catch (Exception e) { throw new ReflectException(e); } } /** * Get the type of the wrapped object. * * @see Object#getClass() */ public Class<?> type() { return type; } /** * Get a wrapper type for a primitive type, or the argument type itself, if * it is not a primitive type. */ public static Class<?> wrapper(Class<?> type) { if (type == null) { return null; } else if (type.isPrimitive()) { if (boolean.class == type) { return Boolean.class; } else if (int.class == type) { return Integer.class; } else if (long.class == type) { return Long.class; } else if (short.class == type) { return Short.class; } else if (byte.class == type) { return Byte.class; } else if (double.class == type) { return Double.class; } else if (float.class == type) { return Float.class; } else if (char.class == type) { return Character.class; } else if (void.class == type) { return Void.class; } } return type; } private static class NULL {} }
131390_4
/* * Copyright 2008 ZXing authors * * 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.google.zxing.datamatrix; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.common.BitMatrix; import com.google.zxing.datamatrix.encoder.DefaultPlacement; import com.google.zxing.Dimension; import com.google.zxing.datamatrix.encoder.ErrorCorrection; import com.google.zxing.datamatrix.encoder.HighLevelEncoder; import com.google.zxing.datamatrix.encoder.MinimalEncoder; import com.google.zxing.datamatrix.encoder.SymbolInfo; import com.google.zxing.datamatrix.encoder.SymbolShapeHint; import com.google.zxing.qrcode.encoder.ByteMatrix; import java.util.Map; import java.nio.charset.Charset; /** * This object renders a Data Matrix code as a BitMatrix 2D array of greyscale values. * * @author [email protected] (Daniel Switkin) * @author Guillaume Le Biller Added to zxing lib. */ public final class DataMatrixWriter implements Writer { @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) { if (contents.isEmpty()) { throw new IllegalArgumentException("Found empty contents"); } if (format != BarcodeFormat.DATA_MATRIX) { throw new IllegalArgumentException("Can only encode DATA_MATRIX, but got " + format); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions can't be negative: " + width + 'x' + height); } // Try to get force shape & min / max size SymbolShapeHint shape = SymbolShapeHint.FORCE_NONE; Dimension minSize = null; Dimension maxSize = null; if (hints != null) { SymbolShapeHint requestedShape = (SymbolShapeHint) hints.get(EncodeHintType.DATA_MATRIX_SHAPE); if (requestedShape != null) { shape = requestedShape; } @SuppressWarnings("deprecation") Dimension requestedMinSize = (Dimension) hints.get(EncodeHintType.MIN_SIZE); if (requestedMinSize != null) { minSize = requestedMinSize; } @SuppressWarnings("deprecation") Dimension requestedMaxSize = (Dimension) hints.get(EncodeHintType.MAX_SIZE); if (requestedMaxSize != null) { maxSize = requestedMaxSize; } } //1. step: Data encodation String encoded; boolean hasCompactionHint = hints != null && hints.containsKey(EncodeHintType.DATA_MATRIX_COMPACT) && Boolean.parseBoolean(hints.get(EncodeHintType.DATA_MATRIX_COMPACT).toString()); if (hasCompactionHint) { boolean hasGS1FormatHint = hints.containsKey(EncodeHintType.GS1_FORMAT) && Boolean.parseBoolean(hints.get(EncodeHintType.GS1_FORMAT).toString()); Charset charset = null; boolean hasEncodingHint = hints.containsKey(EncodeHintType.CHARACTER_SET); if (hasEncodingHint) { charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); } encoded = MinimalEncoder.encodeHighLevel(contents, charset, hasGS1FormatHint ? 0x1D : -1, shape); } else { boolean hasForceC40Hint = hints != null && hints.containsKey(EncodeHintType.FORCE_C40) && Boolean.parseBoolean(hints.get(EncodeHintType.FORCE_C40).toString()); encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, hasForceC40Hint); } SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.length(), shape, minSize, maxSize, true); //2. step: ECC generation String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo); //3. step: Module placement in Matrix DefaultPlacement placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight()); placement.place(); //4. step: low-level encoding return encodeLowLevel(placement, symbolInfo, width, height); } /** * Encode the given symbol info to a bit matrix. * * @param placement The DataMatrix placement. * @param symbolInfo The symbol info to encode. * @return The bit matrix generated. */ private static BitMatrix encodeLowLevel(DefaultPlacement placement, SymbolInfo symbolInfo, int width, int height) { int symbolWidth = symbolInfo.getSymbolDataWidth(); int symbolHeight = symbolInfo.getSymbolDataHeight(); ByteMatrix matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight()); int matrixY = 0; for (int y = 0; y < symbolHeight; y++) { // Fill the top edge with alternate 0 / 1 int matrixX; if ((y % symbolInfo.matrixHeight) == 0) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, (x % 2) == 0); matrixX++; } matrixY++; } matrixX = 0; for (int x = 0; x < symbolWidth; x++) { // Fill the right edge with full 1 if ((x % symbolInfo.matrixWidth) == 0) { matrix.set(matrixX, matrixY, true); matrixX++; } matrix.set(matrixX, matrixY, placement.getBit(x, y)); matrixX++; // Fill the right edge with alternate 0 / 1 if ((x % symbolInfo.matrixWidth) == symbolInfo.matrixWidth - 1) { matrix.set(matrixX, matrixY, (y % 2) == 0); matrixX++; } } matrixY++; // Fill the bottom edge with full 1 if ((y % symbolInfo.matrixHeight) == symbolInfo.matrixHeight - 1) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, true); matrixX++; } matrixY++; } } return convertByteMatrixToBitMatrix(matrix, width, height); } /** * Convert the ByteMatrix to BitMatrix. * * @param reqHeight The requested height of the image (in pixels) with the Datamatrix code * @param reqWidth The requested width of the image (in pixels) with the Datamatrix code * @param matrix The input matrix. * @return The output matrix. */ private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); int outputWidth = Math.max(reqWidth, matrixWidth); int outputHeight = Math.max(reqHeight, matrixHeight); int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight); int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ; int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ; BitMatrix output; // remove padding if requested width and height are too small if (reqHeight < matrixHeight || reqWidth < matrixWidth) { leftPadding = 0; topPadding = 0; output = new BitMatrix(matrixWidth, matrixHeight); } else { output = new BitMatrix(reqWidth, reqHeight); } output.clear(); for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) { // Write the contents of this row of the bytematrix for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) { if (matrix.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } }
wixche/zxing
core/src/main/java/com/google/zxing/datamatrix/DataMatrixWriter.java
2,494
//2. step: ECC generation
line_comment
nl
/* * Copyright 2008 ZXing authors * * 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.google.zxing.datamatrix; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.common.BitMatrix; import com.google.zxing.datamatrix.encoder.DefaultPlacement; import com.google.zxing.Dimension; import com.google.zxing.datamatrix.encoder.ErrorCorrection; import com.google.zxing.datamatrix.encoder.HighLevelEncoder; import com.google.zxing.datamatrix.encoder.MinimalEncoder; import com.google.zxing.datamatrix.encoder.SymbolInfo; import com.google.zxing.datamatrix.encoder.SymbolShapeHint; import com.google.zxing.qrcode.encoder.ByteMatrix; import java.util.Map; import java.nio.charset.Charset; /** * This object renders a Data Matrix code as a BitMatrix 2D array of greyscale values. * * @author [email protected] (Daniel Switkin) * @author Guillaume Le Biller Added to zxing lib. */ public final class DataMatrixWriter implements Writer { @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) { if (contents.isEmpty()) { throw new IllegalArgumentException("Found empty contents"); } if (format != BarcodeFormat.DATA_MATRIX) { throw new IllegalArgumentException("Can only encode DATA_MATRIX, but got " + format); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions can't be negative: " + width + 'x' + height); } // Try to get force shape & min / max size SymbolShapeHint shape = SymbolShapeHint.FORCE_NONE; Dimension minSize = null; Dimension maxSize = null; if (hints != null) { SymbolShapeHint requestedShape = (SymbolShapeHint) hints.get(EncodeHintType.DATA_MATRIX_SHAPE); if (requestedShape != null) { shape = requestedShape; } @SuppressWarnings("deprecation") Dimension requestedMinSize = (Dimension) hints.get(EncodeHintType.MIN_SIZE); if (requestedMinSize != null) { minSize = requestedMinSize; } @SuppressWarnings("deprecation") Dimension requestedMaxSize = (Dimension) hints.get(EncodeHintType.MAX_SIZE); if (requestedMaxSize != null) { maxSize = requestedMaxSize; } } //1. step: Data encodation String encoded; boolean hasCompactionHint = hints != null && hints.containsKey(EncodeHintType.DATA_MATRIX_COMPACT) && Boolean.parseBoolean(hints.get(EncodeHintType.DATA_MATRIX_COMPACT).toString()); if (hasCompactionHint) { boolean hasGS1FormatHint = hints.containsKey(EncodeHintType.GS1_FORMAT) && Boolean.parseBoolean(hints.get(EncodeHintType.GS1_FORMAT).toString()); Charset charset = null; boolean hasEncodingHint = hints.containsKey(EncodeHintType.CHARACTER_SET); if (hasEncodingHint) { charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); } encoded = MinimalEncoder.encodeHighLevel(contents, charset, hasGS1FormatHint ? 0x1D : -1, shape); } else { boolean hasForceC40Hint = hints != null && hints.containsKey(EncodeHintType.FORCE_C40) && Boolean.parseBoolean(hints.get(EncodeHintType.FORCE_C40).toString()); encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, hasForceC40Hint); } SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.length(), shape, minSize, maxSize, true); //2. step:<SUF> String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo); //3. step: Module placement in Matrix DefaultPlacement placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight()); placement.place(); //4. step: low-level encoding return encodeLowLevel(placement, symbolInfo, width, height); } /** * Encode the given symbol info to a bit matrix. * * @param placement The DataMatrix placement. * @param symbolInfo The symbol info to encode. * @return The bit matrix generated. */ private static BitMatrix encodeLowLevel(DefaultPlacement placement, SymbolInfo symbolInfo, int width, int height) { int symbolWidth = symbolInfo.getSymbolDataWidth(); int symbolHeight = symbolInfo.getSymbolDataHeight(); ByteMatrix matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight()); int matrixY = 0; for (int y = 0; y < symbolHeight; y++) { // Fill the top edge with alternate 0 / 1 int matrixX; if ((y % symbolInfo.matrixHeight) == 0) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, (x % 2) == 0); matrixX++; } matrixY++; } matrixX = 0; for (int x = 0; x < symbolWidth; x++) { // Fill the right edge with full 1 if ((x % symbolInfo.matrixWidth) == 0) { matrix.set(matrixX, matrixY, true); matrixX++; } matrix.set(matrixX, matrixY, placement.getBit(x, y)); matrixX++; // Fill the right edge with alternate 0 / 1 if ((x % symbolInfo.matrixWidth) == symbolInfo.matrixWidth - 1) { matrix.set(matrixX, matrixY, (y % 2) == 0); matrixX++; } } matrixY++; // Fill the bottom edge with full 1 if ((y % symbolInfo.matrixHeight) == symbolInfo.matrixHeight - 1) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, true); matrixX++; } matrixY++; } } return convertByteMatrixToBitMatrix(matrix, width, height); } /** * Convert the ByteMatrix to BitMatrix. * * @param reqHeight The requested height of the image (in pixels) with the Datamatrix code * @param reqWidth The requested width of the image (in pixels) with the Datamatrix code * @param matrix The input matrix. * @return The output matrix. */ private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); int outputWidth = Math.max(reqWidth, matrixWidth); int outputHeight = Math.max(reqHeight, matrixHeight); int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight); int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ; int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ; BitMatrix output; // remove padding if requested width and height are too small if (reqHeight < matrixHeight || reqWidth < matrixWidth) { leftPadding = 0; topPadding = 0; output = new BitMatrix(matrixWidth, matrixHeight); } else { output = new BitMatrix(reqWidth, reqHeight); } output.clear(); for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) { // Write the contents of this row of the bytematrix for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) { if (matrix.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } }
137634_39
package com.cold.library; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import androidx.customview.widget.ViewDragHelper; import java.lang.reflect.Field; /** * name: SlideLayout * desc: 侧滑菜单 * author: * date: 2019-09-04 15:10 * remark: */ public class SlideLayout extends FrameLayout implements View.OnTouchListener { private static final String TAG = SlideLayout.class.getName(); /** * 滑动速率,每秒dip */ private static final int SLIDING_VELOCITY = 600; /** * debug */ private boolean isDebug = true; /** * 最底层视图 */ private View mBaseView; /** * 清屏视图 */ private View mDrawerView; /** * 菜单视图 */ private View mMenuView; /** * */ private Context mContext; /** * 抽屉视图是否可见 */ private boolean flag = true; /** * 页面状态 1:侧边栏可见,清屏可见 2:侧边栏不可见 清屏可见 3:侧边栏和清屏界面不可见,初始状态是都可见 */ // private int state = 1; /** * ViewDragHelper */ private ViewDragHelper mHelper; /** * drawer显示出来的占自身的百分比 */ private float mLeftMenuOnScrren; /** * slideview 移动百分比 */ private float mSlideViewOnScreen; /** * 控制的view */ private View controlView; /** * 是否计算完成 */ private boolean isCalculate = false; /** * 当前State */ private int mDragState; /** * 侧边栏不随手势滑动 */ private int newLeft; /** * 侧边栏是否随手势滑动 */ private boolean isMenuGesture; /** * 进度监听 */ private ISlideListener slideListener; /** * 设置进度监听 * @param * @return void */ public void setSlideListener(ISlideListener slideListener) { this.slideListener = slideListener; } /** * ViewDragHelper回调接口 */ ViewDragHelper.Callback cb = new ViewDragHelper.Callback() { @Override public int clampViewPositionHorizontal(View child, int left, int dx) { log("clampViewPositionHorizontal"); int drawerLeft = Math.min( Math.max(getWidth() - child.getWidth(), left), getWidth()); if(!isMenuGesture && child == mMenuView) { log("clampViewPositionHorizontal newLeft: " + newLeft); return newLeft; } return drawerLeft; } @Override public boolean tryCaptureView(View child, int pointerId) { log("tryCaptureView"); return false; } @Override public void onEdgeDragStarted(int edgeFlags, int pointerId) { log("onEdgeDragStarted"); if(mDragState == ViewDragHelper.STATE_IDLE) mHelper.captureChildView(controlView, pointerId); } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { log("onViewPositionChanged"); final int childWidth = changedView.getWidth(); // float offset = (left - (getWidth() - childWidth))* 1.0f / childWidth; float offset = (float) left / childWidth; if(slideListener != null) { slideListener.onPositionChanged(offset); } if(changedView == mDrawerView) { mLeftMenuOnScrren = offset; } else if(changedView == mMenuView){ mSlideViewOnScreen = offset; } changedView.setVisibility(offset == 1 ? View.INVISIBLE : View.VISIBLE); invalidate(); } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { log("onViewReleased"); final int childWidth = releasedChild.getWidth(); float offset = (float)(releasedChild.getLeft() - (getWidth() - childWidth)) / (float)childWidth; if(releasedChild == mDrawerView) { mLeftMenuOnScrren = offset; } else if(releasedChild == mMenuView){ mSlideViewOnScreen = offset; } if(xvel < 0 || xvel == 0 && offset < 0.5f ) { // 目标向左移动 if(releasedChild == mDrawerView) { // state = 2; } else if(releasedChild == mMenuView){ // state = 1; newLeft = getWidth() - childWidth; } flag = true; mHelper.settleCapturedViewAt(getWidth() - childWidth, releasedChild.getTop()); } else { // 目标向右移动 if(releasedChild == mDrawerView) { // state = 3; } else if(releasedChild == mMenuView){ newLeft = getWidth(); // state = 2; } mHelper.settleCapturedViewAt(getWidth(), releasedChild.getTop()); } // mHelper.settleCapturedViewAt(flag ? getWidth() - childWidth : getWidth(), releasedChild.getTop()); invalidate(); } @Override public int getViewHorizontalDragRange(View child) { log("getViewHorizontalDragRange"); return controlView == child ? child.getWidth() : 0; } @Override public void onViewDragStateChanged(int state) { log("onViewDragStateChanged state: " + state); mDragState = state; } }; public SlideLayout(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.slidelayout); isMenuGesture = ta.getBoolean(R.styleable.slidelayout_menu_gesture, true); ta.recycle(); final float density = getResources().getDisplayMetrics().density; final float minVel = SLIDING_VELOCITY * density; mHelper = ViewDragHelper.create(this, 1.0f, cb); mHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT); mHelper.setMinVelocity(minVel); setDrawerLeftEdgeSize(context, mHelper, 1.0f); setOnTouchListener(this); } /** * 设置滑动范围 * @param: activity * @param: dragHelper 设置范围的ViewDragHelper * @param: displayWidthPercentage 滑动因子,为 1 全屏滑动 * @return: void */ public void setDrawerLeftEdgeSize(Context activity, ViewDragHelper dragHelper, float displayWidthPercentage) { Field edgeSizeField; try { edgeSizeField = dragHelper.getClass().getDeclaredField("mEdgeSize"); edgeSizeField.setAccessible(true); DisplayMetrics dm = new DisplayMetrics(); ((Activity)activity).getWindowManager().getDefaultDisplay().getMetrics(dm); edgeSizeField.setInt(dragHelper, (int) (dm.widthPixels * displayWidthPercentage)); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed,l, t, r,b); MarginLayoutParams lp = (MarginLayoutParams) mDrawerView.getLayoutParams(); final int menuWidth = mDrawerView.getMeasuredWidth(); int childLeft = (getWidth() - menuWidth) + (int)(menuWidth * mLeftMenuOnScrren); mDrawerView.layout(childLeft, lp.topMargin, childLeft + menuWidth, lp.topMargin + mDrawerView.getMeasuredHeight()); MarginLayoutParams lp1 = (MarginLayoutParams) mMenuView.getLayoutParams(); final int menuWidth1 = mMenuView.getMeasuredWidth(); int childLeft1 = (getWidth() - menuWidth1) + (int)(menuWidth1 * mSlideViewOnScreen); mMenuView.layout(childLeft1, lp1.topMargin, childLeft1 + menuWidth1, lp1.topMargin + mMenuView.getMeasuredHeight()); newLeft = mMenuView.getLeft(); } /** * 获取容器内的控件引用 * @param: * @return: */ @Override protected void onFinishInflate() { super.onFinishInflate(); int count = getChildCount(); log("count: " + count); if(count != 3){ throw new IllegalArgumentException("child view count must equal 3"); } if(count == 3) { mBaseView = getChildAt(0); mDrawerView = getChildAt(1); mMenuView = getChildAt(2); } controlView = mMenuView; } /** * 按下点X坐标 */ private float startX; @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()){ case MotionEvent.ACTION_DOWN: startX = ev.getX(); mHelper.shouldInterceptTouchEvent(ev); return false; case MotionEvent.ACTION_MOVE: // float endX = ev.getX(); // float distanceX = endX - startX; // if(mMenuView.getVisibility() == View.VISIBLE) { // return false; // } else if(mMenuView.getVisibility() == View.GONE) { // if ((flag && distanceX > 0 && isGreaterThanMinSize(endX, startX)) || (!flag && distanceX < 0 && isGreaterThanMinSize(endX, startX))) { // return mHelper.shouldInterceptTouchEvent(ev); // } else if ((flag && distanceX < 0) || (!flag && distanceX > 0)) { // return false; // } // } break; case MotionEvent.ACTION_UP: return mHelper.shouldInterceptTouchEvent(ev); default: break; } return super.onInterceptTouchEvent(ev); } /** * 滑动范围阈值,可以修改布局上存在滑动控件时的移动范围 * @param: * @return: */ public boolean isGreaterThanMinSize(float x1, float x2) { return Math.abs((int)(x1 - x2)) > 66; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: startX = ev.getX(); mHelper.processTouchEvent(ev); isCalculate = false;//计算开始 break; case MotionEvent.ACTION_MOVE: float endX = ev.getX(); float distanceX = endX - startX; if(!isCalculate) { if ((mMenuView.getLeft() >= getWidth() - mMenuView.getWidth()) && (mMenuView.getLeft() < getWidth() - mMenuView.getWidth() / 2)) { // 侧边栏显示 if(distanceX > 0) { // 向右滑动 controlView = mMenuView; isCalculate = true; } else { // 向左滑动,不叼他 } } else if ((mMenuView.getLeft() >= getWidth() - mMenuView.getWidth() / 2) && (mDrawerView.getLeft() < getWidth() - mDrawerView.getWidth() / 2)) { // 侧边栏隐藏,清屏界面显示 if(distanceX > 0) { // 向右滑动,移动drawerview controlView = mDrawerView; isCalculate = true; } else if(distanceX < 0) {// 向左滑动,移动slideview controlView = mMenuView; isCalculate = true; } } else if (mDrawerView.getLeft() >= getWidth() - mDrawerView.getWidth() / 2) { // 清屏界面隐藏 if(distanceX < 0) { // 移动移动drawerview controlView = mDrawerView; isCalculate = true; } else { // 不管 } } } if(isCalculate) { mHelper.processTouchEvent(ev); } break; case MotionEvent.ACTION_UP: mHelper.processTouchEvent(ev); break; default: mHelper.processTouchEvent(ev); break; } return true; } @Override public void computeScroll() { if (mHelper.continueSettling(true)) { invalidate(); } } /** * 恢复清屏内容 * @param * @return */ public void restoreContent() { if(mDrawerView != null) { mLeftMenuOnScrren = 0.0f; flag = true; mHelper.smoothSlideViewTo(mDrawerView, 0, mDrawerView.getTop()); invalidate(); } } /** * 关闭drawer,预留 * @param: * @return: void */ public void closeDrawer() { View menuView = mDrawerView; mHelper.smoothSlideViewTo(menuView, -menuView.getWidth(), menuView.getTop()); } /** * 打开drawer,预留 * @param: * @return: void */ public void openDrawer() { View menuView = mDrawerView; mHelper.smoothSlideViewTo(menuView, 0, menuView.getTop()); } /** * 关闭drawer,预留 * @param: * @return: void */ public void closeSlideMenu() { View menuView = mMenuView; mSlideViewOnScreen = 1.0f; newLeft = getWidth(); mHelper.smoothSlideViewTo(menuView, getWidth(), menuView.getTop()); invalidate(); } /** * 打开drawer,预留 * @param: * @return: void */ public void openSlideMenu() { View menuView = mMenuView; mSlideViewOnScreen = 0.0f; newLeft = getWidth() - mMenuView.getWidth(); mHelper.smoothSlideViewTo(menuView, getWidth() - mMenuView.getWidth(), menuView.getTop()); invalidate(); } /** * 判断侧滑菜单是否打开 * @param: * @return: */ public boolean isSlideMenuOpen() { return mMenuView.getLeft() >= getWidth() - mMenuView.getWidth() && mMenuView.getLeft() < getWidth() - mMenuView.getWidth() / 2; } /** * 以下4个参数用来记录按下点的初始坐标和结束坐标 */ private float firstDownX = 0; private float lastDownX = 0; private float firstDownY = 0; private float lastDownY = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: firstDownX = event.getX(); firstDownY = event.getY(); lastDownX = event.getX(); lastDownY = event.getY(); break; case MotionEvent.ACTION_MOVE: lastDownX = event.getX(); lastDownY = event.getY(); break; case MotionEvent.ACTION_UP: lastDownX = event.getX(); lastDownY = event.getY(); float deltaX = Math.abs(lastDownX - firstDownX); float deltaY = Math.abs(lastDownY - firstDownY); if (deltaX < 10 && deltaY < 10) { if(isTouchCloseSlideArea(lastDownX, lastDownY)) { if(isSlideMenuOpen()){ closeSlideMenu(); return true; } } } break; } return false; } /** * 判断是否点击在了关闭侧边栏的区域 * @param: x 按下点x坐标 * @param: y 按下点y坐标 * @return: true:关闭 false:不关闭 */ private boolean isTouchCloseSlideArea(float x, float y) { int left = 0; int top = 0; int right = getWidth() - mMenuView.getWidth(); int bottom = mMenuView.getHeight(); if (x >= left && x <= right && y >= top && y <= bottom) { return true; } return false; } private void log(String msg) { if(isDebug) Log.e(TAG, "===================================> " + msg); } }
wjianchen13/SlideDemo
library/src/main/java/com/cold/library/SlideLayout.java
4,767
/** * 关闭drawer,预留 * @param: * @return: void */
block_comment
nl
package com.cold.library; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import androidx.customview.widget.ViewDragHelper; import java.lang.reflect.Field; /** * name: SlideLayout * desc: 侧滑菜单 * author: * date: 2019-09-04 15:10 * remark: */ public class SlideLayout extends FrameLayout implements View.OnTouchListener { private static final String TAG = SlideLayout.class.getName(); /** * 滑动速率,每秒dip */ private static final int SLIDING_VELOCITY = 600; /** * debug */ private boolean isDebug = true; /** * 最底层视图 */ private View mBaseView; /** * 清屏视图 */ private View mDrawerView; /** * 菜单视图 */ private View mMenuView; /** * */ private Context mContext; /** * 抽屉视图是否可见 */ private boolean flag = true; /** * 页面状态 1:侧边栏可见,清屏可见 2:侧边栏不可见 清屏可见 3:侧边栏和清屏界面不可见,初始状态是都可见 */ // private int state = 1; /** * ViewDragHelper */ private ViewDragHelper mHelper; /** * drawer显示出来的占自身的百分比 */ private float mLeftMenuOnScrren; /** * slideview 移动百分比 */ private float mSlideViewOnScreen; /** * 控制的view */ private View controlView; /** * 是否计算完成 */ private boolean isCalculate = false; /** * 当前State */ private int mDragState; /** * 侧边栏不随手势滑动 */ private int newLeft; /** * 侧边栏是否随手势滑动 */ private boolean isMenuGesture; /** * 进度监听 */ private ISlideListener slideListener; /** * 设置进度监听 * @param * @return void */ public void setSlideListener(ISlideListener slideListener) { this.slideListener = slideListener; } /** * ViewDragHelper回调接口 */ ViewDragHelper.Callback cb = new ViewDragHelper.Callback() { @Override public int clampViewPositionHorizontal(View child, int left, int dx) { log("clampViewPositionHorizontal"); int drawerLeft = Math.min( Math.max(getWidth() - child.getWidth(), left), getWidth()); if(!isMenuGesture && child == mMenuView) { log("clampViewPositionHorizontal newLeft: " + newLeft); return newLeft; } return drawerLeft; } @Override public boolean tryCaptureView(View child, int pointerId) { log("tryCaptureView"); return false; } @Override public void onEdgeDragStarted(int edgeFlags, int pointerId) { log("onEdgeDragStarted"); if(mDragState == ViewDragHelper.STATE_IDLE) mHelper.captureChildView(controlView, pointerId); } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { log("onViewPositionChanged"); final int childWidth = changedView.getWidth(); // float offset = (left - (getWidth() - childWidth))* 1.0f / childWidth; float offset = (float) left / childWidth; if(slideListener != null) { slideListener.onPositionChanged(offset); } if(changedView == mDrawerView) { mLeftMenuOnScrren = offset; } else if(changedView == mMenuView){ mSlideViewOnScreen = offset; } changedView.setVisibility(offset == 1 ? View.INVISIBLE : View.VISIBLE); invalidate(); } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { log("onViewReleased"); final int childWidth = releasedChild.getWidth(); float offset = (float)(releasedChild.getLeft() - (getWidth() - childWidth)) / (float)childWidth; if(releasedChild == mDrawerView) { mLeftMenuOnScrren = offset; } else if(releasedChild == mMenuView){ mSlideViewOnScreen = offset; } if(xvel < 0 || xvel == 0 && offset < 0.5f ) { // 目标向左移动 if(releasedChild == mDrawerView) { // state = 2; } else if(releasedChild == mMenuView){ // state = 1; newLeft = getWidth() - childWidth; } flag = true; mHelper.settleCapturedViewAt(getWidth() - childWidth, releasedChild.getTop()); } else { // 目标向右移动 if(releasedChild == mDrawerView) { // state = 3; } else if(releasedChild == mMenuView){ newLeft = getWidth(); // state = 2; } mHelper.settleCapturedViewAt(getWidth(), releasedChild.getTop()); } // mHelper.settleCapturedViewAt(flag ? getWidth() - childWidth : getWidth(), releasedChild.getTop()); invalidate(); } @Override public int getViewHorizontalDragRange(View child) { log("getViewHorizontalDragRange"); return controlView == child ? child.getWidth() : 0; } @Override public void onViewDragStateChanged(int state) { log("onViewDragStateChanged state: " + state); mDragState = state; } }; public SlideLayout(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.slidelayout); isMenuGesture = ta.getBoolean(R.styleable.slidelayout_menu_gesture, true); ta.recycle(); final float density = getResources().getDisplayMetrics().density; final float minVel = SLIDING_VELOCITY * density; mHelper = ViewDragHelper.create(this, 1.0f, cb); mHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT); mHelper.setMinVelocity(minVel); setDrawerLeftEdgeSize(context, mHelper, 1.0f); setOnTouchListener(this); } /** * 设置滑动范围 * @param: activity * @param: dragHelper 设置范围的ViewDragHelper * @param: displayWidthPercentage 滑动因子,为 1 全屏滑动 * @return: void */ public void setDrawerLeftEdgeSize(Context activity, ViewDragHelper dragHelper, float displayWidthPercentage) { Field edgeSizeField; try { edgeSizeField = dragHelper.getClass().getDeclaredField("mEdgeSize"); edgeSizeField.setAccessible(true); DisplayMetrics dm = new DisplayMetrics(); ((Activity)activity).getWindowManager().getDefaultDisplay().getMetrics(dm); edgeSizeField.setInt(dragHelper, (int) (dm.widthPixels * displayWidthPercentage)); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed,l, t, r,b); MarginLayoutParams lp = (MarginLayoutParams) mDrawerView.getLayoutParams(); final int menuWidth = mDrawerView.getMeasuredWidth(); int childLeft = (getWidth() - menuWidth) + (int)(menuWidth * mLeftMenuOnScrren); mDrawerView.layout(childLeft, lp.topMargin, childLeft + menuWidth, lp.topMargin + mDrawerView.getMeasuredHeight()); MarginLayoutParams lp1 = (MarginLayoutParams) mMenuView.getLayoutParams(); final int menuWidth1 = mMenuView.getMeasuredWidth(); int childLeft1 = (getWidth() - menuWidth1) + (int)(menuWidth1 * mSlideViewOnScreen); mMenuView.layout(childLeft1, lp1.topMargin, childLeft1 + menuWidth1, lp1.topMargin + mMenuView.getMeasuredHeight()); newLeft = mMenuView.getLeft(); } /** * 获取容器内的控件引用 * @param: * @return: */ @Override protected void onFinishInflate() { super.onFinishInflate(); int count = getChildCount(); log("count: " + count); if(count != 3){ throw new IllegalArgumentException("child view count must equal 3"); } if(count == 3) { mBaseView = getChildAt(0); mDrawerView = getChildAt(1); mMenuView = getChildAt(2); } controlView = mMenuView; } /** * 按下点X坐标 */ private float startX; @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()){ case MotionEvent.ACTION_DOWN: startX = ev.getX(); mHelper.shouldInterceptTouchEvent(ev); return false; case MotionEvent.ACTION_MOVE: // float endX = ev.getX(); // float distanceX = endX - startX; // if(mMenuView.getVisibility() == View.VISIBLE) { // return false; // } else if(mMenuView.getVisibility() == View.GONE) { // if ((flag && distanceX > 0 && isGreaterThanMinSize(endX, startX)) || (!flag && distanceX < 0 && isGreaterThanMinSize(endX, startX))) { // return mHelper.shouldInterceptTouchEvent(ev); // } else if ((flag && distanceX < 0) || (!flag && distanceX > 0)) { // return false; // } // } break; case MotionEvent.ACTION_UP: return mHelper.shouldInterceptTouchEvent(ev); default: break; } return super.onInterceptTouchEvent(ev); } /** * 滑动范围阈值,可以修改布局上存在滑动控件时的移动范围 * @param: * @return: */ public boolean isGreaterThanMinSize(float x1, float x2) { return Math.abs((int)(x1 - x2)) > 66; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: startX = ev.getX(); mHelper.processTouchEvent(ev); isCalculate = false;//计算开始 break; case MotionEvent.ACTION_MOVE: float endX = ev.getX(); float distanceX = endX - startX; if(!isCalculate) { if ((mMenuView.getLeft() >= getWidth() - mMenuView.getWidth()) && (mMenuView.getLeft() < getWidth() - mMenuView.getWidth() / 2)) { // 侧边栏显示 if(distanceX > 0) { // 向右滑动 controlView = mMenuView; isCalculate = true; } else { // 向左滑动,不叼他 } } else if ((mMenuView.getLeft() >= getWidth() - mMenuView.getWidth() / 2) && (mDrawerView.getLeft() < getWidth() - mDrawerView.getWidth() / 2)) { // 侧边栏隐藏,清屏界面显示 if(distanceX > 0) { // 向右滑动,移动drawerview controlView = mDrawerView; isCalculate = true; } else if(distanceX < 0) {// 向左滑动,移动slideview controlView = mMenuView; isCalculate = true; } } else if (mDrawerView.getLeft() >= getWidth() - mDrawerView.getWidth() / 2) { // 清屏界面隐藏 if(distanceX < 0) { // 移动移动drawerview controlView = mDrawerView; isCalculate = true; } else { // 不管 } } } if(isCalculate) { mHelper.processTouchEvent(ev); } break; case MotionEvent.ACTION_UP: mHelper.processTouchEvent(ev); break; default: mHelper.processTouchEvent(ev); break; } return true; } @Override public void computeScroll() { if (mHelper.continueSettling(true)) { invalidate(); } } /** * 恢复清屏内容 * @param * @return */ public void restoreContent() { if(mDrawerView != null) { mLeftMenuOnScrren = 0.0f; flag = true; mHelper.smoothSlideViewTo(mDrawerView, 0, mDrawerView.getTop()); invalidate(); } } /** * 关闭drawer,预留 * @param: * @return: void */ public void closeDrawer() { View menuView = mDrawerView; mHelper.smoothSlideViewTo(menuView, -menuView.getWidth(), menuView.getTop()); } /** * 打开drawer,预留 * @param: * @return: void */ public void openDrawer() { View menuView = mDrawerView; mHelper.smoothSlideViewTo(menuView, 0, menuView.getTop()); } /** * 关闭drawer,预留 <SUF>*/ public void closeSlideMenu() { View menuView = mMenuView; mSlideViewOnScreen = 1.0f; newLeft = getWidth(); mHelper.smoothSlideViewTo(menuView, getWidth(), menuView.getTop()); invalidate(); } /** * 打开drawer,预留 * @param: * @return: void */ public void openSlideMenu() { View menuView = mMenuView; mSlideViewOnScreen = 0.0f; newLeft = getWidth() - mMenuView.getWidth(); mHelper.smoothSlideViewTo(menuView, getWidth() - mMenuView.getWidth(), menuView.getTop()); invalidate(); } /** * 判断侧滑菜单是否打开 * @param: * @return: */ public boolean isSlideMenuOpen() { return mMenuView.getLeft() >= getWidth() - mMenuView.getWidth() && mMenuView.getLeft() < getWidth() - mMenuView.getWidth() / 2; } /** * 以下4个参数用来记录按下点的初始坐标和结束坐标 */ private float firstDownX = 0; private float lastDownX = 0; private float firstDownY = 0; private float lastDownY = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: firstDownX = event.getX(); firstDownY = event.getY(); lastDownX = event.getX(); lastDownY = event.getY(); break; case MotionEvent.ACTION_MOVE: lastDownX = event.getX(); lastDownY = event.getY(); break; case MotionEvent.ACTION_UP: lastDownX = event.getX(); lastDownY = event.getY(); float deltaX = Math.abs(lastDownX - firstDownX); float deltaY = Math.abs(lastDownY - firstDownY); if (deltaX < 10 && deltaY < 10) { if(isTouchCloseSlideArea(lastDownX, lastDownY)) { if(isSlideMenuOpen()){ closeSlideMenu(); return true; } } } break; } return false; } /** * 判断是否点击在了关闭侧边栏的区域 * @param: x 按下点x坐标 * @param: y 按下点y坐标 * @return: true:关闭 false:不关闭 */ private boolean isTouchCloseSlideArea(float x, float y) { int left = 0; int top = 0; int right = getWidth() - mMenuView.getWidth(); int bottom = mMenuView.getHeight(); if (x >= left && x <= right && y >= top && y <= bottom) { return true; } return false; } private void log(String msg) { if(isDebug) Log.e(TAG, "===================================> " + msg); } }
162837_9
package util.twitter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.regex.*; import java.util.Arrays; import java.util.List; import java.util.ArrayList; /** * Twokenize -- a tokenizer designed for Twitter text in English and some other European languages. * This is the Java version. If you want the old Python version, see: http://github.com/brendano/tweetmotif * * This tokenizer code has gone through a long history: * * (1) Brendan O'Connor wrote original version in Python, http://github.com/brendano/tweetmotif * TweetMotif: Exploratory Search and Topic Summarization for Twitter. * Brendan O'Connor, Michel Krieger, and David Ahn. * ICWSM-2010 (demo track), http://brenocon.com/oconnor_krieger_ahn.icwsm2010.tweetmotif.pdf * (2a) Kevin Gimpel and Daniel Mills modified it for POS tagging for the CMU ARK Twitter POS Tagger * (2b) Jason Baldridge and David Snyder ported it to Scala * (3) Brendan bugfixed the Scala port and merged with POS-specific changes * for the CMU ARK Twitter POS Tagger * (4) Tobi Owoputi ported it back to Java and added many improvements (2012-06) * * Current home is http://github.com/brendano/ark-tweet-nlp and http://www.ark.cs.cmu.edu/TweetNLP * * There have been at least 2 other Java ports, but they are not in the lineage for the code here. */ public class Twokenize { static Pattern Contractions = Pattern.compile("(?i)(\\w+)(n['’′]t|['’′]ve|['’′]ll|['’′]d|['’′]re|['’′]s|['’′]m)$"); static Pattern Whitespace = Pattern.compile("[\\s\\p{Zs}]+"); static String punctChars = "['\"“”‘’.?!…,:;]"; //static String punctSeq = punctChars+"+"; //'anthem'. => ' anthem '. static String punctSeq = "['\"“”‘’]+|[.?!,…]+|[:;]+"; //'anthem'. => ' anthem ' . static String entity = "&(?:amp|lt|gt|quot);"; // URLs // BTO 2012-06: everyone thinks the daringfireball regex should be better, but they're wrong. // If you actually empirically test it the results are bad. // Please see https://github.com/brendano/ark-tweet-nlp/pull/9 static String urlStart1 = "(?:https?://|\\bwww\\.)"; static String commonTLDs = "(?:com|org|edu|gov|net|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|pro|tel|travel|xxx)"; static String ccTLDs = "(?:ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|" + "bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|" + "er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|" + "hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|" + "lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|" + "nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|" + "sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|" + "va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)"; //TODO: remove obscure country domains? static String urlStart2 = "\\b(?:[A-Za-z\\d-])+(?:\\.[A-Za-z0-9]+){0,3}\\." + "(?:"+commonTLDs+"|"+ccTLDs+")"+"(?:\\."+ccTLDs+")?(?=\\W|$)"; static String urlBody = "(?:[^\\.\\s<>][^\\s<>]*?)?"; static String urlExtraCrapBeforeEnd = "(?:"+punctChars+"|"+entity+")+?"; static String urlEnd = "(?:\\.\\.+|[<>]|\\s|$)"; public static String url = "(?:"+urlStart1+"|"+urlStart2+")"+urlBody+"(?=(?:"+urlExtraCrapBeforeEnd+")?"+urlEnd+")"; // Numeric static String timeLike = "\\d+(?::\\d+){1,2}"; //static String numNum = "\\d+\\.\\d+"; static String numberWithCommas = "(?:(?<!\\d)\\d{1,3},)+?\\d{3}" + "(?=(?:[^,\\d]|$))"; static String numComb = "\\p{Sc}?\\d+(?:\\.\\d+)+%?"; // Abbreviations static String boundaryNotDot = "(?:$|\\s|[“\\u0022?!,:;]|" + entity + ")"; static String aa1 = "(?:[A-Za-z]\\.){2,}(?=" + boundaryNotDot + ")"; static String aa2 = "[^A-Za-z](?:[A-Za-z]\\.){1,}[A-Za-z](?=" + boundaryNotDot + ")"; static String standardAbbreviations = "\\b(?:[Mm]r|[Mm]rs|[Mm]s|[Dd]r|[Ss]r|[Jj]r|[Rr]ep|[Ss]en|[Ss]t)\\."; static String arbitraryAbbrev = "(?:" + aa1 +"|"+ aa2 + "|" + standardAbbreviations + ")"; static String separators = "(?:--+|―|—|~|–|=)"; static String decorations = "(?:[♫♪]+|[★☆]+|[♥❤♡]+|[\\u2639-\\u263b]+|[\\ue001-\\uebbb]+)"; static String thingsThatSplitWords = "[^\\s\\.,?\"]"; static String embeddedApostrophe = thingsThatSplitWords+"+['’′]" + thingsThatSplitWords + "*"; public static String OR(String... parts) { String prefix="(?:"; StringBuilder sb = new StringBuilder(); for (String s:parts){ sb.append(prefix); prefix="|"; sb.append(s); } sb.append(")"); return sb.toString(); } // Emoticons static String normalEyes = "(?iu)[:=]"; // 8 and x are eyes but cause problems static String wink = "[;]"; static String noseArea = "(?:|-|[^a-zA-Z0-9 ])"; // doesn't get :'-( static String happyMouths = "[D\\)\\]\\}]+"; static String sadMouths = "[\\(\\[\\{]+"; static String tongue = "[pPd3]+"; static String otherMouths = "(?:[oO]+|[/\\\\]+|[vV]+|[Ss]+|[|]+)"; // remove forward slash if http://'s aren't cleaned // mouth repetition examples: // @aliciakeys Put it in a love song :-)) // @hellocalyclops =))=))=)) Oh well static String bfLeft = "(♥|0|o|°|v|\\$|t|x|;|\\u0CA0|@|ʘ|•|・|◕|\\^|¬|\\*)"; static String bfCenter = "(?:[\\.]|[_-]+)"; static String bfRight = "\\2"; static String s3 = "(?:--['\"])"; static String s4 = "(?:<|&lt;|>|&gt;)[\\._-]+(?:<|&lt;|>|&gt;)"; static String s5 = "(?:[.][_]+[.])"; static String basicface = "(?:(?i)" +bfLeft+bfCenter+bfRight+ ")|" +s3+ "|" +s4+ "|" + s5; static String eeLeft = "[\\\\\ƪԄ\\((<>;ヽ\\-=~\\*]+"; static String eeRight= "[\\-=\\);'\\u0022<>ʃ)//ノノ丿╯σっµ~\\*]+"; static String eeSymbol = "[^A-Za-z0-9\\s\\(\\)\\*:=-]"; static String eastEmote = eeLeft + "(?:"+basicface+"|" +eeSymbol+")+" + eeRight; public static String emoticon = OR( // Standard version :) :( :] :D :P "(?:>|&gt;)?" + OR(normalEyes, wink) + OR(noseArea,"[Oo]") + OR(tongue+"(?=\\W|$|RT|rt|Rt)", otherMouths+"(?=\\W|$|RT|rt|Rt)", sadMouths, happyMouths), // reversed version (: D: use positive lookbehind to remove "(word):" // because eyes on the right side is more ambiguous with the standard usage of : ; "(?<=(?: |^))" + OR(sadMouths,happyMouths,otherMouths) + noseArea + OR(normalEyes, wink) + "(?:<|&lt;)?", //inspired by http://en.wikipedia.org/wiki/User:Scapler/emoticons#East_Asian_style eastEmote.replaceFirst("2", "1"), basicface // iOS 'emoji' characters (some smileys, some symbols) [\ue001-\uebbb] // TODO should try a big precompiled lexicon from Wikipedia, Dan Ramage told me (BTO) he does this ); static String Hearts = "(?:<+/?3+)+"; //the other hearts are in decorations static String Arrows = "(?:<*[-―—=]*>+|<+[-―—=]*>*)|\\p{InArrows}+"; // BTO 2011-06: restored Hashtag, AtMention protection (dropped in original scala port) because it fixes // "hello (#hashtag)" ==> "hello (#hashtag )" WRONG // "hello (#hashtag)" ==> "hello ( #hashtag )" RIGHT // "hello (@person)" ==> "hello (@person )" WRONG // "hello (@person)" ==> "hello ( @person )" RIGHT // ... Some sort of weird interaction with edgepunct I guess, because edgepunct // has poor content-symbol detection. // This also gets #1 #40 which probably aren't hashtags .. but good as tokens. // If you want good hashtag identification, use a different regex. static String Hashtag = "#[a-zA-Z0-9_]+"; //optional: lookbehind for \b //optional: lookbehind for \b, max length 15 static String AtMention = "[@@][a-zA-Z0-9_]+"; // I was worried this would conflict with at-mentions // but seems ok in sample of 5800: 7 changes all email fixes // http://www.regular-expressions.info/email.html static String Bound = "(?:\\W|^|$)"; public static String Email = "(?<=" +Bound+ ")[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}(?=" +Bound+")"; // We will be tokenizing using these regexps as delimiters // Additionally, these things are "protected", meaning they shouldn't be further split themselves. static Pattern Protected = Pattern.compile( OR( Hearts, url, Email, timeLike, //numNum, numberWithCommas, numComb, emoticon, Arrows, entity, punctSeq, arbitraryAbbrev, separators, decorations, embeddedApostrophe, Hashtag, AtMention )); // Edge punctuation // Want: 'foo' => ' foo ' // While also: don't => don't // the first is considered "edge punctuation". // the second is word-internal punctuation -- don't want to mess with it. // BTO (2011-06): the edgepunct system seems to be the #1 source of problems these days. // I remember it causing lots of trouble in the past as well. Would be good to revisit or eliminate. // Note the 'smart quotes' (http://en.wikipedia.org/wiki/Smart_quotes) static String edgePunctChars = "'\"“”‘’«»{}\\(\\)\\[\\]\\*&"; //add \\p{So}? (symbols) static String edgePunct = "[" + edgePunctChars + "]"; static String notEdgePunct = "[a-zA-Z0-9]"; // content characters static String offEdge = "(^|$|:|;|\\s|\\.|,)"; // colon here gets "(hello):" ==> "( hello ):" static Pattern EdgePunctLeft = Pattern.compile(offEdge + "("+edgePunct+"+)("+notEdgePunct+")"); static Pattern EdgePunctRight = Pattern.compile("("+notEdgePunct+")("+edgePunct+"+)" + offEdge); public static String splitEdgePunct (String input) { Matcher m1 = EdgePunctLeft.matcher(input); input = m1.replaceAll("$1$2 $3"); m1 = EdgePunctRight.matcher(input); input = m1.replaceAll("$1 $2$3"); return input; } private static class Pair<T1, T2> { public T1 first; public T2 second; public Pair(T1 x, T2 y) { first=x; second=y; } } // The main work of tokenizing a tweet. private static List<String> simpleTokenize (String text) { // Do the no-brainers first String splitPunctText = splitEdgePunct(text); int textLength = splitPunctText.length(); // BTO: the logic here got quite convoluted via the Scala porting detour // It would be good to switch back to a nice simple procedural style like in the Python version // ... Scala is such a pain. Never again. // Find the matches for subsequences that should be protected, // e.g. URLs, 1.0, U.N.K.L.E., 12:53 Matcher matches = Protected.matcher(splitPunctText); //Storing as List[List[String]] to make zip easier later on List<List<String>> bads = new ArrayList<List<String>>(); //linked list? List<Pair<Integer,Integer>> badSpans = new ArrayList<Pair<Integer,Integer>>(); while(matches.find()){ // The spans of the "bads" should not be split. if (matches.start() != matches.end()){ //unnecessary? List<String> bad = new ArrayList<String>(1); bad.add(splitPunctText.substring(matches.start(),matches.end())); bads.add(bad); badSpans.add(new Pair<Integer, Integer>(matches.start(),matches.end())); } } // Create a list of indices to create the "goods", which can be // split. We are taking "bad" spans like // List((2,5), (8,10)) // to create /// List(0, 2, 5, 8, 10, 12) // where, e.g., "12" here would be the textLength // has an even length and no indices are the same List<Integer> indices = new ArrayList<Integer>(2+2*badSpans.size()); indices.add(0); for(Pair<Integer,Integer> p:badSpans){ indices.add(p.first); indices.add(p.second); } indices.add(textLength); // Group the indices and map them to their respective portion of the string List<List<String>> splitGoods = new ArrayList<List<String>>(indices.size()/2); for (int i=0; i<indices.size(); i+=2) { String goodstr = splitPunctText.substring(indices.get(i),indices.get(i+1)); List<String> splitstr = Arrays.asList(goodstr.trim().split(" ")); splitGoods.add(splitstr); } // Reinterpolate the 'good' and 'bad' Lists, ensuring that // additonal tokens from last good item get included List<String> zippedStr= new ArrayList<String>(); int i; for(i=0; i < bads.size(); i++) { zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); zippedStr = addAllnonempty(zippedStr,bads.get(i)); } zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); // BTO: our POS tagger wants "ur" and "you're" to both be one token. // Uncomment to get "you 're" /*ArrayList<String> splitStr = new ArrayList<String>(zippedStr.size()); for(String tok:zippedStr) splitStr.addAll(splitToken(tok)); zippedStr=splitStr;*/ return zippedStr; } private static List<String> addAllnonempty(List<String> master, List<String> smaller){ for (String s : smaller){ String strim = s.trim(); if (strim.length() > 0) master.add(strim); } return master; } /** "foo bar " => "foo bar" */ public static String squeezeWhitespace (String input){ return Whitespace.matcher(input).replaceAll(" ").trim(); } // Final pass tokenization based on special patterns private static List<String> splitToken (String token) { Matcher m = Contractions.matcher(token); if (m.find()){ String[] contract = {m.group(1), m.group(2)}; return Arrays.asList(contract); } String[] contract = {token}; return Arrays.asList(contract); } /** Assume 'text' has no HTML escaping. **/ public static List<String> tokenize(String text){ return simpleTokenize(squeezeWhitespace(text)); } }
wlin12/JNN
src/util/twitter/Twokenize.java
5,425
// doesn't get :'-(
line_comment
nl
package util.twitter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.regex.*; import java.util.Arrays; import java.util.List; import java.util.ArrayList; /** * Twokenize -- a tokenizer designed for Twitter text in English and some other European languages. * This is the Java version. If you want the old Python version, see: http://github.com/brendano/tweetmotif * * This tokenizer code has gone through a long history: * * (1) Brendan O'Connor wrote original version in Python, http://github.com/brendano/tweetmotif * TweetMotif: Exploratory Search and Topic Summarization for Twitter. * Brendan O'Connor, Michel Krieger, and David Ahn. * ICWSM-2010 (demo track), http://brenocon.com/oconnor_krieger_ahn.icwsm2010.tweetmotif.pdf * (2a) Kevin Gimpel and Daniel Mills modified it for POS tagging for the CMU ARK Twitter POS Tagger * (2b) Jason Baldridge and David Snyder ported it to Scala * (3) Brendan bugfixed the Scala port and merged with POS-specific changes * for the CMU ARK Twitter POS Tagger * (4) Tobi Owoputi ported it back to Java and added many improvements (2012-06) * * Current home is http://github.com/brendano/ark-tweet-nlp and http://www.ark.cs.cmu.edu/TweetNLP * * There have been at least 2 other Java ports, but they are not in the lineage for the code here. */ public class Twokenize { static Pattern Contractions = Pattern.compile("(?i)(\\w+)(n['’′]t|['’′]ve|['’′]ll|['’′]d|['’′]re|['’′]s|['’′]m)$"); static Pattern Whitespace = Pattern.compile("[\\s\\p{Zs}]+"); static String punctChars = "['\"“”‘’.?!…,:;]"; //static String punctSeq = punctChars+"+"; //'anthem'. => ' anthem '. static String punctSeq = "['\"“”‘’]+|[.?!,…]+|[:;]+"; //'anthem'. => ' anthem ' . static String entity = "&(?:amp|lt|gt|quot);"; // URLs // BTO 2012-06: everyone thinks the daringfireball regex should be better, but they're wrong. // If you actually empirically test it the results are bad. // Please see https://github.com/brendano/ark-tweet-nlp/pull/9 static String urlStart1 = "(?:https?://|\\bwww\\.)"; static String commonTLDs = "(?:com|org|edu|gov|net|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|pro|tel|travel|xxx)"; static String ccTLDs = "(?:ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|" + "bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|" + "er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|" + "hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|" + "lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|" + "nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|" + "sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|" + "va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)"; //TODO: remove obscure country domains? static String urlStart2 = "\\b(?:[A-Za-z\\d-])+(?:\\.[A-Za-z0-9]+){0,3}\\." + "(?:"+commonTLDs+"|"+ccTLDs+")"+"(?:\\."+ccTLDs+")?(?=\\W|$)"; static String urlBody = "(?:[^\\.\\s<>][^\\s<>]*?)?"; static String urlExtraCrapBeforeEnd = "(?:"+punctChars+"|"+entity+")+?"; static String urlEnd = "(?:\\.\\.+|[<>]|\\s|$)"; public static String url = "(?:"+urlStart1+"|"+urlStart2+")"+urlBody+"(?=(?:"+urlExtraCrapBeforeEnd+")?"+urlEnd+")"; // Numeric static String timeLike = "\\d+(?::\\d+){1,2}"; //static String numNum = "\\d+\\.\\d+"; static String numberWithCommas = "(?:(?<!\\d)\\d{1,3},)+?\\d{3}" + "(?=(?:[^,\\d]|$))"; static String numComb = "\\p{Sc}?\\d+(?:\\.\\d+)+%?"; // Abbreviations static String boundaryNotDot = "(?:$|\\s|[“\\u0022?!,:;]|" + entity + ")"; static String aa1 = "(?:[A-Za-z]\\.){2,}(?=" + boundaryNotDot + ")"; static String aa2 = "[^A-Za-z](?:[A-Za-z]\\.){1,}[A-Za-z](?=" + boundaryNotDot + ")"; static String standardAbbreviations = "\\b(?:[Mm]r|[Mm]rs|[Mm]s|[Dd]r|[Ss]r|[Jj]r|[Rr]ep|[Ss]en|[Ss]t)\\."; static String arbitraryAbbrev = "(?:" + aa1 +"|"+ aa2 + "|" + standardAbbreviations + ")"; static String separators = "(?:--+|―|—|~|–|=)"; static String decorations = "(?:[♫♪]+|[★☆]+|[♥❤♡]+|[\\u2639-\\u263b]+|[\\ue001-\\uebbb]+)"; static String thingsThatSplitWords = "[^\\s\\.,?\"]"; static String embeddedApostrophe = thingsThatSplitWords+"+['’′]" + thingsThatSplitWords + "*"; public static String OR(String... parts) { String prefix="(?:"; StringBuilder sb = new StringBuilder(); for (String s:parts){ sb.append(prefix); prefix="|"; sb.append(s); } sb.append(")"); return sb.toString(); } // Emoticons static String normalEyes = "(?iu)[:=]"; // 8 and x are eyes but cause problems static String wink = "[;]"; static String noseArea = "(?:|-|[^a-zA-Z0-9 ])"; // doesn't get<SUF> static String happyMouths = "[D\\)\\]\\}]+"; static String sadMouths = "[\\(\\[\\{]+"; static String tongue = "[pPd3]+"; static String otherMouths = "(?:[oO]+|[/\\\\]+|[vV]+|[Ss]+|[|]+)"; // remove forward slash if http://'s aren't cleaned // mouth repetition examples: // @aliciakeys Put it in a love song :-)) // @hellocalyclops =))=))=)) Oh well static String bfLeft = "(♥|0|o|°|v|\\$|t|x|;|\\u0CA0|@|ʘ|•|・|◕|\\^|¬|\\*)"; static String bfCenter = "(?:[\\.]|[_-]+)"; static String bfRight = "\\2"; static String s3 = "(?:--['\"])"; static String s4 = "(?:<|&lt;|>|&gt;)[\\._-]+(?:<|&lt;|>|&gt;)"; static String s5 = "(?:[.][_]+[.])"; static String basicface = "(?:(?i)" +bfLeft+bfCenter+bfRight+ ")|" +s3+ "|" +s4+ "|" + s5; static String eeLeft = "[\\\\\ƪԄ\\((<>;ヽ\\-=~\\*]+"; static String eeRight= "[\\-=\\);'\\u0022<>ʃ)//ノノ丿╯σっµ~\\*]+"; static String eeSymbol = "[^A-Za-z0-9\\s\\(\\)\\*:=-]"; static String eastEmote = eeLeft + "(?:"+basicface+"|" +eeSymbol+")+" + eeRight; public static String emoticon = OR( // Standard version :) :( :] :D :P "(?:>|&gt;)?" + OR(normalEyes, wink) + OR(noseArea,"[Oo]") + OR(tongue+"(?=\\W|$|RT|rt|Rt)", otherMouths+"(?=\\W|$|RT|rt|Rt)", sadMouths, happyMouths), // reversed version (: D: use positive lookbehind to remove "(word):" // because eyes on the right side is more ambiguous with the standard usage of : ; "(?<=(?: |^))" + OR(sadMouths,happyMouths,otherMouths) + noseArea + OR(normalEyes, wink) + "(?:<|&lt;)?", //inspired by http://en.wikipedia.org/wiki/User:Scapler/emoticons#East_Asian_style eastEmote.replaceFirst("2", "1"), basicface // iOS 'emoji' characters (some smileys, some symbols) [\ue001-\uebbb] // TODO should try a big precompiled lexicon from Wikipedia, Dan Ramage told me (BTO) he does this ); static String Hearts = "(?:<+/?3+)+"; //the other hearts are in decorations static String Arrows = "(?:<*[-―—=]*>+|<+[-―—=]*>*)|\\p{InArrows}+"; // BTO 2011-06: restored Hashtag, AtMention protection (dropped in original scala port) because it fixes // "hello (#hashtag)" ==> "hello (#hashtag )" WRONG // "hello (#hashtag)" ==> "hello ( #hashtag )" RIGHT // "hello (@person)" ==> "hello (@person )" WRONG // "hello (@person)" ==> "hello ( @person )" RIGHT // ... Some sort of weird interaction with edgepunct I guess, because edgepunct // has poor content-symbol detection. // This also gets #1 #40 which probably aren't hashtags .. but good as tokens. // If you want good hashtag identification, use a different regex. static String Hashtag = "#[a-zA-Z0-9_]+"; //optional: lookbehind for \b //optional: lookbehind for \b, max length 15 static String AtMention = "[@@][a-zA-Z0-9_]+"; // I was worried this would conflict with at-mentions // but seems ok in sample of 5800: 7 changes all email fixes // http://www.regular-expressions.info/email.html static String Bound = "(?:\\W|^|$)"; public static String Email = "(?<=" +Bound+ ")[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}(?=" +Bound+")"; // We will be tokenizing using these regexps as delimiters // Additionally, these things are "protected", meaning they shouldn't be further split themselves. static Pattern Protected = Pattern.compile( OR( Hearts, url, Email, timeLike, //numNum, numberWithCommas, numComb, emoticon, Arrows, entity, punctSeq, arbitraryAbbrev, separators, decorations, embeddedApostrophe, Hashtag, AtMention )); // Edge punctuation // Want: 'foo' => ' foo ' // While also: don't => don't // the first is considered "edge punctuation". // the second is word-internal punctuation -- don't want to mess with it. // BTO (2011-06): the edgepunct system seems to be the #1 source of problems these days. // I remember it causing lots of trouble in the past as well. Would be good to revisit or eliminate. // Note the 'smart quotes' (http://en.wikipedia.org/wiki/Smart_quotes) static String edgePunctChars = "'\"“”‘’«»{}\\(\\)\\[\\]\\*&"; //add \\p{So}? (symbols) static String edgePunct = "[" + edgePunctChars + "]"; static String notEdgePunct = "[a-zA-Z0-9]"; // content characters static String offEdge = "(^|$|:|;|\\s|\\.|,)"; // colon here gets "(hello):" ==> "( hello ):" static Pattern EdgePunctLeft = Pattern.compile(offEdge + "("+edgePunct+"+)("+notEdgePunct+")"); static Pattern EdgePunctRight = Pattern.compile("("+notEdgePunct+")("+edgePunct+"+)" + offEdge); public static String splitEdgePunct (String input) { Matcher m1 = EdgePunctLeft.matcher(input); input = m1.replaceAll("$1$2 $3"); m1 = EdgePunctRight.matcher(input); input = m1.replaceAll("$1 $2$3"); return input; } private static class Pair<T1, T2> { public T1 first; public T2 second; public Pair(T1 x, T2 y) { first=x; second=y; } } // The main work of tokenizing a tweet. private static List<String> simpleTokenize (String text) { // Do the no-brainers first String splitPunctText = splitEdgePunct(text); int textLength = splitPunctText.length(); // BTO: the logic here got quite convoluted via the Scala porting detour // It would be good to switch back to a nice simple procedural style like in the Python version // ... Scala is such a pain. Never again. // Find the matches for subsequences that should be protected, // e.g. URLs, 1.0, U.N.K.L.E., 12:53 Matcher matches = Protected.matcher(splitPunctText); //Storing as List[List[String]] to make zip easier later on List<List<String>> bads = new ArrayList<List<String>>(); //linked list? List<Pair<Integer,Integer>> badSpans = new ArrayList<Pair<Integer,Integer>>(); while(matches.find()){ // The spans of the "bads" should not be split. if (matches.start() != matches.end()){ //unnecessary? List<String> bad = new ArrayList<String>(1); bad.add(splitPunctText.substring(matches.start(),matches.end())); bads.add(bad); badSpans.add(new Pair<Integer, Integer>(matches.start(),matches.end())); } } // Create a list of indices to create the "goods", which can be // split. We are taking "bad" spans like // List((2,5), (8,10)) // to create /// List(0, 2, 5, 8, 10, 12) // where, e.g., "12" here would be the textLength // has an even length and no indices are the same List<Integer> indices = new ArrayList<Integer>(2+2*badSpans.size()); indices.add(0); for(Pair<Integer,Integer> p:badSpans){ indices.add(p.first); indices.add(p.second); } indices.add(textLength); // Group the indices and map them to their respective portion of the string List<List<String>> splitGoods = new ArrayList<List<String>>(indices.size()/2); for (int i=0; i<indices.size(); i+=2) { String goodstr = splitPunctText.substring(indices.get(i),indices.get(i+1)); List<String> splitstr = Arrays.asList(goodstr.trim().split(" ")); splitGoods.add(splitstr); } // Reinterpolate the 'good' and 'bad' Lists, ensuring that // additonal tokens from last good item get included List<String> zippedStr= new ArrayList<String>(); int i; for(i=0; i < bads.size(); i++) { zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); zippedStr = addAllnonempty(zippedStr,bads.get(i)); } zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); // BTO: our POS tagger wants "ur" and "you're" to both be one token. // Uncomment to get "you 're" /*ArrayList<String> splitStr = new ArrayList<String>(zippedStr.size()); for(String tok:zippedStr) splitStr.addAll(splitToken(tok)); zippedStr=splitStr;*/ return zippedStr; } private static List<String> addAllnonempty(List<String> master, List<String> smaller){ for (String s : smaller){ String strim = s.trim(); if (strim.length() > 0) master.add(strim); } return master; } /** "foo bar " => "foo bar" */ public static String squeezeWhitespace (String input){ return Whitespace.matcher(input).replaceAll(" ").trim(); } // Final pass tokenization based on special patterns private static List<String> splitToken (String token) { Matcher m = Contractions.matcher(token); if (m.find()){ String[] contract = {m.group(1), m.group(2)}; return Arrays.asList(contract); } String[] contract = {token}; return Arrays.asList(contract); } /** Assume 'text' has no HTML escaping. **/ public static List<String> tokenize(String text){ return simpleTokenize(squeezeWhitespace(text)); } }
104717_0
package GUI; import Auxiliary.*; import Items.*; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.Set; import java.util.HashSet; import core.*; /** * @note Opgemerkte fouten : * - in IFacade : in vorige versie moest getMinimalCostToReach() (double) -2 returene als de positie niet bereikbaar was door gebrek aan energie van de * robot en (double) -1 als de positie niet bereikbaar was omwille van obstacles. De implementatie van deze Facade gooit -1 in beide gevallen. RoboRally houdt * nog altijd rekening met zowel -1 als -2, echter. * - in RoboRally : lijnen 412 en 414 stond er words[2], wat een ArrayOutOfBoundsException opgooiden omwille van het feit dat er maar 2 Objecten waren in words[] */ public class Facade implements IFacade<Board, Robot, Wall, Battery, RepairKit, SurpriseBox> { @Override public Board createBoard(long width, long height) { try{ Board board = new Board(width, height); return board; } catch(IllegalArgumentException err) { System.err.println(err.getMessage()); return null; } } @Override public void merge(Board board1, Board board2) { try { //board2 is terminated after merge(). merge(board1,board2); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } /** * @note Since all aspects related to the weight of an item must be worked out in a total way, negative weight-inputs are accepted * as given parameters. (contrary to what's stated in the documentation of IFacade, see assignment RoboRally (part 3) & documentation IFacade) */ @Override public Battery createBattery(double initialEnergy, int weight) { EnergyAmount initialEnergyAmount = new EnergyAmount(initialEnergy, EnergyUnit.WATTSECOND); if((initialEnergy < 0) || (initialEnergyAmount.compareTo(Battery.getStandardCapacity()) == 1)) {System.err.println("Invalid initial energy given!"); return null; } Battery battery = new Battery(initialEnergyAmount, weight); return battery; } @Override public void putBattery(Board board, long x, long y, Battery battery) { assert (board != null) ; try{ board.putEntity(Position.returnUniquePosition(x, y),battery); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage()); } } @Override public long getBatteryX(Battery battery) throws IllegalStateException { if(battery.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return battery.getPosition().getX(); } @Override public long getBatteryY(Battery battery) throws IllegalStateException { if(battery.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return battery.getPosition().getY(); } @Override public RepairKit createRepairKit(double repairAmount, int weight) { EnergyAmount initialEnergyAmount = new EnergyAmount(repairAmount, EnergyUnit.WATTSECOND); if(repairAmount < 0) {System.err.println("Invalid repair amount given!"); return null; } RepairKit repairKit = new RepairKit(initialEnergyAmount, weight); return repairKit; } @Override public void putRepairKit(Board board, long x, long y, RepairKit repairKit){ assert (board != null) ; try{ board.putEntity(Position.returnUniquePosition(x, y),repairKit); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage()); } } @Override public long getRepairKitX(RepairKit repairKit) throws IllegalStateException{ if(repairKit.getPosition() == null) throw new IllegalStateException("Repair kit is not placed on a board."); return repairKit.getPosition().getX(); } @Override public long getRepairKitY(RepairKit repairKit) throws IllegalStateException{ if(repairKit.getPosition() == null) throw new IllegalStateException("Repair kit is not placed on a board."); return repairKit.getPosition().getY(); } /** * @note Since all aspects related to the weight of an item must be worked out in a total way, negative weight-inputs are accepted * as given parameters. (contrary to what's stated in the documentation of IFacade, see assignment RoboRally (part 3) & documentation IFacade) */ @Override public SurpriseBox createSurpriseBox(int weight){ return new SurpriseBox(weight); } @Override public void putSurpriseBox(Board board, long x, long y, SurpriseBox surpriseBox){ assert (board != null) ; try{ board.putEntity(Position.returnUniquePosition(x, y),surpriseBox); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage()); } } @Override public long getSurpriseBoxX(SurpriseBox surpriseBox) throws IllegalStateException { if(surpriseBox.getPosition() == null) throw new IllegalStateException("Surprisebox is not placed on a board."); return surpriseBox.getPosition().getX(); } @Override public long getSurpriseBoxY(SurpriseBox surpriseBox) throws IllegalStateException { if(surpriseBox.getPosition() == null) throw new IllegalStateException("Surprisebox is not placed on a board."); return surpriseBox.getPosition().getY(); } @Override public Robot createRobot(int orientation, double initialEnergy) { EnergyAmount initialEnergyAmount = new EnergyAmount(initialEnergy, EnergyUnit.WATTSECOND); if(!(initialEnergy > 0) || (initialEnergyAmount.compareTo(Robot.getMaxCapacity()) == 1)) {System.err.println("Invalid initial energy given!"); return null; } Robot robot = new Robot(Orientation.getOrientation(orientation), initialEnergyAmount); return robot; } @Override public void putRobot(Board board, long x, long y, Robot robot) { assert (board != null) ; try { board.putEntity(Position.returnUniquePosition(x, y),robot); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public long getRobotX(Robot robot) throws IllegalStateException { if(robot.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return robot.getPosition().getX(); } @Override public long getRobotY(Robot robot) throws IllegalStateException { if(robot.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return robot.getPosition().getY(); } @Override public int getOrientation(Robot robot) { return robot.getOrientation().getIntOrientation(); } @Override public double getEnergy(Robot robot) { return robot.getEnergy().getAmountInSpecifiedUnit(EnergyUnit.WATTSECOND); } @Override public void move(Robot robot) { if(robot.getEnergy().compareTo(robot.getEnergyToMove()) == -1) { System.err.println("Insufficient energy to move!"); } else { try{ robot.move(); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } } @Override public void turn(Robot robot) { if(robot.getEnergy().compareTo(Robot.getEnergyToTurn()) == -1) System.err.println("Insufficient energy-amount to turn!"); else robot.turnClockwise(); } @Override public void pickUpBattery(Robot robot, Battery battery) { try { robot.pickUp(battery); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } @Override public void useBattery(Robot robot, Battery battery) { try{ robot.use(battery); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public void dropBattery(Robot robot, Battery battery) { try{ robot.dropItem(battery); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void pickUpRepairKit(Robot robot, RepairKit repairKit) { try { robot.pickUp(repairKit); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } @Override public void useRepairKit(Robot robot, RepairKit repairKit) { try{ robot.use(repairKit); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public void dropRepairKit(Robot robot, RepairKit repairKit) { try{ robot.dropItem(repairKit); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void pickUpSurpriseBox(Robot robot, SurpriseBox surpriseBox) { try { robot.pickUp(surpriseBox); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } @Override public void useSurpriseBox(Robot robot, SurpriseBox surpriseBox) { try{ robot.use(surpriseBox); } catch(NullPointerException exc) {System.err.println(exc.getMessage()); } //Following exceptions should never occur. catch(IllegalArgumentException exc) {assert false;} catch(IllegalStateException exc) {assert false;} } @Override public void dropSurpriseBox(Robot robot, SurpriseBox surpriseBox) { try{ robot.dropItem(surpriseBox); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void transferItems(Robot from, Robot to) { try { from.transferItems(to); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public int isMinimalCostToReach17Plus() { return 1; } @Override public double getMinimalCostToReach(Robot robot, long x, long y) { Position position = Position.returnUniquePosition(x,y); try { return robot.getEnergyRequiredToReach(position).getAmountInSpecifiedUnit(EnergyUnit.WATTSECOND); } catch(IllegalStateException exc) { return Double.parseDouble(exc.getMessage()); } catch(IllegalArgumentException exc) { System.err.println(exc.getMessage()); return -1; } } @Override public int isMoveNextTo18Plus() { return 1; } @Override public void moveNextTo(Robot robot, Robot other) { try{ Robot.moveNextTo(robot,other); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void shoot(Robot robot) throws UnsupportedOperationException { if(robot.getEnergy().compareTo(Robot.getEnergyToShoot()) == -1) System.err.println("Insufficient energy to shoot."); else { try { robot.shoot(); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} } } @Override public Wall createWall() throws UnsupportedOperationException { return new Wall(); } @Override public void putWall(Board board, long x, long y, Wall wall) throws UnsupportedOperationException { //assuming "wall" was meant instead of robot in the documentation of IFacade ;-) assert board != null; try{ board.putEntity(Position.returnUniquePosition(x, y), wall); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public long getWallX(Wall wall) throws IllegalStateException, UnsupportedOperationException { if(wall.getBoard() == null) throw new IllegalStateException("This wall is not placed on a board!"); else { return wall.getPosition().getX(); } } @Override public long getWallY(Wall wall) throws IllegalStateException, UnsupportedOperationException { if(wall.getBoard() == null) throw new IllegalStateException("This wall is not placed on a board!"); else { return wall.getPosition().getY(); } } @Override public Set<Robot> getRobots(Board board) { assert board != null; HashSet<Robot> robots = new HashSet<Robot>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(Robot.class)) robots.add((Robot) entity); return robots; } @Override public Set<Wall> getWalls(Board board) throws UnsupportedOperationException { assert board != null; HashSet<Wall> walls = new HashSet<Wall>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(Wall.class)) walls.add((Wall) entity); return walls; } @Override public Set<RepairKit> getRepairKits(Board board) { assert board != null; HashSet<RepairKit> repairKits = new HashSet<RepairKit>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(RepairKit.class)) repairKits.add((RepairKit) entity); return repairKits; } @Override public Set<SurpriseBox> getSurpriseBoxes(Board board) { assert board != null; HashSet<SurpriseBox> surpriseBoxes = new HashSet<SurpriseBox>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(SurpriseBox.class)) surpriseBoxes.add((SurpriseBox) entity); return surpriseBoxes; } @Override public Set<Battery> getBatteries(Board board) { assert board != null; HashSet<Battery> batteries = new HashSet<Battery>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(Battery.class)) batteries.add((Battery) entity); return batteries; } @Override public int loadProgramFromFile(Robot robot, String path) { try { robot.addProgram(path); return 0; } catch(FileNotFoundException exc) { return - 42 ; } } @Override public int saveProgramToFile(Robot robot, String path) { try{ FileWriter f = new FileWriter(path); PrintWriter w = new PrintWriter(f); w.println(robot.getProgram().toString()); w.close(); return 0; } catch(Exception exc){return (int) - Math.PI;} } @Override public void prettyPrintProgram(Robot robot, Writer writer) { try { writer.write(robot.getProgram().toString()); writer.flush(); } catch(IOException exc) {System.err.println(exc.getMessage());} } @Override public void stepn(Robot robot, int n) { try { robot.executeNSteps(n); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } }
wmclt/Project2ndBachelor
src/GUI/Facade.java
5,080
/** * @note Opgemerkte fouten : * - in IFacade : in vorige versie moest getMinimalCostToReach() (double) -2 returene als de positie niet bereikbaar was door gebrek aan energie van de * robot en (double) -1 als de positie niet bereikbaar was omwille van obstacles. De implementatie van deze Facade gooit -1 in beide gevallen. RoboRally houdt * nog altijd rekening met zowel -1 als -2, echter. * - in RoboRally : lijnen 412 en 414 stond er words[2], wat een ArrayOutOfBoundsException opgooiden omwille van het feit dat er maar 2 Objecten waren in words[] */
block_comment
nl
package GUI; import Auxiliary.*; import Items.*; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.Set; import java.util.HashSet; import core.*; /** * @note Opgemerkte<SUF>*/ public class Facade implements IFacade<Board, Robot, Wall, Battery, RepairKit, SurpriseBox> { @Override public Board createBoard(long width, long height) { try{ Board board = new Board(width, height); return board; } catch(IllegalArgumentException err) { System.err.println(err.getMessage()); return null; } } @Override public void merge(Board board1, Board board2) { try { //board2 is terminated after merge(). merge(board1,board2); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } /** * @note Since all aspects related to the weight of an item must be worked out in a total way, negative weight-inputs are accepted * as given parameters. (contrary to what's stated in the documentation of IFacade, see assignment RoboRally (part 3) & documentation IFacade) */ @Override public Battery createBattery(double initialEnergy, int weight) { EnergyAmount initialEnergyAmount = new EnergyAmount(initialEnergy, EnergyUnit.WATTSECOND); if((initialEnergy < 0) || (initialEnergyAmount.compareTo(Battery.getStandardCapacity()) == 1)) {System.err.println("Invalid initial energy given!"); return null; } Battery battery = new Battery(initialEnergyAmount, weight); return battery; } @Override public void putBattery(Board board, long x, long y, Battery battery) { assert (board != null) ; try{ board.putEntity(Position.returnUniquePosition(x, y),battery); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage()); } } @Override public long getBatteryX(Battery battery) throws IllegalStateException { if(battery.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return battery.getPosition().getX(); } @Override public long getBatteryY(Battery battery) throws IllegalStateException { if(battery.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return battery.getPosition().getY(); } @Override public RepairKit createRepairKit(double repairAmount, int weight) { EnergyAmount initialEnergyAmount = new EnergyAmount(repairAmount, EnergyUnit.WATTSECOND); if(repairAmount < 0) {System.err.println("Invalid repair amount given!"); return null; } RepairKit repairKit = new RepairKit(initialEnergyAmount, weight); return repairKit; } @Override public void putRepairKit(Board board, long x, long y, RepairKit repairKit){ assert (board != null) ; try{ board.putEntity(Position.returnUniquePosition(x, y),repairKit); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage()); } } @Override public long getRepairKitX(RepairKit repairKit) throws IllegalStateException{ if(repairKit.getPosition() == null) throw new IllegalStateException("Repair kit is not placed on a board."); return repairKit.getPosition().getX(); } @Override public long getRepairKitY(RepairKit repairKit) throws IllegalStateException{ if(repairKit.getPosition() == null) throw new IllegalStateException("Repair kit is not placed on a board."); return repairKit.getPosition().getY(); } /** * @note Since all aspects related to the weight of an item must be worked out in a total way, negative weight-inputs are accepted * as given parameters. (contrary to what's stated in the documentation of IFacade, see assignment RoboRally (part 3) & documentation IFacade) */ @Override public SurpriseBox createSurpriseBox(int weight){ return new SurpriseBox(weight); } @Override public void putSurpriseBox(Board board, long x, long y, SurpriseBox surpriseBox){ assert (board != null) ; try{ board.putEntity(Position.returnUniquePosition(x, y),surpriseBox); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage()); } } @Override public long getSurpriseBoxX(SurpriseBox surpriseBox) throws IllegalStateException { if(surpriseBox.getPosition() == null) throw new IllegalStateException("Surprisebox is not placed on a board."); return surpriseBox.getPosition().getX(); } @Override public long getSurpriseBoxY(SurpriseBox surpriseBox) throws IllegalStateException { if(surpriseBox.getPosition() == null) throw new IllegalStateException("Surprisebox is not placed on a board."); return surpriseBox.getPosition().getY(); } @Override public Robot createRobot(int orientation, double initialEnergy) { EnergyAmount initialEnergyAmount = new EnergyAmount(initialEnergy, EnergyUnit.WATTSECOND); if(!(initialEnergy > 0) || (initialEnergyAmount.compareTo(Robot.getMaxCapacity()) == 1)) {System.err.println("Invalid initial energy given!"); return null; } Robot robot = new Robot(Orientation.getOrientation(orientation), initialEnergyAmount); return robot; } @Override public void putRobot(Board board, long x, long y, Robot robot) { assert (board != null) ; try { board.putEntity(Position.returnUniquePosition(x, y),robot); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public long getRobotX(Robot robot) throws IllegalStateException { if(robot.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return robot.getPosition().getX(); } @Override public long getRobotY(Robot robot) throws IllegalStateException { if(robot.getPosition() == null) throw new IllegalStateException("Battery is not placed on a board."); return robot.getPosition().getY(); } @Override public int getOrientation(Robot robot) { return robot.getOrientation().getIntOrientation(); } @Override public double getEnergy(Robot robot) { return robot.getEnergy().getAmountInSpecifiedUnit(EnergyUnit.WATTSECOND); } @Override public void move(Robot robot) { if(robot.getEnergy().compareTo(robot.getEnergyToMove()) == -1) { System.err.println("Insufficient energy to move!"); } else { try{ robot.move(); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } } @Override public void turn(Robot robot) { if(robot.getEnergy().compareTo(Robot.getEnergyToTurn()) == -1) System.err.println("Insufficient energy-amount to turn!"); else robot.turnClockwise(); } @Override public void pickUpBattery(Robot robot, Battery battery) { try { robot.pickUp(battery); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } @Override public void useBattery(Robot robot, Battery battery) { try{ robot.use(battery); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public void dropBattery(Robot robot, Battery battery) { try{ robot.dropItem(battery); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void pickUpRepairKit(Robot robot, RepairKit repairKit) { try { robot.pickUp(repairKit); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } @Override public void useRepairKit(Robot robot, RepairKit repairKit) { try{ robot.use(repairKit); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public void dropRepairKit(Robot robot, RepairKit repairKit) { try{ robot.dropItem(repairKit); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void pickUpSurpriseBox(Robot robot, SurpriseBox surpriseBox) { try { robot.pickUp(surpriseBox); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } @Override public void useSurpriseBox(Robot robot, SurpriseBox surpriseBox) { try{ robot.use(surpriseBox); } catch(NullPointerException exc) {System.err.println(exc.getMessage()); } //Following exceptions should never occur. catch(IllegalArgumentException exc) {assert false;} catch(IllegalStateException exc) {assert false;} } @Override public void dropSurpriseBox(Robot robot, SurpriseBox surpriseBox) { try{ robot.dropItem(surpriseBox); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void transferItems(Robot from, Robot to) { try { from.transferItems(to); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public int isMinimalCostToReach17Plus() { return 1; } @Override public double getMinimalCostToReach(Robot robot, long x, long y) { Position position = Position.returnUniquePosition(x,y); try { return robot.getEnergyRequiredToReach(position).getAmountInSpecifiedUnit(EnergyUnit.WATTSECOND); } catch(IllegalStateException exc) { return Double.parseDouble(exc.getMessage()); } catch(IllegalArgumentException exc) { System.err.println(exc.getMessage()); return -1; } } @Override public int isMoveNextTo18Plus() { return 1; } @Override public void moveNextTo(Robot robot, Robot other) { try{ Robot.moveNextTo(robot,other); } catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} } @Override public void shoot(Robot robot) throws UnsupportedOperationException { if(robot.getEnergy().compareTo(Robot.getEnergyToShoot()) == -1) System.err.println("Insufficient energy to shoot."); else { try { robot.shoot(); } catch(NullPointerException exc) {System.err.println(exc.getMessage());} } } @Override public Wall createWall() throws UnsupportedOperationException { return new Wall(); } @Override public void putWall(Board board, long x, long y, Wall wall) throws UnsupportedOperationException { //assuming "wall" was meant instead of robot in the documentation of IFacade ;-) assert board != null; try{ board.putEntity(Position.returnUniquePosition(x, y), wall); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} catch(NullPointerException exc) {System.err.println(exc.getMessage());} catch(IllegalArgumentException exc) {System.err.println(exc.getMessage());} } @Override public long getWallX(Wall wall) throws IllegalStateException, UnsupportedOperationException { if(wall.getBoard() == null) throw new IllegalStateException("This wall is not placed on a board!"); else { return wall.getPosition().getX(); } } @Override public long getWallY(Wall wall) throws IllegalStateException, UnsupportedOperationException { if(wall.getBoard() == null) throw new IllegalStateException("This wall is not placed on a board!"); else { return wall.getPosition().getY(); } } @Override public Set<Robot> getRobots(Board board) { assert board != null; HashSet<Robot> robots = new HashSet<Robot>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(Robot.class)) robots.add((Robot) entity); return robots; } @Override public Set<Wall> getWalls(Board board) throws UnsupportedOperationException { assert board != null; HashSet<Wall> walls = new HashSet<Wall>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(Wall.class)) walls.add((Wall) entity); return walls; } @Override public Set<RepairKit> getRepairKits(Board board) { assert board != null; HashSet<RepairKit> repairKits = new HashSet<RepairKit>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(RepairKit.class)) repairKits.add((RepairKit) entity); return repairKits; } @Override public Set<SurpriseBox> getSurpriseBoxes(Board board) { assert board != null; HashSet<SurpriseBox> surpriseBoxes = new HashSet<SurpriseBox>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(SurpriseBox.class)) surpriseBoxes.add((SurpriseBox) entity); return surpriseBoxes; } @Override public Set<Battery> getBatteries(Board board) { assert board != null; HashSet<Battery> batteries = new HashSet<Battery>(); for(Entity entity : board.getEntitiesOfSpecifiedKindOnBoard(Battery.class)) batteries.add((Battery) entity); return batteries; } @Override public int loadProgramFromFile(Robot robot, String path) { try { robot.addProgram(path); return 0; } catch(FileNotFoundException exc) { return - 42 ; } } @Override public int saveProgramToFile(Robot robot, String path) { try{ FileWriter f = new FileWriter(path); PrintWriter w = new PrintWriter(f); w.println(robot.getProgram().toString()); w.close(); return 0; } catch(Exception exc){return (int) - Math.PI;} } @Override public void prettyPrintProgram(Robot robot, Writer writer) { try { writer.write(robot.getProgram().toString()); writer.flush(); } catch(IOException exc) {System.err.println(exc.getMessage());} } @Override public void stepn(Robot robot, int n) { try { robot.executeNSteps(n); } catch(IllegalStateException exc) {System.err.println(exc.getMessage());} } }
45089_2
// // ERXDutchLocalizer.java // ERExtensions // // Created by Johan Henselmans on 08/11/09. // Copyright (c) 2009. All rights reserved. // package er.extensions.localization; /** * ERXDutchLocalizer is a subclass of {@link ERXLocalizer}. * <p> * Overrides <code>plurify</code> from its super class * and tries to pluralize the string according to dutch grammar rules. * * <pre> * +en voor de meeste substantieven * De bank -&gt; de banken * Het boek -&gt; de boeken * voorbeelden in context * * -s wordt –zen * de buis -&gt; de buizen * het huis -&gt; de huizen * voorbeelden in context * * -f wordt –ven * de korf -&gt; de korven * voorbeelden in context * * -heid wordt –heden * de grootheid -&gt; de grootheden * de waarheid -&gt; de waarheden * voorbeelden in context * * meervoud met -s * * +s voor substantieven met meer dan 1 lettergreep die eindigen op -e, -el, -en, -er, -em, -ie * De wafel -&gt; de wafels * voorbeelden in context * * +s voor substantieven die eindigen op é, eau: * Het cadeau -&gt; De cadeaus * Het café -&gt; de cafés * * +’s voor substantieven die eindigen op –a, -i, -o, -u, -y: * De paraplu -&gt; De paraplu’s * voorbeelden in context * * +’s voor afkortingen, +'en als afkorting eindigt –s of -x: * tv -&gt; tv's * GPS -&gt; GPS'en * </pre> */ public class ERXDutchLocalizer extends ERXLocalizer { public ERXDutchLocalizer(String aLanguage) { super(aLanguage); } @Override protected String plurify(String name, int count) { String result = name; if(name != null && count > 1) { if(result.endsWith("s")) { result = result.substring(0, result.length()-1)+"zen"; } else if(result.endsWith("f")) { result = result.substring(0, result.length()-1)+"ven"; } else if(result.matches("^.....+[^e][lnrm]$")) { result = result.substring(0, result.length()-1)+"s"; } else if(result.matches("^.....+[^i][e]$")) { result = result.substring(0, result.length()-1)+"s"; } else if(result.matches("^.....+[e]$")) { result = result.substring(0, result.length()-1)+"s"; } else if(result.endsWith("heid")) { result = result.substring(0, result.length()-2)+"den"; } else if(result.endsWith("\u00E9")) { // here the é should be taken care of result = result.substring(0, result.length())+"s"; } else if(result.endsWith("eau")) { result = result.substring(0, result.length())+"s"; } else if(result.matches("^.+[aiouy]$")) { result = result.substring(0, result.length())+"'s"; // these are abbreviations, but which are there? } else if(result.matches("^.+[v]$")) { result = result.substring(0, result.length())+"'s"; } else if(result.matches("^.+[s]$")) { result = result.substring(0, result.length())+"'s"; // end abbreviations } else { result = result.substring(0, result.length())+"en"; } /* if(result.matches("^.+cie$")) return result; if(result.endsWith("ii")) { result = result.substring(0, result.length()-1); } */ } return result; } }
wocommunity/wonder
Frameworks/Core/ERExtensions/Sources/er/extensions/localization/ERXDutchLocalizer.java
1,212
/** * ERXDutchLocalizer is a subclass of {@link ERXLocalizer}. * <p> * Overrides <code>plurify</code> from its super class * and tries to pluralize the string according to dutch grammar rules. * * <pre> * +en voor de meeste substantieven * De bank -&gt; de banken * Het boek -&gt; de boeken * voorbeelden in context * * -s wordt –zen * de buis -&gt; de buizen * het huis -&gt; de huizen * voorbeelden in context * * -f wordt –ven * de korf -&gt; de korven * voorbeelden in context * * -heid wordt –heden * de grootheid -&gt; de grootheden * de waarheid -&gt; de waarheden * voorbeelden in context * * meervoud met -s * * +s voor substantieven met meer dan 1 lettergreep die eindigen op -e, -el, -en, -er, -em, -ie * De wafel -&gt; de wafels * voorbeelden in context * * +s voor substantieven die eindigen op é, eau: * Het cadeau -&gt; De cadeaus * Het café -&gt; de cafés * * +’s voor substantieven die eindigen op –a, -i, -o, -u, -y: * De paraplu -&gt; De paraplu’s * voorbeelden in context * * +’s voor afkortingen, +'en als afkorting eindigt –s of -x: * tv -&gt; tv's * GPS -&gt; GPS'en * </pre> */
block_comment
nl
// // ERXDutchLocalizer.java // ERExtensions // // Created by Johan Henselmans on 08/11/09. // Copyright (c) 2009. All rights reserved. // package er.extensions.localization; /** * ERXDutchLocalizer is a<SUF>*/ public class ERXDutchLocalizer extends ERXLocalizer { public ERXDutchLocalizer(String aLanguage) { super(aLanguage); } @Override protected String plurify(String name, int count) { String result = name; if(name != null && count > 1) { if(result.endsWith("s")) { result = result.substring(0, result.length()-1)+"zen"; } else if(result.endsWith("f")) { result = result.substring(0, result.length()-1)+"ven"; } else if(result.matches("^.....+[^e][lnrm]$")) { result = result.substring(0, result.length()-1)+"s"; } else if(result.matches("^.....+[^i][e]$")) { result = result.substring(0, result.length()-1)+"s"; } else if(result.matches("^.....+[e]$")) { result = result.substring(0, result.length()-1)+"s"; } else if(result.endsWith("heid")) { result = result.substring(0, result.length()-2)+"den"; } else if(result.endsWith("\u00E9")) { // here the é should be taken care of result = result.substring(0, result.length())+"s"; } else if(result.endsWith("eau")) { result = result.substring(0, result.length())+"s"; } else if(result.matches("^.+[aiouy]$")) { result = result.substring(0, result.length())+"'s"; // these are abbreviations, but which are there? } else if(result.matches("^.+[v]$")) { result = result.substring(0, result.length())+"'s"; } else if(result.matches("^.+[s]$")) { result = result.substring(0, result.length())+"'s"; // end abbreviations } else { result = result.substring(0, result.length())+"en"; } /* if(result.matches("^.+cie$")) return result; if(result.endsWith("ii")) { result = result.substring(0, result.length()-1); } */ } return result; } }
75974_3
package byps.http; import java.util.concurrent.atomic.AtomicLong; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import byps.BAsyncResult; import byps.BException; import byps.BExceptionC; import byps.BMessage; import byps.BMessageHeader; import byps.BOutput; import byps.BServer; import byps.BServerR; import byps.BTransport; /** * LongPoll-Nachricht: * */ public class HServerR extends BServerR { protected static final AtomicLong requstCounter = new AtomicLong(); public HServerR(BTransport transport, BServer server, int nbOfConns) { super(transport, server); this.nbOfConns = nbOfConns; this.sleepMillisBeforeRetry = 30 * 1000; } @Override public void start() throws BException { if (log.isDebugEnabled()) log.debug("start("); synchronized (refDone) { refDone[0] = false; } for (int i = 0; i < nbOfConns; i++) { sendLongPoll(null); } if (log.isDebugEnabled()) log.debug(")start"); } @Override public void done() { if (log.isDebugEnabled()) log.debug("done("); synchronized (refDone) { refDone[0] = true; refDone.notifyAll(); } // Wird von HWireClient.done() aufgerufen. // Dort werden die Long-Polls vom Server beendet. // workerThread.interrupt(); // // try { // workerThread.join(1000); // } // catch (InterruptedException ignored) {} if (log.isDebugEnabled()) log.debug(")done"); } protected class LongPoll implements Runnable { protected BMessage methodResult; protected LongPoll(BMessage methodResult) throws BException { if (log.isDebugEnabled()) log.debug("LongPoll(" + methodResult); final long requestId = HServerR.requstCounter.incrementAndGet(); if (methodResult != null) { this.methodResult = methodResult; } else { BOutput outp = transport.getOutput(); outp.header.flags |= BMessageHeader.FLAG_RESPONSE; outp.store(null); // irgendwas, damit auch der Header in den ByteBuffer // geschrieben wird. this.methodResult = outp.toMessage(requestId); } if (log.isDebugEnabled()) log.debug(")LongPoll"); } public void run() { if (log.isDebugEnabled()) log.debug("run("); final long startTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId()); final BAsyncResult<BMessage> asyncResult = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("setAsyncResult(" + msg); final long requestId = HServerR.requstCounter.incrementAndGet(); try { if (e != null) { BOutput out = transport.getOutput(); out.header.flags = BMessageHeader.FLAG_RESPONSE; out.setException(e); msg = out.toMessage(requestId); } sendLongPoll(msg); } catch (BException e1) { if (log.isErrorEnabled()) log.error("Failed to send longpoll for obj=" + msg, e1); } if (log.isDebugEnabled()) log.debug(")setAsyncResult"); } }; BAsyncResult<BMessage> nextAsyncMethod = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("asyncMethod.setAsyncResult(" + msg + ", e=" + e); try { long endTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId() + "[" + (endTime-startTime) + "]"); if (e == null) { // Execute the method received from server. transport.recv(server, msg, asyncResult); } else { BException ex = (BException) e; switch (ex.code) { case BExceptionC.SESSION_CLOSED: // Session was invalidated. log.info("Reverse request stops due to closed session."); break; case BExceptionC.UNAUTHORIZED: // Re-login required log.info("Reverse request was unauthorized."); break; case BExceptionC.CANCELLED: log.info("Reverse request was cancelled."); // no retry break; case BExceptionC.RESEND_LONG_POLL: log.info("Reverse request refreshs long-poll."); // HWireClientR has released the expried long-poll. // Ignore the error and send a new long-poll. asyncResult.setAsyncResult(null, null); break; default: onLostConnection(ex); break; } } } catch (Throwable ex) { // transport.recv failed if (log.isDebugEnabled()) log.debug("recv failed.", e); asyncResult.setAsyncResult(null, ex); } if (log.isDebugEnabled()) log.debug(")asyncMethod.setAsyncResult"); } private void onLostConnection(BException ex) { boolean callLostConnectionHandler = false; synchronized (refDone) { // Server still running? if (!refDone[0]) { try { if (lostConnectionHandler != null) { callLostConnectionHandler = true; } else { // Wait some seconds before next retry refDone.wait(sleepMillisBeforeRetry); } } catch (InterruptedException e1) { } } } if (callLostConnectionHandler) { log.info("Reverse request lost connection due to " + ex + ", call handler for lost connection."); lostConnectionHandler.onLostConnection(ex); } else { log.info("Reverse request refreshs long-poll after due to " + ex); asyncResult.setAsyncResult(null, null); } } }; // Sende den longPoll-Request // Im Body befindet sich die Antwort auf die vorige vom Server gestellte // Anfrage. // Als Ergebnis des longPoll kommt eine neue Serveranfrage (Methode). transport.getWire().sendR(methodResult, nextAsyncMethod); if (log.isDebugEnabled()) log.debug(")run"); } } protected void sendLongPoll(BMessage obj) throws BException { if (log.isDebugEnabled()) log.debug("sendLongPollInWorkerThread(" + obj); synchronized (refDone) { if (!refDone[0]) { LongPoll lp = new LongPoll(obj); lp.run(); } } // synchronized(this) { // if (log.isDebugEnabled()) log.debug("execute in worker thread"); // currentLongPoll_access_sync = lp; // this.notifyAll(); // } if (log.isDebugEnabled()) log.debug(")sendLongPollInWorkerThread"); } // protected class WorkerThread extends Thread { // WorkerThread() { // setName("longpoll-" + c_longPollCounter.incrementAndGet()); // } // // public void run() { // if (log.isDebugEnabled()) log.debug("LongPoll.run("); // try { // while (!isInterrupted()) { // LongPoll lp = null; // synchronized(HServerR.this) { // while (currentLongPoll_access_sync == null) { // if (log.isDebugEnabled()) log.debug("wait for LongPoll"); // HServerR.this.wait(); // } // lp = currentLongPoll_access_sync; // currentLongPoll_access_sync = null; // } // // try { // if (log.isDebugEnabled()) log.debug("execute LongPoll"); // lp.run(); // } // catch (Throwable e) { // log.error("LongPoll worker thread received uncaught exception.", e); // } // } // if (log.isDebugEnabled()) log.debug("Worker interrupted"); // } // catch (InterruptedException e) { // if (log.isDebugEnabled()) log.debug("Recevied "+ e); // } // if (log.isDebugEnabled()) log.debug(")LongPoll.run"); // } // } protected int nbOfConns; protected boolean[] refDone = new boolean[1]; protected final long sleepMillisBeforeRetry; // protected final Thread workerThread = new WorkerThread(); // protected LongPoll currentLongPoll_access_sync; private final static Logger log = LoggerFactory.getLogger(HServerR.class); }
wolfgangimig/byps
java/bypshttp/src/byps/http/HServerR.java
2,616
// Dort werden die Long-Polls vom Server beendet.
line_comment
nl
package byps.http; import java.util.concurrent.atomic.AtomicLong; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import byps.BAsyncResult; import byps.BException; import byps.BExceptionC; import byps.BMessage; import byps.BMessageHeader; import byps.BOutput; import byps.BServer; import byps.BServerR; import byps.BTransport; /** * LongPoll-Nachricht: * */ public class HServerR extends BServerR { protected static final AtomicLong requstCounter = new AtomicLong(); public HServerR(BTransport transport, BServer server, int nbOfConns) { super(transport, server); this.nbOfConns = nbOfConns; this.sleepMillisBeforeRetry = 30 * 1000; } @Override public void start() throws BException { if (log.isDebugEnabled()) log.debug("start("); synchronized (refDone) { refDone[0] = false; } for (int i = 0; i < nbOfConns; i++) { sendLongPoll(null); } if (log.isDebugEnabled()) log.debug(")start"); } @Override public void done() { if (log.isDebugEnabled()) log.debug("done("); synchronized (refDone) { refDone[0] = true; refDone.notifyAll(); } // Wird von HWireClient.done() aufgerufen. // Dort werden<SUF> // workerThread.interrupt(); // // try { // workerThread.join(1000); // } // catch (InterruptedException ignored) {} if (log.isDebugEnabled()) log.debug(")done"); } protected class LongPoll implements Runnable { protected BMessage methodResult; protected LongPoll(BMessage methodResult) throws BException { if (log.isDebugEnabled()) log.debug("LongPoll(" + methodResult); final long requestId = HServerR.requstCounter.incrementAndGet(); if (methodResult != null) { this.methodResult = methodResult; } else { BOutput outp = transport.getOutput(); outp.header.flags |= BMessageHeader.FLAG_RESPONSE; outp.store(null); // irgendwas, damit auch der Header in den ByteBuffer // geschrieben wird. this.methodResult = outp.toMessage(requestId); } if (log.isDebugEnabled()) log.debug(")LongPoll"); } public void run() { if (log.isDebugEnabled()) log.debug("run("); final long startTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId()); final BAsyncResult<BMessage> asyncResult = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("setAsyncResult(" + msg); final long requestId = HServerR.requstCounter.incrementAndGet(); try { if (e != null) { BOutput out = transport.getOutput(); out.header.flags = BMessageHeader.FLAG_RESPONSE; out.setException(e); msg = out.toMessage(requestId); } sendLongPoll(msg); } catch (BException e1) { if (log.isErrorEnabled()) log.error("Failed to send longpoll for obj=" + msg, e1); } if (log.isDebugEnabled()) log.debug(")setAsyncResult"); } }; BAsyncResult<BMessage> nextAsyncMethod = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("asyncMethod.setAsyncResult(" + msg + ", e=" + e); try { long endTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId() + "[" + (endTime-startTime) + "]"); if (e == null) { // Execute the method received from server. transport.recv(server, msg, asyncResult); } else { BException ex = (BException) e; switch (ex.code) { case BExceptionC.SESSION_CLOSED: // Session was invalidated. log.info("Reverse request stops due to closed session."); break; case BExceptionC.UNAUTHORIZED: // Re-login required log.info("Reverse request was unauthorized."); break; case BExceptionC.CANCELLED: log.info("Reverse request was cancelled."); // no retry break; case BExceptionC.RESEND_LONG_POLL: log.info("Reverse request refreshs long-poll."); // HWireClientR has released the expried long-poll. // Ignore the error and send a new long-poll. asyncResult.setAsyncResult(null, null); break; default: onLostConnection(ex); break; } } } catch (Throwable ex) { // transport.recv failed if (log.isDebugEnabled()) log.debug("recv failed.", e); asyncResult.setAsyncResult(null, ex); } if (log.isDebugEnabled()) log.debug(")asyncMethod.setAsyncResult"); } private void onLostConnection(BException ex) { boolean callLostConnectionHandler = false; synchronized (refDone) { // Server still running? if (!refDone[0]) { try { if (lostConnectionHandler != null) { callLostConnectionHandler = true; } else { // Wait some seconds before next retry refDone.wait(sleepMillisBeforeRetry); } } catch (InterruptedException e1) { } } } if (callLostConnectionHandler) { log.info("Reverse request lost connection due to " + ex + ", call handler for lost connection."); lostConnectionHandler.onLostConnection(ex); } else { log.info("Reverse request refreshs long-poll after due to " + ex); asyncResult.setAsyncResult(null, null); } } }; // Sende den longPoll-Request // Im Body befindet sich die Antwort auf die vorige vom Server gestellte // Anfrage. // Als Ergebnis des longPoll kommt eine neue Serveranfrage (Methode). transport.getWire().sendR(methodResult, nextAsyncMethod); if (log.isDebugEnabled()) log.debug(")run"); } } protected void sendLongPoll(BMessage obj) throws BException { if (log.isDebugEnabled()) log.debug("sendLongPollInWorkerThread(" + obj); synchronized (refDone) { if (!refDone[0]) { LongPoll lp = new LongPoll(obj); lp.run(); } } // synchronized(this) { // if (log.isDebugEnabled()) log.debug("execute in worker thread"); // currentLongPoll_access_sync = lp; // this.notifyAll(); // } if (log.isDebugEnabled()) log.debug(")sendLongPollInWorkerThread"); } // protected class WorkerThread extends Thread { // WorkerThread() { // setName("longpoll-" + c_longPollCounter.incrementAndGet()); // } // // public void run() { // if (log.isDebugEnabled()) log.debug("LongPoll.run("); // try { // while (!isInterrupted()) { // LongPoll lp = null; // synchronized(HServerR.this) { // while (currentLongPoll_access_sync == null) { // if (log.isDebugEnabled()) log.debug("wait for LongPoll"); // HServerR.this.wait(); // } // lp = currentLongPoll_access_sync; // currentLongPoll_access_sync = null; // } // // try { // if (log.isDebugEnabled()) log.debug("execute LongPoll"); // lp.run(); // } // catch (Throwable e) { // log.error("LongPoll worker thread received uncaught exception.", e); // } // } // if (log.isDebugEnabled()) log.debug("Worker interrupted"); // } // catch (InterruptedException e) { // if (log.isDebugEnabled()) log.debug("Recevied "+ e); // } // if (log.isDebugEnabled()) log.debug(")LongPoll.run"); // } // } protected int nbOfConns; protected boolean[] refDone = new boolean[1]; protected final long sleepMillisBeforeRetry; // protected final Thread workerThread = new WorkerThread(); // protected LongPoll currentLongPoll_access_sync; private final static Logger log = LoggerFactory.getLogger(HServerR.class); }
117362_6
/* * Copyright (c) 2009-2011, EzWare * 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 the * EzWare 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. * */ package net.sf.openrocket.gui.util; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JList; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; /** * The decorator for JList which makes it work like check list * UI can be designed using JList and which can be later decorated to become a check list * @author Eugene Ryzhikov * * @param <T> list item type */ public class CheckList<T> { private final JList list; private static final MouseAdapter checkBoxEditor = new CheckListEditor(); public static class Builder { private JList list; public Builder(JList list) { this.list = list == null ? new JList() : list; } public Builder() { this(null); } public <T> CheckList<T> build() { return new CheckList<T>(list); } } /** * Wraps the standard JList and makes it work like check list * @param list */ private CheckList(final JList list) { if (list == null) throw new NullPointerException(); this.list = list; this.list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (!isEditorAttached()) list.addMouseListener(checkBoxEditor); this.list.setCellRenderer(new CheckListRenderer()); setupKeyboardActions(list); } @SuppressWarnings("serial") private void setupKeyboardActions(final JList list) { String actionKey = "toggle-check"; list.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), actionKey); list.getActionMap().put(actionKey, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { toggleIndex(list.getSelectedIndex()); } }); } private boolean isEditorAttached() { for (MouseListener ml : list.getMouseListeners()) { if (ml instanceof CheckListEditor) return true; } return false; } public JList getList() { return list; } /** * Sets data to a check list. Simplification for setting new the model * @param data */ public void setData(Collection<T> data) { setModel(new DefaultCheckListModel<T>(data)); } /** * Sets the model for check list. * @param model */ public void setModel(DefaultCheckListModel<T> model) { list.setModel(model); } @SuppressWarnings("unchecked") public DefaultCheckListModel<T> getModel() { return (DefaultCheckListModel<T>) list.getModel(); } /** * Returns a collection of checked items. * @return collection of checked items. Empty collection if nothing is selected */ public Collection<T> getCheckedItems() { return getModel().getCheckedItems(); } public Collection<T> getUncheckedItems() { List<T> unchecked = new ArrayList<T>(); for (int i = getModel().getSize() - 1; i >= 0; i--) { unchecked.add((T) getModel().getElementAt(i)); } unchecked.removeAll(getCheckedItems()); return unchecked; } public void checkAll() { getModel().checkAll(); } public void clearAll() { getModel().clearAll(); } /** * Resets checked elements * @param elements */ public void setCheckedItems(Collection<T> elements) { getModel().setCheckedItems(elements); } public void setUncheckedItems( Collection<T> elements ) { getModel().setUncheckedItems(elements); } public void toggleIndex(int index) { if (index >= 0 && index < list.getModel().getSize()) { DefaultCheckListModel<T> model = getModel(); model.setCheckedIndex(index, !model.isCheckedIndex(index)); } } }
wolsen/openrocket
swing/src/net/sf/openrocket/gui/util/CheckList.java
1,773
/** * Resets checked elements * @param elements */
block_comment
nl
/* * Copyright (c) 2009-2011, EzWare * 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 the * EzWare 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. * */ package net.sf.openrocket.gui.util; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JList; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; /** * The decorator for JList which makes it work like check list * UI can be designed using JList and which can be later decorated to become a check list * @author Eugene Ryzhikov * * @param <T> list item type */ public class CheckList<T> { private final JList list; private static final MouseAdapter checkBoxEditor = new CheckListEditor(); public static class Builder { private JList list; public Builder(JList list) { this.list = list == null ? new JList() : list; } public Builder() { this(null); } public <T> CheckList<T> build() { return new CheckList<T>(list); } } /** * Wraps the standard JList and makes it work like check list * @param list */ private CheckList(final JList list) { if (list == null) throw new NullPointerException(); this.list = list; this.list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (!isEditorAttached()) list.addMouseListener(checkBoxEditor); this.list.setCellRenderer(new CheckListRenderer()); setupKeyboardActions(list); } @SuppressWarnings("serial") private void setupKeyboardActions(final JList list) { String actionKey = "toggle-check"; list.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), actionKey); list.getActionMap().put(actionKey, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { toggleIndex(list.getSelectedIndex()); } }); } private boolean isEditorAttached() { for (MouseListener ml : list.getMouseListeners()) { if (ml instanceof CheckListEditor) return true; } return false; } public JList getList() { return list; } /** * Sets data to a check list. Simplification for setting new the model * @param data */ public void setData(Collection<T> data) { setModel(new DefaultCheckListModel<T>(data)); } /** * Sets the model for check list. * @param model */ public void setModel(DefaultCheckListModel<T> model) { list.setModel(model); } @SuppressWarnings("unchecked") public DefaultCheckListModel<T> getModel() { return (DefaultCheckListModel<T>) list.getModel(); } /** * Returns a collection of checked items. * @return collection of checked items. Empty collection if nothing is selected */ public Collection<T> getCheckedItems() { return getModel().getCheckedItems(); } public Collection<T> getUncheckedItems() { List<T> unchecked = new ArrayList<T>(); for (int i = getModel().getSize() - 1; i >= 0; i--) { unchecked.add((T) getModel().getElementAt(i)); } unchecked.removeAll(getCheckedItems()); return unchecked; } public void checkAll() { getModel().checkAll(); } public void clearAll() { getModel().clearAll(); } /** * Resets checked elements<SUF>*/ public void setCheckedItems(Collection<T> elements) { getModel().setCheckedItems(elements); } public void setUncheckedItems( Collection<T> elements ) { getModel().setUncheckedItems(elements); } public void toggleIndex(int index) { if (index >= 0 && index < list.getModel().getSize()) { DefaultCheckListModel<T> model = getModel(); model.setCheckedIndex(index, !model.isCheckedIndex(index)); } } }
146070_15
/* * 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.commons.rng.sampling.distribution; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * List of samplers. */ public class ContinuousSamplersList { /** List of all RNGs implemented in the library. */ private static final List<ContinuousSamplerTestData[]> LIST = new ArrayList<ContinuousSamplerTestData[]>(); static { try { // List of distributions to test. // Gaussian ("inverse method"). final double meanNormal = -123.45; final double sigmaNormal = 6.789; add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), RandomSource.create(RandomSource.KISS)); // Gaussian (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal)); // Gaussian ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), new GaussianSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Beta ("inverse method"). final double alphaBeta = 4.3; final double betaBeta = 2.1; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta), RandomSource.create(RandomSource.ISAAC)); // Beta ("Cheng"). add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBeta, alphaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta)); // Beta ("Cheng", alternate algorithm). final double alphaBetaAlt = 0.5678; final double betaBetaAlt = 0.1234; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBetaAlt, betaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBetaAlt, alphaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt)); // Cauchy ("inverse method"). final double medianCauchy = 0.123; final double scaleCauchy = 4.5; add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(medianCauchy, scaleCauchy), RandomSource.create(RandomSource.WELL_19937_C)); // Chi-square ("inverse method"). final int dofChi2 = 12; add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(dofChi2), RandomSource.create(RandomSource.WELL_19937_A)); // Exponential ("inverse method"). final double meanExp = 3.45; add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp), RandomSource.create(RandomSource.WELL_44497_A)); // Exponential. add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp), new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp)); // F ("inverse method"). final int numDofF = 4; final int denomDofF = 7; add(LIST, new org.apache.commons.math3.distribution.FDistribution(numDofF, denomDofF), RandomSource.create(RandomSource.MT_64)); // Gamma ("inverse method"). final double thetaGammaSmallerThanOne = 0.1234; final double thetaGammaLargerThanOne = 2.345; final double alphaGamma = 3.456; add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma), RandomSource.create(RandomSource.SPLIT_MIX_64)); // Gamma (theta < 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaSmallerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), alphaGamma, thetaGammaSmallerThanOne)); // Gamma (theta > 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B), alphaGamma, thetaGammaLargerThanOne)); // Gumbel ("inverse method"). final double muGumbel = -4.56; final double betaGumbel = 0.123; add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(muGumbel, betaGumbel), RandomSource.create(RandomSource.WELL_1024_A)); // Laplace ("inverse method"). final double muLaplace = 12.3; final double betaLaplace = 5.6; add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(muLaplace, betaLaplace), RandomSource.create(RandomSource.MWC_256)); // Levy ("inverse method"). final double muLevy = -1.098; final double cLevy = 0.76; add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(muLevy, cLevy), RandomSource.create(RandomSource.TWO_CMRES)); // Log normal ("inverse method"). final double scaleLogNormal = 23.45; final double shapeLogNormal = 0.1234; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal), RandomSource.create(RandomSource.KISS)); // Log normal ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal), new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal)); // Log normal ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal), new MarsagliaLogNormalSampler(RandomSource.create(RandomSource.MT_64), scaleLogNormal, shapeLogNormal)); // Logistic ("inverse method"). final double muLogistic = -123.456; final double sLogistic = 7.89; add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(muLogistic, sLogistic), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6)); // Nakagami ("inverse method"). final double muNakagami = 78.9; final double omegaNakagami = 23.4; add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(muNakagami, omegaNakagami), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3)); // Pareto ("inverse method"). final double scalePareto = 23.45; final double shapePareto = 0.1234; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11)); // Pareto. add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto), new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto)); // T ("inverse method"). final double dofT = 0.76543; add(LIST, new org.apache.commons.math3.distribution.TDistribution(dofT), RandomSource.create(RandomSource.ISAAC)); // Triangular ("inverse method"). final double aTriangle = -0.76543; final double cTriangle = -0.65432; final double bTriangle = -0.54321; add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(aTriangle, cTriangle, bTriangle), RandomSource.create(RandomSource.MT)); // Uniform ("inverse method"). final double loUniform = -1.098; final double hiUniform = 0.76; add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform), RandomSource.create(RandomSource.TWO_CMRES)); // Uniform. add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform), new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform)); // Weibull ("inverse method"). final double alphaWeibull = 678.9; final double betaWeibull = 98.76; add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(alphaWeibull, betaWeibull), RandomSource.create(RandomSource.WELL_44497_B)); } catch (Exception e) { System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ContinuousSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, UniformRandomProvider rng) { final ContinuousSampler inverseMethodSampler = new InverseTransformContinuousSampler(rng, new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler, getDeciles(dist)) }); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler, getDeciles(dist)) }); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<ContinuousSamplerTestData[]> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @return the deciles of the given distribution. */ private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) { final int last = 9; final double[] deciles = new double[last]; final double ten = 10; for (int i = 0; i < last; i++) { deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten); } return deciles; } }
woonsan/commons-rng
commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplersList.java
3,918
// Gumbel ("inverse method").
line_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.commons.rng.sampling.distribution; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * List of samplers. */ public class ContinuousSamplersList { /** List of all RNGs implemented in the library. */ private static final List<ContinuousSamplerTestData[]> LIST = new ArrayList<ContinuousSamplerTestData[]>(); static { try { // List of distributions to test. // Gaussian ("inverse method"). final double meanNormal = -123.45; final double sigmaNormal = 6.789; add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), RandomSource.create(RandomSource.KISS)); // Gaussian (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal)); // Gaussian ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal), new GaussianSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Beta ("inverse method"). final double alphaBeta = 4.3; final double betaBeta = 2.1; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta), RandomSource.create(RandomSource.ISAAC)); // Beta ("Cheng"). add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBeta, alphaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta)); // Beta ("Cheng", alternate algorithm). final double alphaBetaAlt = 0.5678; final double betaBetaAlt = 0.1234; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBetaAlt, betaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBetaAlt, alphaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt)); // Cauchy ("inverse method"). final double medianCauchy = 0.123; final double scaleCauchy = 4.5; add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(medianCauchy, scaleCauchy), RandomSource.create(RandomSource.WELL_19937_C)); // Chi-square ("inverse method"). final int dofChi2 = 12; add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(dofChi2), RandomSource.create(RandomSource.WELL_19937_A)); // Exponential ("inverse method"). final double meanExp = 3.45; add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp), RandomSource.create(RandomSource.WELL_44497_A)); // Exponential. add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp), new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp)); // F ("inverse method"). final int numDofF = 4; final int denomDofF = 7; add(LIST, new org.apache.commons.math3.distribution.FDistribution(numDofF, denomDofF), RandomSource.create(RandomSource.MT_64)); // Gamma ("inverse method"). final double thetaGammaSmallerThanOne = 0.1234; final double thetaGammaLargerThanOne = 2.345; final double alphaGamma = 3.456; add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma), RandomSource.create(RandomSource.SPLIT_MIX_64)); // Gamma (theta < 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaSmallerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), alphaGamma, thetaGammaSmallerThanOne)); // Gamma (theta > 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B), alphaGamma, thetaGammaLargerThanOne)); // Gumbel ("inverse<SUF> final double muGumbel = -4.56; final double betaGumbel = 0.123; add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(muGumbel, betaGumbel), RandomSource.create(RandomSource.WELL_1024_A)); // Laplace ("inverse method"). final double muLaplace = 12.3; final double betaLaplace = 5.6; add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(muLaplace, betaLaplace), RandomSource.create(RandomSource.MWC_256)); // Levy ("inverse method"). final double muLevy = -1.098; final double cLevy = 0.76; add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(muLevy, cLevy), RandomSource.create(RandomSource.TWO_CMRES)); // Log normal ("inverse method"). final double scaleLogNormal = 23.45; final double shapeLogNormal = 0.1234; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal), RandomSource.create(RandomSource.KISS)); // Log normal ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal), new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal)); // Log normal ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal), new MarsagliaLogNormalSampler(RandomSource.create(RandomSource.MT_64), scaleLogNormal, shapeLogNormal)); // Logistic ("inverse method"). final double muLogistic = -123.456; final double sLogistic = 7.89; add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(muLogistic, sLogistic), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6)); // Nakagami ("inverse method"). final double muNakagami = 78.9; final double omegaNakagami = 23.4; add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(muNakagami, omegaNakagami), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3)); // Pareto ("inverse method"). final double scalePareto = 23.45; final double shapePareto = 0.1234; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11)); // Pareto. add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto), new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto)); // T ("inverse method"). final double dofT = 0.76543; add(LIST, new org.apache.commons.math3.distribution.TDistribution(dofT), RandomSource.create(RandomSource.ISAAC)); // Triangular ("inverse method"). final double aTriangle = -0.76543; final double cTriangle = -0.65432; final double bTriangle = -0.54321; add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(aTriangle, cTriangle, bTriangle), RandomSource.create(RandomSource.MT)); // Uniform ("inverse method"). final double loUniform = -1.098; final double hiUniform = 0.76; add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform), RandomSource.create(RandomSource.TWO_CMRES)); // Uniform. add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform), new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform)); // Weibull ("inverse method"). final double alphaWeibull = 678.9; final double betaWeibull = 98.76; add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(alphaWeibull, betaWeibull), RandomSource.create(RandomSource.WELL_44497_B)); } catch (Exception e) { System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ContinuousSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, UniformRandomProvider rng) { final ContinuousSampler inverseMethodSampler = new InverseTransformContinuousSampler(rng, new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler, getDeciles(dist)) }); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler, getDeciles(dist)) }); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<ContinuousSamplerTestData[]> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @return the deciles of the given distribution. */ private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) { final int last = 9; final double[] deciles = new double[last]; final double ten = 10; for (int i = 0; i < last; i++) { deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten); } return deciles; } }
84602_23
/* * Social World * Copyright (C) 2014 Mathias Sikos * * This program 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 2 * 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 General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * or see http://www.gnu.org/licenses/gpl-2.0.html * */ package org.socialworld.actions; import org.socialworld.GlobalSwitches; import org.socialworld.attributes.Time; import org.socialworld.calculation.IObjectReceiver; import org.socialworld.calculation.IObjectSender; import org.socialworld.calculation.NoObject; import org.socialworld.calculation.ObjectRequester; import org.socialworld.calculation.SimulationCluster; import org.socialworld.calculation.Type; import org.socialworld.calculation.Value; import org.socialworld.collections.ValueArrayList; import org.socialworld.core.Event; import org.socialworld.core.IEventParam; import org.socialworld.core.Simulation; import org.socialworld.objects.SimulationObject; import org.socialworld.objects.access.HiddenSimulationObject; /** * @author Mathias Sikos (MatWorsoc) * * It's the base class for all simulation actions (actions done by simulation * objects). It collects all base action attributes. That are action type, * action mode, priority, earliest execution time, latest execution time, * duration, remained duration, intensity. * * * German: * AbstractAction ist die Basisklasse (abstrakte Klasse) für Aktionen der Simlationsobjekte. * Die Aktionsobjekte von abgeleiteten Klassen werden im ActionMaster verwaltet * und vom ActionHandler zur Ausführung gebracht. * * Die Ausführung besteht dabei aus 2 Schritten * a) Einleitung der Ausführung * b) Wirksamwerden der Aktion * * a) Einleitung der Ausführung: * Der ActionMaster führt die ActionHandler aller Simulationsobjekte * und weist den jeweiligen ActionHandler an, mit der Ausführung einer Aktion zu beginnen bzw. eine Aktion fortzusetzen. * Der ActionHandler sorgt dafür, * dass für das auszuführende Aktionsobjekt (Ableitung von AbstractAction) die Methode perform() aufgerufen wird. * Die Methode perform() ist abstract und muss in allen Ableitungen implementiert werden/sein. * Die Methode perform() führt Vorabprüfungen der Daten zur Aktion durch, * erzeugt das zugehörige Performer-Objekt (siehe Schritt b), * erzeugt die auszulösenden Ereignisse, * fügt den Ereignissen das Performerobjekt als Ereigniseigenschaft hinzu, * und trägt diese in die Ereignisverwaltung (EventMaster) ein (siehe Schritt b). * * b) Wirksamwerden der Aktion * Es gilt der Grundsatz, dass alle Aktionen durch ihre Ereignisverarbeitung wirksam werden. * Im Schritt a) wurden Ereignisse zu den Aktionen in die Ereignisverwaltung eingetragen. * Die Ereignisverwaltung arbeitet die Ereignisse nach ihren Regeln ab. * Für jedes Event wird die evaluate-Methode des dem Ereignis zugeordenten Performers (Ableitung der Klasse ActionPerformer) aufgerufen. * Diese wiederum ruft die Methode perform im Performerobjekt auf. * Diese Methode ermittelt die für die Ereignisverarbeitung benötigten Werte * aus dem Aktionsobjekt, dem ausführenden Objekt (also dem Akteur) und ggf. dem Zielobjekt. * Diese Werte werden standardisiert in einer Liste abgelegt * und können vom Ereignis über Standardmethoden ausgelesen werden. * Schließlich werden für die Ereignisse ihre Wirkung auf die Simulationsobjekte und ggf. Reaktionen ermittelt. * * Die Klasse AbstractAction ist die Basisklasse für die Aktionsobjekte des Schrittes a), * enthält also die Daten für die Einleitung der Ausführung (Erzeugung von Performer und Event). * */ public abstract class AbstractAction implements IObjectSender, IObjectReceiver { public static final int MAX_ACTION_PRIORITY = 256; protected SimulationObject actor; private HiddenSimulationObject hiddenWriteAccesToActor; protected ActionType type; protected ActionMode mode; protected Time minTime; protected Time maxTime; protected int priority; protected float intensity; protected long duration; protected long remainedDuration; protected boolean interruptable = false; protected boolean interrupted = false; protected boolean done = false; private Simulation simulation = Simulation.getInstance(); protected AbstractAction linkedAction; static private String[] standardPropertyNames = ActionType.getStandardPropertyNames(); protected final String[] furtherPropertyNames; protected ObjectRequester objectRequester = new ObjectRequester(); protected AbstractAction() { this.type = ActionType.ignore; this.furtherPropertyNames = this.type.getFurtherPropertyNames(); } public AbstractAction(AbstractAction original) { setBaseProperties(original); this.furtherPropertyNames = this.type.getFurtherPropertyNames(); setFurtherProperties(original); } protected AbstractAction(ValueArrayList actionProperties) { setBaseProperties(actionProperties); this.furtherPropertyNames = this.type.getFurtherPropertyNames(); setFurtherProperties(actionProperties); } public void setActor(SimulationObject actor, HiddenSimulationObject hiddenWriteAccess) { this.hiddenWriteAccesToActor = hiddenWriteAccess; this.actor = actor; } public final void removeWriteAccess() { this.hiddenWriteAccesToActor = null; } protected final HiddenSimulationObject getHiddenWriteAccessToActor(AbstractAction concreteAction) { if (this == concreteAction ) return hiddenWriteAccesToActor; else // dummy return new HiddenSimulationObject(); } public boolean isToBeIgnored() { return (type == ActionType.ignore); } private void setBaseProperties(ValueArrayList actionProperties) { ActionType type; ActionMode mode; float intensity; Time minTime, maxTime; int priority; long duration; Value v; Object o; v = actionProperties.getValue( standardPropertyNames[0]); o = v.getObject(Type.actionType); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > type: o (getObject(Type.actionType)) is NoObject " + ((NoObject)o).getReason().toString() ); } return; } else { type = (ActionType) o; } v = actionProperties.getValue( standardPropertyNames[1]); o = v.getObject(Type.actionMode); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > mode: o (getObject(Type.actionMode)) is NoObject " + ((NoObject)o).getReason().toString() ); } return; } else { mode = (ActionMode) o; } v = actionProperties.getValue( standardPropertyNames[2]); o = v.getObject(Type.floatingpoint); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > intensity: o (getObject(Type.floatingpoint)) is NoObject " + ((NoObject)o).getReason().toString() ); } intensity = 0; } else { intensity = (float) o; } v = actionProperties.getValue( standardPropertyNames[3]); o = v.getObject(Type.time); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > minTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() ); } minTime = new Time(); } else { minTime = (Time) o; } v = actionProperties.getValue( standardPropertyNames[4]); o = v.getObject(Type.time); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > maxTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() ); } maxTime = new Time(); } else { maxTime = (Time) o; } v = actionProperties.getValue( standardPropertyNames[5]); o = v.getObject(Type.integer); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > priority: o (getObject(Type.integer)) is NoObject " + ((NoObject)o).getReason().toString() ); } priority = 0; } else { priority = (int) o; } v = actionProperties.getValue( standardPropertyNames[6]); o = v.getObject(Type.longinteger); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > duration: o (getObject(Type.longinteger)) is NoObject " + ((NoObject)o).getReason().toString() ); } duration = 0; } else { duration = (long) o; } this.setType(type); this.setMode(mode); this.setIntensity(intensity); this.setMinTime(minTime); this.setMaxTime(maxTime); this.setPriority(priority); this.setDuration(duration); this.setRemainedDuration(duration); this.linkedAction = null; if (duration > 0) interruptable = true; } protected abstract void setFurtherProperties(ValueArrayList actionProperties); protected void setBaseProperties(AbstractAction original) { this.type = original.type; this.mode = original.mode; this.intensity = original.intensity; this.minTime = original.minTime; this.maxTime = original.maxTime; this.priority = original.priority; this.duration = original.duration; } protected abstract void setFurtherProperties(AbstractAction original); public abstract void perform(); protected void addEvent(Event event) { simulation.getEventMaster().addEvent(event); } /** * The method sets the linked action. * * @param linked action */ public void setLinkedAction (AbstractAction linkedAction) { this.linkedAction = linkedAction; } /** * The method returns the linked action. * It is null if there is no linked action. * * @return linked action */ public AbstractAction getLinkedAction() { return linkedAction; } public SimulationObject getActor() { return actor; } public void setDone() { done = true; } public boolean isDone() { return done; } public boolean isInterruptable() { return interruptable; } public boolean isInterrupted() { return interrupted; } public void interrupt() { this.setDuration(remainedDuration); this.setRemainedDuration(0); this.interrupted = true; } public void continueAfterInterrupt() { this.setRemainedDuration(duration); this.interrupted = false; } public void requestPropertyList(IEventParam paramObject) { ValueArrayList propertiesAsValueList = new ValueArrayList(); propertiesAsValueList.add(new Value(Type.floatingpoint, Value.VALUE_BY_NAME_ACTION_INTENSITY, this.intensity)); paramObject.answerPropertiesRequest(propertiesAsValueList); } /** * The methods returns the action type. * * @return type */ public ActionType getType() { return this.type; } /** * @param type * the type to set */ public void setType(final ActionType type) { this.type = type; } /** * @return the time */ public Time getMinTime() { return this.minTime; } /** * @param time * the time to set */ public void setMinTime(final Time time) { this.minTime = time; } /** * @return the time */ public Time getMaxTime() { return this.maxTime; } /** * @param time * the time to set */ public void setMaxTime(final Time time) { this.maxTime = time; } /** * The methods returns the action's priority. * * @return priority */ public int getPriority() { return this.priority; } /** * @param priority * the priority to set */ public void setPriority(final int priority) { this.priority = priority; } /** * @return the mode */ public ActionMode getMode() { return this.mode; } /** * @param mode * the mode to set */ public void setMode(final ActionMode mode) { this.mode = mode; } /** * @return the intensity */ public float getIntensity() { return this.intensity; } /** * @param intensity * the intensity to set */ public void setIntensity(final float intensity) { this.intensity = intensity; } /** * @return the duration */ public long getDuration() { return this.duration; } /** * @param duration * the duration to set */ public void setDuration(final long duration) { this.duration = duration; } /** * The methods returns the action's remained duration. * * @return remainedDuration */ public long getRemainedDuration() { return this.remainedDuration; } /** * @param remainedDuration * the remainedDuration to set */ public void setRemainedDuration(final long remainedDuration) { this.remainedDuration = remainedDuration; } /** * The method decrements the attribute remainedDuration. That means, an * action needs less time to complete. * * @param decrement */ public void lowerRemainedDuration(final long decrement) { this.remainedDuration -= decrement; // System.out.println("AbstractAction.lowerRemainedDuration(): " + toString() + " " + actor.toString() + " noch offen: " + this.remainedDuration); if (this.remainedDuration <= 0) done = true; } /** * The method increments the attribute remainedDuration. That means, an * action needs more time to complete. * * @param increment */ public void raiseRemainedDuration(final long increment) { this.remainedDuration += increment; } @Override public String toString() { return "(" + this.type.toString() + ")"; //$NON-NLS-1$ } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////implementing IObjectSender /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public int sendYourselfTo(IObjectReceiver receiver, int requestID) { return receiver.receiveObject(requestID, this); } public int sendYourselfTo(SimulationCluster cluster, IObjectReceiver receiver, int requestID) { return receiver.receiveObject(requestID, this); } public IObjectSender copy() { return this; } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////implementing IObjectReceiver /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// @Override public int receiveObject(int requestID, Object object) { objectRequester.receive(requestID, object); return 0; } }
worsoc/socialworld
src/main/java/org/socialworld/actions/AbstractAction.java
4,863
//////////////////////implementing IObjectSender ///////////////////////////////////////
line_comment
nl
/* * Social World * Copyright (C) 2014 Mathias Sikos * * This program 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 2 * 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 General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * or see http://www.gnu.org/licenses/gpl-2.0.html * */ package org.socialworld.actions; import org.socialworld.GlobalSwitches; import org.socialworld.attributes.Time; import org.socialworld.calculation.IObjectReceiver; import org.socialworld.calculation.IObjectSender; import org.socialworld.calculation.NoObject; import org.socialworld.calculation.ObjectRequester; import org.socialworld.calculation.SimulationCluster; import org.socialworld.calculation.Type; import org.socialworld.calculation.Value; import org.socialworld.collections.ValueArrayList; import org.socialworld.core.Event; import org.socialworld.core.IEventParam; import org.socialworld.core.Simulation; import org.socialworld.objects.SimulationObject; import org.socialworld.objects.access.HiddenSimulationObject; /** * @author Mathias Sikos (MatWorsoc) * * It's the base class for all simulation actions (actions done by simulation * objects). It collects all base action attributes. That are action type, * action mode, priority, earliest execution time, latest execution time, * duration, remained duration, intensity. * * * German: * AbstractAction ist die Basisklasse (abstrakte Klasse) für Aktionen der Simlationsobjekte. * Die Aktionsobjekte von abgeleiteten Klassen werden im ActionMaster verwaltet * und vom ActionHandler zur Ausführung gebracht. * * Die Ausführung besteht dabei aus 2 Schritten * a) Einleitung der Ausführung * b) Wirksamwerden der Aktion * * a) Einleitung der Ausführung: * Der ActionMaster führt die ActionHandler aller Simulationsobjekte * und weist den jeweiligen ActionHandler an, mit der Ausführung einer Aktion zu beginnen bzw. eine Aktion fortzusetzen. * Der ActionHandler sorgt dafür, * dass für das auszuführende Aktionsobjekt (Ableitung von AbstractAction) die Methode perform() aufgerufen wird. * Die Methode perform() ist abstract und muss in allen Ableitungen implementiert werden/sein. * Die Methode perform() führt Vorabprüfungen der Daten zur Aktion durch, * erzeugt das zugehörige Performer-Objekt (siehe Schritt b), * erzeugt die auszulösenden Ereignisse, * fügt den Ereignissen das Performerobjekt als Ereigniseigenschaft hinzu, * und trägt diese in die Ereignisverwaltung (EventMaster) ein (siehe Schritt b). * * b) Wirksamwerden der Aktion * Es gilt der Grundsatz, dass alle Aktionen durch ihre Ereignisverarbeitung wirksam werden. * Im Schritt a) wurden Ereignisse zu den Aktionen in die Ereignisverwaltung eingetragen. * Die Ereignisverwaltung arbeitet die Ereignisse nach ihren Regeln ab. * Für jedes Event wird die evaluate-Methode des dem Ereignis zugeordenten Performers (Ableitung der Klasse ActionPerformer) aufgerufen. * Diese wiederum ruft die Methode perform im Performerobjekt auf. * Diese Methode ermittelt die für die Ereignisverarbeitung benötigten Werte * aus dem Aktionsobjekt, dem ausführenden Objekt (also dem Akteur) und ggf. dem Zielobjekt. * Diese Werte werden standardisiert in einer Liste abgelegt * und können vom Ereignis über Standardmethoden ausgelesen werden. * Schließlich werden für die Ereignisse ihre Wirkung auf die Simulationsobjekte und ggf. Reaktionen ermittelt. * * Die Klasse AbstractAction ist die Basisklasse für die Aktionsobjekte des Schrittes a), * enthält also die Daten für die Einleitung der Ausführung (Erzeugung von Performer und Event). * */ public abstract class AbstractAction implements IObjectSender, IObjectReceiver { public static final int MAX_ACTION_PRIORITY = 256; protected SimulationObject actor; private HiddenSimulationObject hiddenWriteAccesToActor; protected ActionType type; protected ActionMode mode; protected Time minTime; protected Time maxTime; protected int priority; protected float intensity; protected long duration; protected long remainedDuration; protected boolean interruptable = false; protected boolean interrupted = false; protected boolean done = false; private Simulation simulation = Simulation.getInstance(); protected AbstractAction linkedAction; static private String[] standardPropertyNames = ActionType.getStandardPropertyNames(); protected final String[] furtherPropertyNames; protected ObjectRequester objectRequester = new ObjectRequester(); protected AbstractAction() { this.type = ActionType.ignore; this.furtherPropertyNames = this.type.getFurtherPropertyNames(); } public AbstractAction(AbstractAction original) { setBaseProperties(original); this.furtherPropertyNames = this.type.getFurtherPropertyNames(); setFurtherProperties(original); } protected AbstractAction(ValueArrayList actionProperties) { setBaseProperties(actionProperties); this.furtherPropertyNames = this.type.getFurtherPropertyNames(); setFurtherProperties(actionProperties); } public void setActor(SimulationObject actor, HiddenSimulationObject hiddenWriteAccess) { this.hiddenWriteAccesToActor = hiddenWriteAccess; this.actor = actor; } public final void removeWriteAccess() { this.hiddenWriteAccesToActor = null; } protected final HiddenSimulationObject getHiddenWriteAccessToActor(AbstractAction concreteAction) { if (this == concreteAction ) return hiddenWriteAccesToActor; else // dummy return new HiddenSimulationObject(); } public boolean isToBeIgnored() { return (type == ActionType.ignore); } private void setBaseProperties(ValueArrayList actionProperties) { ActionType type; ActionMode mode; float intensity; Time minTime, maxTime; int priority; long duration; Value v; Object o; v = actionProperties.getValue( standardPropertyNames[0]); o = v.getObject(Type.actionType); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > type: o (getObject(Type.actionType)) is NoObject " + ((NoObject)o).getReason().toString() ); } return; } else { type = (ActionType) o; } v = actionProperties.getValue( standardPropertyNames[1]); o = v.getObject(Type.actionMode); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > mode: o (getObject(Type.actionMode)) is NoObject " + ((NoObject)o).getReason().toString() ); } return; } else { mode = (ActionMode) o; } v = actionProperties.getValue( standardPropertyNames[2]); o = v.getObject(Type.floatingpoint); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > intensity: o (getObject(Type.floatingpoint)) is NoObject " + ((NoObject)o).getReason().toString() ); } intensity = 0; } else { intensity = (float) o; } v = actionProperties.getValue( standardPropertyNames[3]); o = v.getObject(Type.time); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > minTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() ); } minTime = new Time(); } else { minTime = (Time) o; } v = actionProperties.getValue( standardPropertyNames[4]); o = v.getObject(Type.time); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > maxTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() ); } maxTime = new Time(); } else { maxTime = (Time) o; } v = actionProperties.getValue( standardPropertyNames[5]); o = v.getObject(Type.integer); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > priority: o (getObject(Type.integer)) is NoObject " + ((NoObject)o).getReason().toString() ); } priority = 0; } else { priority = (int) o; } v = actionProperties.getValue( standardPropertyNames[6]); o = v.getObject(Type.longinteger); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > duration: o (getObject(Type.longinteger)) is NoObject " + ((NoObject)o).getReason().toString() ); } duration = 0; } else { duration = (long) o; } this.setType(type); this.setMode(mode); this.setIntensity(intensity); this.setMinTime(minTime); this.setMaxTime(maxTime); this.setPriority(priority); this.setDuration(duration); this.setRemainedDuration(duration); this.linkedAction = null; if (duration > 0) interruptable = true; } protected abstract void setFurtherProperties(ValueArrayList actionProperties); protected void setBaseProperties(AbstractAction original) { this.type = original.type; this.mode = original.mode; this.intensity = original.intensity; this.minTime = original.minTime; this.maxTime = original.maxTime; this.priority = original.priority; this.duration = original.duration; } protected abstract void setFurtherProperties(AbstractAction original); public abstract void perform(); protected void addEvent(Event event) { simulation.getEventMaster().addEvent(event); } /** * The method sets the linked action. * * @param linked action */ public void setLinkedAction (AbstractAction linkedAction) { this.linkedAction = linkedAction; } /** * The method returns the linked action. * It is null if there is no linked action. * * @return linked action */ public AbstractAction getLinkedAction() { return linkedAction; } public SimulationObject getActor() { return actor; } public void setDone() { done = true; } public boolean isDone() { return done; } public boolean isInterruptable() { return interruptable; } public boolean isInterrupted() { return interrupted; } public void interrupt() { this.setDuration(remainedDuration); this.setRemainedDuration(0); this.interrupted = true; } public void continueAfterInterrupt() { this.setRemainedDuration(duration); this.interrupted = false; } public void requestPropertyList(IEventParam paramObject) { ValueArrayList propertiesAsValueList = new ValueArrayList(); propertiesAsValueList.add(new Value(Type.floatingpoint, Value.VALUE_BY_NAME_ACTION_INTENSITY, this.intensity)); paramObject.answerPropertiesRequest(propertiesAsValueList); } /** * The methods returns the action type. * * @return type */ public ActionType getType() { return this.type; } /** * @param type * the type to set */ public void setType(final ActionType type) { this.type = type; } /** * @return the time */ public Time getMinTime() { return this.minTime; } /** * @param time * the time to set */ public void setMinTime(final Time time) { this.minTime = time; } /** * @return the time */ public Time getMaxTime() { return this.maxTime; } /** * @param time * the time to set */ public void setMaxTime(final Time time) { this.maxTime = time; } /** * The methods returns the action's priority. * * @return priority */ public int getPriority() { return this.priority; } /** * @param priority * the priority to set */ public void setPriority(final int priority) { this.priority = priority; } /** * @return the mode */ public ActionMode getMode() { return this.mode; } /** * @param mode * the mode to set */ public void setMode(final ActionMode mode) { this.mode = mode; } /** * @return the intensity */ public float getIntensity() { return this.intensity; } /** * @param intensity * the intensity to set */ public void setIntensity(final float intensity) { this.intensity = intensity; } /** * @return the duration */ public long getDuration() { return this.duration; } /** * @param duration * the duration to set */ public void setDuration(final long duration) { this.duration = duration; } /** * The methods returns the action's remained duration. * * @return remainedDuration */ public long getRemainedDuration() { return this.remainedDuration; } /** * @param remainedDuration * the remainedDuration to set */ public void setRemainedDuration(final long remainedDuration) { this.remainedDuration = remainedDuration; } /** * The method decrements the attribute remainedDuration. That means, an * action needs less time to complete. * * @param decrement */ public void lowerRemainedDuration(final long decrement) { this.remainedDuration -= decrement; // System.out.println("AbstractAction.lowerRemainedDuration(): " + toString() + " " + actor.toString() + " noch offen: " + this.remainedDuration); if (this.remainedDuration <= 0) done = true; } /** * The method increments the attribute remainedDuration. That means, an * action needs more time to complete. * * @param increment */ public void raiseRemainedDuration(final long increment) { this.remainedDuration += increment; } @Override public String toString() { return "(" + this.type.toString() + ")"; //$NON-NLS-1$ } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////implementing IObjectSender<SUF> /////////////////////////////////////////////////////////////////////////////////////////// public int sendYourselfTo(IObjectReceiver receiver, int requestID) { return receiver.receiveObject(requestID, this); } public int sendYourselfTo(SimulationCluster cluster, IObjectReceiver receiver, int requestID) { return receiver.receiveObject(requestID, this); } public IObjectSender copy() { return this; } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////implementing IObjectReceiver /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// @Override public int receiveObject(int requestID, Object object) { objectRequester.receive(requestID, object); return 0; } }
13741_1
import java.util.Arrays; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * oplossing gebaseerd op de het levenshtein algoritme * oplossing gebaseerd op de code op volgende website: * https://www.baeldung.com/java-levenshtein-distance * * @author Wouter Vande Velde <[email protected]> */ public class Main { public static void main(String[] args) { Main gb = new Main(); gb.init(); } public void init () { Scanner scanner = new Scanner(System.in); int aantalTesten = Integer.parseInt(scanner.nextLine()); String correct, poging; for (int test = 0; test < aantalTesten; test++) { correct = scanner.nextLine(); poging = scanner.nextLine(); System.out.println(test +1 + " " +bereken(poging, correct)); } } int bereken(String x, String y) { // aantal foutpunten per character int[][] foutPunten = new int[x.length() + 1][y.length() + 1]; // overloop alle characters van beide strings en vergelijk ze met elkaar for (int i = 0; i <= x.length(); i++) { for (int j = 0; j <= y.length(); j++) { if (i == 0) { foutPunten[i][j] = 2*j; } else if (j == 0) { foutPunten[i][j] = 2*i; } else { // vergelijk de 2 karakters en kijk of het lager is, // als het niet lager is, is het sowieso een fout van 2 punten foutPunten[i][j] = min(foutPunten[i - 1][j - 1] + puntenFoutenVervanging(x.charAt(i - 1), y.charAt(j - 1)), foutPunten[i - 1][j] + 2, foutPunten[i][j - 1] + 2); } } } return foutPunten[x.length()][y.length()]; } /** * vergelijk 2 karakters en bepaal de punten * @param karakter1 * @param karakter2 * @return */ public static int puntenFoutenVervanging(char karakter1, char karakter2) { // ze zijn gelijk if (karakter1 == karakter2) { return 0 ; } // ze verschillen 32 van elkaar, van hoofdletter naar kleine if( karakter1+32 == karakter2 || karakter1-32 == karakter2) { // kijk of het wel een letter is if((karakter1 >64 && karakter1 <91) || (karakter1 >96 && karakter1 <123)){ return 1; } } // anders fout is 2 return 2; } public static int min(int... numbers) { return Arrays.stream(numbers) .min().orElse(Integer.MAX_VALUE); } }
wouter-vv/VlaamseProgrammeerWedstrijd
Dictee/src/Main.java
975
/** * oplossing gebaseerd op de het levenshtein algoritme * oplossing gebaseerd op de code op volgende website: * https://www.baeldung.com/java-levenshtein-distance * * @author Wouter Vande Velde <[email protected]> */
block_comment
nl
import java.util.Arrays; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * oplossing gebaseerd op<SUF>*/ public class Main { public static void main(String[] args) { Main gb = new Main(); gb.init(); } public void init () { Scanner scanner = new Scanner(System.in); int aantalTesten = Integer.parseInt(scanner.nextLine()); String correct, poging; for (int test = 0; test < aantalTesten; test++) { correct = scanner.nextLine(); poging = scanner.nextLine(); System.out.println(test +1 + " " +bereken(poging, correct)); } } int bereken(String x, String y) { // aantal foutpunten per character int[][] foutPunten = new int[x.length() + 1][y.length() + 1]; // overloop alle characters van beide strings en vergelijk ze met elkaar for (int i = 0; i <= x.length(); i++) { for (int j = 0; j <= y.length(); j++) { if (i == 0) { foutPunten[i][j] = 2*j; } else if (j == 0) { foutPunten[i][j] = 2*i; } else { // vergelijk de 2 karakters en kijk of het lager is, // als het niet lager is, is het sowieso een fout van 2 punten foutPunten[i][j] = min(foutPunten[i - 1][j - 1] + puntenFoutenVervanging(x.charAt(i - 1), y.charAt(j - 1)), foutPunten[i - 1][j] + 2, foutPunten[i][j - 1] + 2); } } } return foutPunten[x.length()][y.length()]; } /** * vergelijk 2 karakters en bepaal de punten * @param karakter1 * @param karakter2 * @return */ public static int puntenFoutenVervanging(char karakter1, char karakter2) { // ze zijn gelijk if (karakter1 == karakter2) { return 0 ; } // ze verschillen 32 van elkaar, van hoofdletter naar kleine if( karakter1+32 == karakter2 || karakter1-32 == karakter2) { // kijk of het wel een letter is if((karakter1 >64 && karakter1 <91) || (karakter1 >96 && karakter1 <123)){ return 1; } } // anders fout is 2 return 2; } public static int min(int... numbers) { return Arrays.stream(numbers) .min().orElse(Integer.MAX_VALUE); } }
48371_12
package com.eegeo.mapapi.camera; /** * Encapsulates optional parameters for performing a camera animation */ public class CameraAnimationOptions { /** * The duration of the animation, in seconds. */ public final double durationSeconds; /** * The speed of the animation, in meters per second. */ public final double preferredAnimationSpeed; /** * The minimum animation duration, in seconds */ public final double minDuration; /** * The maximum animation duration, in seconds */ public final double maxDuration; /** * The distance threshold, in meters, above which a camera animation will jump to its destination immediately. */ public final double snapDistanceThreshold; /** * True if the camera animation should jump to its destination for large distances. */ public final boolean snapIfDistanceExceedsThreshold; /** * True if a user touch gesture may interrupt the camera animation. */ public final boolean interruptByGestureAllowed; /** * @eegeo.internal */ public final boolean hasExplicitDuration; /** * @eegeo.internal */ public final boolean hasPreferredAnimationSpeed; /** * @eegeo.internal */ public final boolean hasMinDuration; /** * @eegeo.internal */ public final boolean hasMaxDuration; /** * @eegeo.internal */ public final boolean hasSnapDistanceThreshold; /** * @eegeo.internal */ private CameraAnimationOptions( double durationSeconds, double preferredAnimationSpeed, double minDuration, double maxDuration, double snapDistanceThreshold, boolean snapIfDistanceExceedsThreshold, boolean interruptByGestureAllowed, boolean hasExplicitDuration, boolean hasPreferredAnimationSpeed, boolean hasMinDuration, boolean hasMaxDuration, boolean hasSnapDistanceThreshold ) { this.durationSeconds = durationSeconds; this.preferredAnimationSpeed = preferredAnimationSpeed; this.minDuration = minDuration; this.maxDuration = maxDuration; this.snapDistanceThreshold = snapDistanceThreshold; this.snapIfDistanceExceedsThreshold = snapIfDistanceExceedsThreshold; this.interruptByGestureAllowed = interruptByGestureAllowed; this.hasExplicitDuration = hasExplicitDuration; this.hasPreferredAnimationSpeed = hasPreferredAnimationSpeed; this.hasMinDuration = hasMinDuration; this.hasMaxDuration = hasMaxDuration; this.hasSnapDistanceThreshold = hasSnapDistanceThreshold; } /** * A builder class for creating a CameraAnimationOptions instance. */ public static final class Builder { private double m_durationSeconds = 0.0; private double m_preferredAnimationSpeed = 0.0; private double m_minDuration = 0.0; private double m_maxDuration = 0.0; private double m_snapDistanceThreshold = 0.0; private boolean m_snapIfDistanceExceedsThreshold = true; private boolean m_interruptByGestureAllowed = true; private boolean m_hasExplicitDuration = false; private boolean m_hasPreferredAnimationSpeed = false; private boolean m_hasMinDuration = false; private boolean m_hasMaxDuration = false; private boolean m_hasSnapDistanceThreshold = false; /** * An explicit animation duration. If this method is not called, the resultant CameraAnimationOptions * will indicate that an appropriate duration should be automatically calculated based on the * distance of the camera transition. * @param durationSeconds The duration of the animation, in seconds. * @return */ public Builder duration(double durationSeconds) { m_durationSeconds = durationSeconds; m_hasExplicitDuration = true; return this; } /** * The preferred speed at which the camera target should travel, in meters per second. * If this method not called, the resultant CameraAnimationOptions will indicate that a default * speed should be used. * @param animationSpeedMetersPerSecond The speed of the animation, in meters per second. * @return */ public Builder preferredAnimationSpeed(double animationSpeedMetersPerSecond) { m_preferredAnimationSpeed = animationSpeedMetersPerSecond; m_hasPreferredAnimationSpeed = true; m_hasExplicitDuration = false; return this; } /** * Configure the options to immediately jump to the animation destination for distances * above a threshold. The default is True. * @param shouldSnap True if the camera animation should jump to its destination for large distances. * @return */ public Builder snapIfDistanceExceedsThreshold(boolean shouldSnap) { m_snapIfDistanceExceedsThreshold = shouldSnap; return this; } /** * Configure whether the animation may be interrupted by user touch gestures. The default is True. * @param isAllowed True if a user touch gesture may interrupt the camera animation. * @return */ public Builder interruptByGestureAllowed(boolean isAllowed) { m_interruptByGestureAllowed = isAllowed; return this; } /** * The minimum duration of the camera animation, if automatically calculated. The default is 1s. * @param minDuration The minimum animation duration, in seconds * @return */ public Builder minDuration(double minDuration) { m_minDuration = minDuration; m_hasMinDuration = true; return this; } /** * The maximum duration of the camera animation, if automatically calculated. The default is 5s. * @param maxDuration The maximum animation duration, in seconds * @return */ public Builder maxDuration(double maxDuration) { m_maxDuration = maxDuration; m_hasMaxDuration = true; return this; } /** * The distance threshold above which an animation will jump to its destination immediately. * The default is 5000m. * @param snapDistanceThresholdMeters The distance, in meters. * @return */ public Builder snapDistanceThreshold(double snapDistanceThresholdMeters) { m_snapDistanceThreshold = snapDistanceThresholdMeters; m_hasSnapDistanceThreshold = true; return this; } public Builder() { super(); } /** * Builds the CameraAnimationOptions object. * @return The final CameraAnimationOptions object. */ public CameraAnimationOptions build() { return new CameraAnimationOptions( m_durationSeconds, m_preferredAnimationSpeed, m_minDuration, m_maxDuration, m_snapDistanceThreshold, m_snapIfDistanceExceedsThreshold, m_interruptByGestureAllowed, m_hasExplicitDuration, m_hasPreferredAnimationSpeed, m_hasMinDuration, m_hasMaxDuration, m_hasSnapDistanceThreshold ); } } }
wrld3d/android-api
sdk/src/main/java/com/eegeo/mapapi/camera/CameraAnimationOptions.java
1,881
/** * @eegeo.internal */
block_comment
nl
package com.eegeo.mapapi.camera; /** * Encapsulates optional parameters for performing a camera animation */ public class CameraAnimationOptions { /** * The duration of the animation, in seconds. */ public final double durationSeconds; /** * The speed of the animation, in meters per second. */ public final double preferredAnimationSpeed; /** * The minimum animation duration, in seconds */ public final double minDuration; /** * The maximum animation duration, in seconds */ public final double maxDuration; /** * The distance threshold, in meters, above which a camera animation will jump to its destination immediately. */ public final double snapDistanceThreshold; /** * True if the camera animation should jump to its destination for large distances. */ public final boolean snapIfDistanceExceedsThreshold; /** * True if a user touch gesture may interrupt the camera animation. */ public final boolean interruptByGestureAllowed; /** * @eegeo.internal */ public final boolean hasExplicitDuration; /** * @eegeo.internal */ public final boolean hasPreferredAnimationSpeed; /** * @eegeo.internal */ public final boolean hasMinDuration; /** * @eegeo.internal */ public final boolean hasMaxDuration; /** * @eegeo.internal <SUF>*/ public final boolean hasSnapDistanceThreshold; /** * @eegeo.internal */ private CameraAnimationOptions( double durationSeconds, double preferredAnimationSpeed, double minDuration, double maxDuration, double snapDistanceThreshold, boolean snapIfDistanceExceedsThreshold, boolean interruptByGestureAllowed, boolean hasExplicitDuration, boolean hasPreferredAnimationSpeed, boolean hasMinDuration, boolean hasMaxDuration, boolean hasSnapDistanceThreshold ) { this.durationSeconds = durationSeconds; this.preferredAnimationSpeed = preferredAnimationSpeed; this.minDuration = minDuration; this.maxDuration = maxDuration; this.snapDistanceThreshold = snapDistanceThreshold; this.snapIfDistanceExceedsThreshold = snapIfDistanceExceedsThreshold; this.interruptByGestureAllowed = interruptByGestureAllowed; this.hasExplicitDuration = hasExplicitDuration; this.hasPreferredAnimationSpeed = hasPreferredAnimationSpeed; this.hasMinDuration = hasMinDuration; this.hasMaxDuration = hasMaxDuration; this.hasSnapDistanceThreshold = hasSnapDistanceThreshold; } /** * A builder class for creating a CameraAnimationOptions instance. */ public static final class Builder { private double m_durationSeconds = 0.0; private double m_preferredAnimationSpeed = 0.0; private double m_minDuration = 0.0; private double m_maxDuration = 0.0; private double m_snapDistanceThreshold = 0.0; private boolean m_snapIfDistanceExceedsThreshold = true; private boolean m_interruptByGestureAllowed = true; private boolean m_hasExplicitDuration = false; private boolean m_hasPreferredAnimationSpeed = false; private boolean m_hasMinDuration = false; private boolean m_hasMaxDuration = false; private boolean m_hasSnapDistanceThreshold = false; /** * An explicit animation duration. If this method is not called, the resultant CameraAnimationOptions * will indicate that an appropriate duration should be automatically calculated based on the * distance of the camera transition. * @param durationSeconds The duration of the animation, in seconds. * @return */ public Builder duration(double durationSeconds) { m_durationSeconds = durationSeconds; m_hasExplicitDuration = true; return this; } /** * The preferred speed at which the camera target should travel, in meters per second. * If this method not called, the resultant CameraAnimationOptions will indicate that a default * speed should be used. * @param animationSpeedMetersPerSecond The speed of the animation, in meters per second. * @return */ public Builder preferredAnimationSpeed(double animationSpeedMetersPerSecond) { m_preferredAnimationSpeed = animationSpeedMetersPerSecond; m_hasPreferredAnimationSpeed = true; m_hasExplicitDuration = false; return this; } /** * Configure the options to immediately jump to the animation destination for distances * above a threshold. The default is True. * @param shouldSnap True if the camera animation should jump to its destination for large distances. * @return */ public Builder snapIfDistanceExceedsThreshold(boolean shouldSnap) { m_snapIfDistanceExceedsThreshold = shouldSnap; return this; } /** * Configure whether the animation may be interrupted by user touch gestures. The default is True. * @param isAllowed True if a user touch gesture may interrupt the camera animation. * @return */ public Builder interruptByGestureAllowed(boolean isAllowed) { m_interruptByGestureAllowed = isAllowed; return this; } /** * The minimum duration of the camera animation, if automatically calculated. The default is 1s. * @param minDuration The minimum animation duration, in seconds * @return */ public Builder minDuration(double minDuration) { m_minDuration = minDuration; m_hasMinDuration = true; return this; } /** * The maximum duration of the camera animation, if automatically calculated. The default is 5s. * @param maxDuration The maximum animation duration, in seconds * @return */ public Builder maxDuration(double maxDuration) { m_maxDuration = maxDuration; m_hasMaxDuration = true; return this; } /** * The distance threshold above which an animation will jump to its destination immediately. * The default is 5000m. * @param snapDistanceThresholdMeters The distance, in meters. * @return */ public Builder snapDistanceThreshold(double snapDistanceThresholdMeters) { m_snapDistanceThreshold = snapDistanceThresholdMeters; m_hasSnapDistanceThreshold = true; return this; } public Builder() { super(); } /** * Builds the CameraAnimationOptions object. * @return The final CameraAnimationOptions object. */ public CameraAnimationOptions build() { return new CameraAnimationOptions( m_durationSeconds, m_preferredAnimationSpeed, m_minDuration, m_maxDuration, m_snapDistanceThreshold, m_snapIfDistanceExceedsThreshold, m_interruptByGestureAllowed, m_hasExplicitDuration, m_hasPreferredAnimationSpeed, m_hasMinDuration, m_hasMaxDuration, m_hasSnapDistanceThreshold ); } } }
23373_7
package nl.b3p.geotools.data.dxf.entities; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.text.MessageFormat; import java.util.regex.Pattern; import nl.b3p.geotools.data.GeometryType; import nl.b3p.geotools.data.dxf.parser.DXFUnivers; import nl.b3p.geotools.data.dxf.header.DXFLayer; import nl.b3p.geotools.data.dxf.header.DXFLineType; import nl.b3p.geotools.data.dxf.header.DXFTables; import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair; import nl.b3p.geotools.data.dxf.parser.DXFGroupCode; import nl.b3p.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DXFText extends DXFEntity { private static final Log log = LogFactory.getLog(DXFText.class); private Double x = null, y = null; public DXFText(DXFText newText) { this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0); setStartingLineNumber(newText.getStartingLineNumber()); setType(newText.getType()); setUnivers(newText.getUnivers()); } public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) { super(c, l , visibility, lineType, thickness); } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException { DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness); t.setUnivers(univers); t.setName(isMText ? "DXFMText" : "DXFText"); t.setTextrotation(0.0); t.setStartingLineNumber(br.getLineNumber()); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; // MTEXT direction vector Double directionX = null, directionY = null; String textposhor = "left"; String textposver = "bottom"; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: // geldt voor alle waarden van type br.reset(); doLoop = false; break; case X_1: //"10" t.setX(cvp.getDoubleValue()); break; case Y_1: //"20" t.setY(cvp.getDoubleValue()); break; case TEXT: //"1" t.setText(processOrStripTextCodes(cvp.getStringValue())); break; case ANGLE_1: //"50" t.setTextrotation(cvp.getDoubleValue()); break; case X_2: // 11, X-axis direction vector directionX = cvp.getDoubleValue(); break; case Y_2: // 21, Y-axis direction vector directionY = cvp.getDoubleValue(); break; case THICKNESS: //"39" t.setThickness(cvp.getDoubleValue()); break; case DOUBLE_1: //"40" t.setTextheight(cvp.getDoubleValue()); break; case INT_2: // 71: MTEXT attachment point switch(cvp.getShortValue()) { case 1: textposver = "top"; textposhor = "left"; break; case 2: textposver = "top"; textposhor = "center"; break; case 3: textposver = "top"; textposhor = "right"; break; case 4: textposver = "middle"; textposhor = "left"; break; case 5: textposver = "middle"; textposhor = "center"; break; case 6: textposver = "middle"; textposhor = "right"; break; case 7: textposver = "bottom"; textposhor = "left"; break; case 8: textposver = "bottom"; textposhor = "center"; break; case 9: textposver = "bottom"; textposhor = "right"; break; } break; case INT_3: // 72: TEXT horizontal text justification type // komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde switch(cvp.getShortValue()) { case 0: textposhor = "left"; break; case 1: textposhor = "center"; break; case 2: textposhor = "right"; break; case 3: // aligned case 4: // middle case 5: // fit // negeer, maar hier "center" van textposhor = "center"; } break; case INT_4: switch(cvp.getShortValue()) { case 0: textposver = "bottom"; break; // eigenlijk baseline case 1: textposver = "bottom"; break; case 2: textposver = "middle"; break; case 3: textposver = "top"; break; } break; case LAYER_NAME: //"8" t._refLayer = univers.findLayer(cvp.getStringValue()); break; case COLOR: //"62" t.setColor(cvp.getShortValue()); break; case VISIBILITY: //"60" t.setVisible(cvp.getShortValue() == 0); break; default: break; } } t.setTextposvertical(textposver); t.setTextposhorizontal(textposhor); if(isMText && directionX != null && directionY != null) { t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY)); if(log.isDebugEnabled()) { log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees", t.getStartingLineNumber(), t.getX(), t.getY(), directionX, directionY, t.getTextrotation())); } } t.setType(GeometryType.POINT); return t; } private static String processOrStripTextCodes(String text) { if(text == null) { return null; } // http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454 text = text.replaceAll("%%[cC]", "Ø"); text = text.replaceAll("\\\\[Pp]", "\r\n"); text = text.replaceAll("\\\\[Ll~]", ""); text = text.replaceAll(Pattern.quote("\\\\"), "\\"); text = text.replaceAll(Pattern.quote("\\{"), "{"); text = text.replaceAll(Pattern.quote("\\}"), "}"); text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", ""); return text; } private static double calculateRotationFromDirectionVector(double x, double y) { double rotation; // Hoek tussen vector (1,0) en de direction vector uit MText als theta: // arccos (theta) = inproduct(A,B) / lengte(A).lengte(B) // arccos (theta) = Bx / wortel(Bx^2 + By^2) // indien hoek in kwadrant III of IV, dan theta = -(theta-2PI) double length = Math.sqrt(x*x + y*y); if(length == 0) { rotation = 0; } else { double theta = Math.acos(x / length); if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) { theta = -(theta - 2*Math.PI); } // conversie van radialen naar graden rotation = theta * (180/Math.PI); if(Math.abs(360 - rotation) < 1e-4) { rotation = 0; } } return rotation; } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return geometry; } @Override public void updateGeometry() { if(x != null && y != null) { Coordinate c = rotateAndPlace(new Coordinate(x, y)); setGeometry(getUnivers().getGeometryFactory().createPoint(c)); } else { setGeometry(null); } } @Override public DXFEntity translate(double x, double y) { this.x += x; this.y += y; return this; } @Override public DXFEntity clone() { return new DXFText(this); //throw new UnsupportedOperationException(); } }
wscherphof/b3p-gt2-dxf
src/main/java/nl/b3p/geotools/data/dxf/entities/DXFText.java
2,844
// negeer, maar hier "center" van
line_comment
nl
package nl.b3p.geotools.data.dxf.entities; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.text.MessageFormat; import java.util.regex.Pattern; import nl.b3p.geotools.data.GeometryType; import nl.b3p.geotools.data.dxf.parser.DXFUnivers; import nl.b3p.geotools.data.dxf.header.DXFLayer; import nl.b3p.geotools.data.dxf.header.DXFLineType; import nl.b3p.geotools.data.dxf.header.DXFTables; import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair; import nl.b3p.geotools.data.dxf.parser.DXFGroupCode; import nl.b3p.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DXFText extends DXFEntity { private static final Log log = LogFactory.getLog(DXFText.class); private Double x = null, y = null; public DXFText(DXFText newText) { this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0); setStartingLineNumber(newText.getStartingLineNumber()); setType(newText.getType()); setUnivers(newText.getUnivers()); } public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) { super(c, l , visibility, lineType, thickness); } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException { DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness); t.setUnivers(univers); t.setName(isMText ? "DXFMText" : "DXFText"); t.setTextrotation(0.0); t.setStartingLineNumber(br.getLineNumber()); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; // MTEXT direction vector Double directionX = null, directionY = null; String textposhor = "left"; String textposver = "bottom"; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: // geldt voor alle waarden van type br.reset(); doLoop = false; break; case X_1: //"10" t.setX(cvp.getDoubleValue()); break; case Y_1: //"20" t.setY(cvp.getDoubleValue()); break; case TEXT: //"1" t.setText(processOrStripTextCodes(cvp.getStringValue())); break; case ANGLE_1: //"50" t.setTextrotation(cvp.getDoubleValue()); break; case X_2: // 11, X-axis direction vector directionX = cvp.getDoubleValue(); break; case Y_2: // 21, Y-axis direction vector directionY = cvp.getDoubleValue(); break; case THICKNESS: //"39" t.setThickness(cvp.getDoubleValue()); break; case DOUBLE_1: //"40" t.setTextheight(cvp.getDoubleValue()); break; case INT_2: // 71: MTEXT attachment point switch(cvp.getShortValue()) { case 1: textposver = "top"; textposhor = "left"; break; case 2: textposver = "top"; textposhor = "center"; break; case 3: textposver = "top"; textposhor = "right"; break; case 4: textposver = "middle"; textposhor = "left"; break; case 5: textposver = "middle"; textposhor = "center"; break; case 6: textposver = "middle"; textposhor = "right"; break; case 7: textposver = "bottom"; textposhor = "left"; break; case 8: textposver = "bottom"; textposhor = "center"; break; case 9: textposver = "bottom"; textposhor = "right"; break; } break; case INT_3: // 72: TEXT horizontal text justification type // komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde switch(cvp.getShortValue()) { case 0: textposhor = "left"; break; case 1: textposhor = "center"; break; case 2: textposhor = "right"; break; case 3: // aligned case 4: // middle case 5: // fit // negeer, maar<SUF> textposhor = "center"; } break; case INT_4: switch(cvp.getShortValue()) { case 0: textposver = "bottom"; break; // eigenlijk baseline case 1: textposver = "bottom"; break; case 2: textposver = "middle"; break; case 3: textposver = "top"; break; } break; case LAYER_NAME: //"8" t._refLayer = univers.findLayer(cvp.getStringValue()); break; case COLOR: //"62" t.setColor(cvp.getShortValue()); break; case VISIBILITY: //"60" t.setVisible(cvp.getShortValue() == 0); break; default: break; } } t.setTextposvertical(textposver); t.setTextposhorizontal(textposhor); if(isMText && directionX != null && directionY != null) { t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY)); if(log.isDebugEnabled()) { log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees", t.getStartingLineNumber(), t.getX(), t.getY(), directionX, directionY, t.getTextrotation())); } } t.setType(GeometryType.POINT); return t; } private static String processOrStripTextCodes(String text) { if(text == null) { return null; } // http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454 text = text.replaceAll("%%[cC]", "Ø"); text = text.replaceAll("\\\\[Pp]", "\r\n"); text = text.replaceAll("\\\\[Ll~]", ""); text = text.replaceAll(Pattern.quote("\\\\"), "\\"); text = text.replaceAll(Pattern.quote("\\{"), "{"); text = text.replaceAll(Pattern.quote("\\}"), "}"); text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", ""); return text; } private static double calculateRotationFromDirectionVector(double x, double y) { double rotation; // Hoek tussen vector (1,0) en de direction vector uit MText als theta: // arccos (theta) = inproduct(A,B) / lengte(A).lengte(B) // arccos (theta) = Bx / wortel(Bx^2 + By^2) // indien hoek in kwadrant III of IV, dan theta = -(theta-2PI) double length = Math.sqrt(x*x + y*y); if(length == 0) { rotation = 0; } else { double theta = Math.acos(x / length); if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) { theta = -(theta - 2*Math.PI); } // conversie van radialen naar graden rotation = theta * (180/Math.PI); if(Math.abs(360 - rotation) < 1e-4) { rotation = 0; } } return rotation; } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return geometry; } @Override public void updateGeometry() { if(x != null && y != null) { Coordinate c = rotateAndPlace(new Coordinate(x, y)); setGeometry(getUnivers().getGeometryFactory().createPoint(c)); } else { setGeometry(null); } } @Override public DXFEntity translate(double x, double y) { this.x += x; this.y += y; return this; } @Override public DXFEntity clone() { return new DXFText(this); //throw new UnsupportedOperationException(); } }
30175_34
/** * KAR Geo Tool - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * 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 Affero 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/>. */ package nl.b3p.kar.hibernate; import javax.persistence.*; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import javax.persistence.EntityManager; import javax.servlet.http.HttpServletRequest; import nl.b3p.kar.SecurityRealm; import org.hibernate.annotations.Sort; import org.hibernate.annotations.SortType; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Klasse voor definitie van een gebruiker * * @author Chris */ @Entity public class Gebruiker implements Principal { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; @Column(unique=true, nullable=false) private String username; private String passwordsalt; private String passwordhash; private String fullname; private String email; private String phone; private String position; /** * JSON string met profielinstellingen. */ @Column(columnDefinition="text") private String profile; @ManyToMany @JoinTable(name = "gebruiker_roles", joinColumns=@JoinColumn(name="gebruiker"), inverseJoinColumns=@JoinColumn(name="role")) private Set<Role> roles = new HashSet(); @OneToMany(mappedBy="gebruiker") @MapKeyJoinColumn(name="data_owner") @Sort(type=SortType.NATURAL) private SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights = new TreeMap<DataOwner, GebruikerDataOwnerRights>(); @OneToMany(mappedBy="gebruiker") private List<GebruikerVRIRights> vriRights = new ArrayList(); /** * Verandert het wachtwoord * * @param request nodig voor bepaling random salt * @param pw het wachtwoord * @throws NoSuchAlgorithmException The error * @throws UnsupportedEncodingException The error */ public void changePassword(HttpServletRequest request, String pw) throws NoSuchAlgorithmException, UnsupportedEncodingException { String salt = SecurityRealm.generateHexSalt(request); String hash = SecurityRealm.getHexSha1(salt, pw); setPasswordsalt(salt); setPasswordhash(hash); } /** * Zoekt de huidige gebruiker * * @param request waarin gebruiker is te vinden * @return getter de gebruiker * @throws Exception The error */ public static Gebruiker getNonTransientPrincipal(HttpServletRequest request) throws Exception { Gebruiker g = (Gebruiker)request.getUserPrincipal(); if(g == null) { return null; } return Stripersist.getEntityManager().find(Gebruiker.class, g.getId()); } /** * Haalt id van gebruiker op * * @return getter id */ public Integer getId() { return id; } /** * * @param id setter */ public void setId(Integer id) { this.id = id; } /** * Haalt gebruikersnaam op * * @return getter username */ public String getUsername() { return username; } /** * * @param username setter */ public void setUsername(String username) { this.username = username; } /** * * @return getter passwordsalt */ public String getPasswordsalt() { return passwordsalt; } /** * * @param passwordSalt setter */ public void setPasswordsalt(String passwordSalt) { this.passwordsalt = passwordSalt; } /** * * @return getter passwordhash */ public String getPasswordhash() { return passwordhash; } /** * * @param passwordhash setter */ public void setPasswordhash(String passwordhash) { this.passwordhash = passwordhash; } /** * Principal implementatie */ public String getName() { return getUsername(); } /** * * @return getter fullname */ public String getFullname() { return fullname; } /** * * @param fullname setter */ public void setFullname(String fullname) { this.fullname = fullname; } /** * * @return getter email */ public String getEmail() { return email; } /** * * @param email setter */ public void setEmail(String email) { this.email = email; } /** * * @return getter phone */ public String getPhone() { return phone; } /** * * @param phone setter */ public void setPhone(String phone) { this.phone = phone; } /** * * @return getter position */ public String getPosition() { return position; } /** * * @param position setter */ public void setPosition(String position) { this.position = position; } /** * * @return getter roles */ public Set<Role> getRoles() { return roles; } /** * * @param roles setter */ public void setRoles(Set<Role> roles) { this.roles = roles; } /** * * @return getter profile */ public String getProfile() { return profile; } /** * * @param profile setter */ public void setProfile(String profile) { this.profile = profile; } /** * * @return getter is gebruiker beheerder? */ public boolean isBeheerder() { return isInRole(Role.BEHEERDER); } /** * * @return getter */ public boolean isVervoerder(){ return isInRole(Role.VERVOERDER); } /** * * @param roleName roleName * @return getter heeft gebruiker de gevraagde rol? */ public boolean isInRole(String roleName) { for(Iterator it = getRoles().iterator(); it.hasNext();) { Role r = (Role)it.next(); if(r.getRole().equals(roleName)) { return true; } } return false; } /** * * @return getter dataOwnerRights */ public Map<DataOwner, GebruikerDataOwnerRights> getDataOwnerRights() { return dataOwnerRights; } /** * * @param dataOwnerRights setter */ public void setDataOwnerRights(SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights) { this.dataOwnerRights = dataOwnerRights; } /** * * @return getter */ public List<GebruikerVRIRights> getVriRights() { return vriRights; } /** * * @param vriRights setter */ public void setVriRights(List<GebruikerVRIRights> vriRights) { this.vriRights = vriRights; } /** * Lijst van van data owners die gebruiker met gebruiker role mag lezen (bij * beheerder/vervoerder worden NIET alle data owners teruggegeven). Een * dataOwnerRights record betekent altijd lezen of schrijven, nooit kan * editable en readable beide false zijn. * @return getter */ public Set<DataOwner> getReadableDataOwners() { return dataOwnerRights.keySet(); } /** * Lijst van van data owners die gebruiker met gebruiker role mag bewerken (bij * beheerder role worden NIET alle data owners teruggegeven). * @return getter */ public Set<DataOwner> getEditableDataOwners() { HashSet<DataOwner> dataOwners = new HashSet<DataOwner>(); for (Entry<DataOwner, GebruikerDataOwnerRights> entry : dataOwnerRights.entrySet()) { if(entry.getValue().isEditable()) { dataOwners.add(entry.getValue().getDataOwner()); } } return dataOwners; } /** * Gebruiker kan RoadsideEquipment editen als: * - Gebruiker beheerder is, of * - Gebruiker DataOwner kan editen, of * - Gebruiker VRI kan editen. * * Vervoerders kunnen nooit editen, ook al staan in de database DataOwner/VRI * rechten (zou GUI niet mogelijk moeten maken). * @param rseq rseq * @return getter */ public boolean canEdit(RoadsideEquipment rseq) { if(isBeheerder()) { return true; } if(isVervoerder()) { return false; } DataOwner d = rseq.getDataOwner(); if(d != null) { GebruikerDataOwnerRights r = dataOwnerRights.get(d); if(r != null && r.isEditable()) { return true; } } Long rseqId = rseq.getId(); if(rseqId != null) { for(GebruikerVRIRights gebruikerVRIRights : vriRights) { if(gebruikerVRIRights.isEditable()) { if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) { return true; } } } } return false; } /** * Gebruiker kan RoadsideEquipment lezen als: * - Gebruiker is beheerder, of * - Gebruiker is vervoerder, of * - Gebruiker heeft GebruikerDataOwnerRights record voor DAO van RSEQ, of * - Gebruiker heeft GebruikerVRIRights record voor RSEQ. * * Een DataOwner recht of VRI recht bij een gebruiker betekent altijd mimimaal * leesrecht. Readable=false en editable=false bij rights records zouden niet * in db moeten kunnen staan. Hier wordt gebruik van gemaakt bij zoekacties. * @param rseq rseq * @return getter */ public boolean canRead(RoadsideEquipment rseq) { if(isBeheerder() || isVervoerder()) { return true; } DataOwner d = rseq.getDataOwner(); if(d != null) { GebruikerDataOwnerRights r = dataOwnerRights.get(d); if(r != null) { // Geen test op isEditable() of isReadable() nodig, een van beide // is voldoende maar zouden nooit met allebei false in database // moeten staan return true; } } Long rseqId = rseq.getId(); if(rseqId != null) { for(GebruikerVRIRights gebruikerVRIRights: vriRights) { // Geen test op isEditable() of isReadable() nodig, een van beide // is voldoende maar zouden nooit met allebei false in database // moeten staan if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) { return true; } } } return false; } /** * Zet de rechten mbt de DataOwner * @param dao het dataowner object * @param editable mag geedit worden * @param readable mag gelezen worden * @throws Exception The error */ public void setDataOwnerRight(DataOwner dao, Boolean editable, Boolean readable) throws Exception { EntityManager em = Stripersist.getEntityManager(); GebruikerDataOwnerRights dor = getDataOwnerRights().get(dao); if(dor == null) { dor = new GebruikerDataOwnerRights(); dor.setDataOwner(dao); dor.setGebruiker(this); em.persist(dor); getDataOwnerRights().put(dao, dor); } if(editable != null) { dor.setEditable(editable); } if(readable != null) { dor.setReadable(readable); } } /** * * @return getter * @throws JSONException The error */ public JSONObject toJSON() throws JSONException{ JSONObject obj = new JSONObject(); obj.put("id", id); obj.put("username", username); obj.put("fullname", fullname); obj.put("mail", email); obj.put("phone", phone); return obj; } @Override public String toString(){ return username + " (" +fullname + ")"; } }
wscherphof/kargeotool
src/main/java/nl/b3p/kar/hibernate/Gebruiker.java
4,161
/** * Lijst van van data owners die gebruiker met gebruiker role mag bewerken (bij * beheerder role worden NIET alle data owners teruggegeven). * @return getter */
block_comment
nl
/** * KAR Geo Tool - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * 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 Affero 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/>. */ package nl.b3p.kar.hibernate; import javax.persistence.*; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import javax.persistence.EntityManager; import javax.servlet.http.HttpServletRequest; import nl.b3p.kar.SecurityRealm; import org.hibernate.annotations.Sort; import org.hibernate.annotations.SortType; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Klasse voor definitie van een gebruiker * * @author Chris */ @Entity public class Gebruiker implements Principal { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; @Column(unique=true, nullable=false) private String username; private String passwordsalt; private String passwordhash; private String fullname; private String email; private String phone; private String position; /** * JSON string met profielinstellingen. */ @Column(columnDefinition="text") private String profile; @ManyToMany @JoinTable(name = "gebruiker_roles", joinColumns=@JoinColumn(name="gebruiker"), inverseJoinColumns=@JoinColumn(name="role")) private Set<Role> roles = new HashSet(); @OneToMany(mappedBy="gebruiker") @MapKeyJoinColumn(name="data_owner") @Sort(type=SortType.NATURAL) private SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights = new TreeMap<DataOwner, GebruikerDataOwnerRights>(); @OneToMany(mappedBy="gebruiker") private List<GebruikerVRIRights> vriRights = new ArrayList(); /** * Verandert het wachtwoord * * @param request nodig voor bepaling random salt * @param pw het wachtwoord * @throws NoSuchAlgorithmException The error * @throws UnsupportedEncodingException The error */ public void changePassword(HttpServletRequest request, String pw) throws NoSuchAlgorithmException, UnsupportedEncodingException { String salt = SecurityRealm.generateHexSalt(request); String hash = SecurityRealm.getHexSha1(salt, pw); setPasswordsalt(salt); setPasswordhash(hash); } /** * Zoekt de huidige gebruiker * * @param request waarin gebruiker is te vinden * @return getter de gebruiker * @throws Exception The error */ public static Gebruiker getNonTransientPrincipal(HttpServletRequest request) throws Exception { Gebruiker g = (Gebruiker)request.getUserPrincipal(); if(g == null) { return null; } return Stripersist.getEntityManager().find(Gebruiker.class, g.getId()); } /** * Haalt id van gebruiker op * * @return getter id */ public Integer getId() { return id; } /** * * @param id setter */ public void setId(Integer id) { this.id = id; } /** * Haalt gebruikersnaam op * * @return getter username */ public String getUsername() { return username; } /** * * @param username setter */ public void setUsername(String username) { this.username = username; } /** * * @return getter passwordsalt */ public String getPasswordsalt() { return passwordsalt; } /** * * @param passwordSalt setter */ public void setPasswordsalt(String passwordSalt) { this.passwordsalt = passwordSalt; } /** * * @return getter passwordhash */ public String getPasswordhash() { return passwordhash; } /** * * @param passwordhash setter */ public void setPasswordhash(String passwordhash) { this.passwordhash = passwordhash; } /** * Principal implementatie */ public String getName() { return getUsername(); } /** * * @return getter fullname */ public String getFullname() { return fullname; } /** * * @param fullname setter */ public void setFullname(String fullname) { this.fullname = fullname; } /** * * @return getter email */ public String getEmail() { return email; } /** * * @param email setter */ public void setEmail(String email) { this.email = email; } /** * * @return getter phone */ public String getPhone() { return phone; } /** * * @param phone setter */ public void setPhone(String phone) { this.phone = phone; } /** * * @return getter position */ public String getPosition() { return position; } /** * * @param position setter */ public void setPosition(String position) { this.position = position; } /** * * @return getter roles */ public Set<Role> getRoles() { return roles; } /** * * @param roles setter */ public void setRoles(Set<Role> roles) { this.roles = roles; } /** * * @return getter profile */ public String getProfile() { return profile; } /** * * @param profile setter */ public void setProfile(String profile) { this.profile = profile; } /** * * @return getter is gebruiker beheerder? */ public boolean isBeheerder() { return isInRole(Role.BEHEERDER); } /** * * @return getter */ public boolean isVervoerder(){ return isInRole(Role.VERVOERDER); } /** * * @param roleName roleName * @return getter heeft gebruiker de gevraagde rol? */ public boolean isInRole(String roleName) { for(Iterator it = getRoles().iterator(); it.hasNext();) { Role r = (Role)it.next(); if(r.getRole().equals(roleName)) { return true; } } return false; } /** * * @return getter dataOwnerRights */ public Map<DataOwner, GebruikerDataOwnerRights> getDataOwnerRights() { return dataOwnerRights; } /** * * @param dataOwnerRights setter */ public void setDataOwnerRights(SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights) { this.dataOwnerRights = dataOwnerRights; } /** * * @return getter */ public List<GebruikerVRIRights> getVriRights() { return vriRights; } /** * * @param vriRights setter */ public void setVriRights(List<GebruikerVRIRights> vriRights) { this.vriRights = vriRights; } /** * Lijst van van data owners die gebruiker met gebruiker role mag lezen (bij * beheerder/vervoerder worden NIET alle data owners teruggegeven). Een * dataOwnerRights record betekent altijd lezen of schrijven, nooit kan * editable en readable beide false zijn. * @return getter */ public Set<DataOwner> getReadableDataOwners() { return dataOwnerRights.keySet(); } /** * Lijst van van<SUF>*/ public Set<DataOwner> getEditableDataOwners() { HashSet<DataOwner> dataOwners = new HashSet<DataOwner>(); for (Entry<DataOwner, GebruikerDataOwnerRights> entry : dataOwnerRights.entrySet()) { if(entry.getValue().isEditable()) { dataOwners.add(entry.getValue().getDataOwner()); } } return dataOwners; } /** * Gebruiker kan RoadsideEquipment editen als: * - Gebruiker beheerder is, of * - Gebruiker DataOwner kan editen, of * - Gebruiker VRI kan editen. * * Vervoerders kunnen nooit editen, ook al staan in de database DataOwner/VRI * rechten (zou GUI niet mogelijk moeten maken). * @param rseq rseq * @return getter */ public boolean canEdit(RoadsideEquipment rseq) { if(isBeheerder()) { return true; } if(isVervoerder()) { return false; } DataOwner d = rseq.getDataOwner(); if(d != null) { GebruikerDataOwnerRights r = dataOwnerRights.get(d); if(r != null && r.isEditable()) { return true; } } Long rseqId = rseq.getId(); if(rseqId != null) { for(GebruikerVRIRights gebruikerVRIRights : vriRights) { if(gebruikerVRIRights.isEditable()) { if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) { return true; } } } } return false; } /** * Gebruiker kan RoadsideEquipment lezen als: * - Gebruiker is beheerder, of * - Gebruiker is vervoerder, of * - Gebruiker heeft GebruikerDataOwnerRights record voor DAO van RSEQ, of * - Gebruiker heeft GebruikerVRIRights record voor RSEQ. * * Een DataOwner recht of VRI recht bij een gebruiker betekent altijd mimimaal * leesrecht. Readable=false en editable=false bij rights records zouden niet * in db moeten kunnen staan. Hier wordt gebruik van gemaakt bij zoekacties. * @param rseq rseq * @return getter */ public boolean canRead(RoadsideEquipment rseq) { if(isBeheerder() || isVervoerder()) { return true; } DataOwner d = rseq.getDataOwner(); if(d != null) { GebruikerDataOwnerRights r = dataOwnerRights.get(d); if(r != null) { // Geen test op isEditable() of isReadable() nodig, een van beide // is voldoende maar zouden nooit met allebei false in database // moeten staan return true; } } Long rseqId = rseq.getId(); if(rseqId != null) { for(GebruikerVRIRights gebruikerVRIRights: vriRights) { // Geen test op isEditable() of isReadable() nodig, een van beide // is voldoende maar zouden nooit met allebei false in database // moeten staan if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) { return true; } } } return false; } /** * Zet de rechten mbt de DataOwner * @param dao het dataowner object * @param editable mag geedit worden * @param readable mag gelezen worden * @throws Exception The error */ public void setDataOwnerRight(DataOwner dao, Boolean editable, Boolean readable) throws Exception { EntityManager em = Stripersist.getEntityManager(); GebruikerDataOwnerRights dor = getDataOwnerRights().get(dao); if(dor == null) { dor = new GebruikerDataOwnerRights(); dor.setDataOwner(dao); dor.setGebruiker(this); em.persist(dor); getDataOwnerRights().put(dao, dor); } if(editable != null) { dor.setEditable(editable); } if(readable != null) { dor.setReadable(readable); } } /** * * @return getter * @throws JSONException The error */ public JSONObject toJSON() throws JSONException{ JSONObject obj = new JSONObject(); obj.put("id", id); obj.put("username", username); obj.put("fullname", fullname); obj.put("mail", email); obj.put("phone", phone); return obj; } @Override public String toString(){ return username + " (" +fullname + ")"; } }
32843_52
/* * 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.axiom.om.impl.dom; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMOutputFormat; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.MTOMXMLStreamWriter; import org.apache.axiom.om.impl.OMNodeEx; import org.apache.axiom.om.impl.builder.StAXBuilder; import org.apache.axiom.om.util.StAXUtils; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.OutputStream; import java.io.Writer; import java.util.Hashtable; public abstract class NodeImpl implements Node, NodeList, OMNodeEx, Cloneable { /** Holds the user data objects */ private Hashtable userData; // Will be initialized in setUserData() /** Field builder */ public OMXMLParserWrapper builder; /** Field done */ protected boolean done = false; protected DocumentImpl ownerNode; /** Factory that created this node */ protected final OMFactory factory; // data protected short flags; protected final static short OWNED = 0x1 << 1; protected final static short FIRSTCHILD = 0x1 << 2; protected final static short READONLY = 0x1 << 3; protected final static short SPECIFIED = 0x1 << 4; protected final static short NORMALIZED = 0x1 << 5; // // Constructors // protected NodeImpl(DocumentImpl ownerDocument, OMFactory factory) { //this(factory); this.factory = factory; this.ownerNode = ownerDocument; // this.isOwned(true); } protected NodeImpl(OMFactory factory) { this.factory = factory; } public void normalize() { //Parent node should override this } public boolean hasAttributes() { return false; // overridden in ElementImpl } public boolean hasChildNodes() { return false; // Override in ParentNode } public String getLocalName() { return null; // Override in AttrImpl and ElementImpl } public String getNamespaceURI() { return null; // Override in AttrImpl and ElementImpl } public String getNodeValue() throws DOMException { return null; } /* * Overidden in ElementImpl and AttrImpl. */ public String getPrefix() { return null; } public void setNodeValue(String arg0) throws DOMException { // Don't do anything, to be overridden in SOME Child classes } public void setPrefix(String prefix) throws DOMException { throw new DOMException(DOMException.NAMESPACE_ERR, DOMMessageFormatter .formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NAMESPACE_ERR, null)); } /** * Finds the document that this Node belongs to (the document in whose context the Node was * created). The Node may or may not */ public Document getOwnerDocument() { return this.ownerNode; } /** * Returns the collection of attributes associated with this node, or null if none. At this * writing, Element is the only type of node which will ever have attributes. * * @see ElementImpl */ public NamedNodeMap getAttributes() { return null; // overridden in ElementImpl } /** * Gets the first child of this Node, or null if none. * <p/> * By default we do not have any children, ParentNode overrides this. * * @see ParentNode */ public Node getFirstChild() { return null; } /** * Gets the last child of this Node, or null if none. * <p/> * By default we do not have any children, ParentNode overrides this. * * @see ParentNode */ public Node getLastChild() { return null; } /** Returns the next child of this node's parent, or null if none. */ public Node getNextSibling() { return null; // default behavior, overriden in ChildNode } public Node getParentNode() { return null; // overriden by ChildNode // Document, DocumentFragment, and Attribute will never have parents. } /* * Same as getParentNode but returns internal type NodeImpl. */ NodeImpl parentNode() { return null; } /** Returns the previous child of this node's parent, or null if none. */ public Node getPreviousSibling() { return null; // default behavior, overriden in ChildNode } // public Node cloneNode(boolean deep) { // if(this instanceof OMElement) { // return (Node)((OMElement)this).cloneOMElement(); // } else if(this instanceof OMText ){ // return ((TextImpl)this).cloneText(); // } else { // throw new UnsupportedOperationException("Only elements can be cloned // right now"); // } // } // public Node cloneNode(boolean deep) { NodeImpl newnode; try { newnode = (NodeImpl) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("**Internal Error**" + e); } newnode.ownerNode = this.ownerNode; newnode.isOwned(false); newnode.isReadonly(false); return newnode; } /* * (non-Javadoc) * * @see org.w3c.dom.Node#getChildNodes() */ public NodeList getChildNodes() { return this; } public boolean isSupported(String feature, String version) { throw new UnsupportedOperationException(); // TODO } /* * (non-Javadoc) * * @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node) */ public Node appendChild(Node newChild) throws DOMException { return insertBefore(newChild, null); } /* * (non-Javadoc) * * @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node) */ public Node removeChild(Node oldChild) throws DOMException { throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter .formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_FOUND_ERR, null)); } /* * (non-Javadoc) * * @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node insertBefore(Node newChild, Node refChild) throws DOMException { // Overridden in ParentNode throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /* * (non-Javadoc) * * @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node replaceChild(Node newChild, Node oldChild) throws DOMException { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } // // NodeList methods // /** * NodeList method: Returns the number of immediate children of this node. * <p/> * By default we do not have any children, ParentNode overrides this. * * @return Returns int. * @see ParentNode */ public int getLength() { return 0; } /** * NodeList method: Returns the Nth immediate child of this node, or null if the index is out of * bounds. * <p/> * By default we do not have any children, ParentNode overrides this. * * @param index * @return Returns org.w3c.dom.Node * @see ParentNode */ public Node item(int index) { return null; } /* * Flags setters and getters */ final boolean isOwned() { return (flags & OWNED) != 0; } final void isOwned(boolean value) { flags = (short) (value ? flags | OWNED : flags & ~OWNED); } final boolean isFirstChild() { return (flags & FIRSTCHILD) != 0; } final void isFirstChild(boolean value) { flags = (short) (value ? flags | FIRSTCHILD : flags & ~FIRSTCHILD); } final boolean isReadonly() { return (flags & READONLY) != 0; } final void isReadonly(boolean value) { flags = (short) (value ? flags | READONLY : flags & ~READONLY); } final boolean isSpecified() { return (flags & SPECIFIED) != 0; } final void isSpecified(boolean value) { flags = (short) (value ? flags | SPECIFIED : flags & ~SPECIFIED); } final boolean isNormalized() { return (flags & NORMALIZED) != 0; } final void isNormalized(boolean value) { // See if flag should propagate to parent. if (!value && isNormalized() && ownerNode != null) { ownerNode.isNormalized(false); } flags = (short) (value ? flags | NORMALIZED : flags & ~NORMALIZED); } // / // /OM Methods // / /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#getParent() */ public OMContainer getParent() throws OMException { return null; // overriden by ChildNode // Document, DocumentFragment, and Attribute will never have parents. } /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#isComplete() */ public boolean isComplete() { return this.done; } public void setComplete(boolean state) { this.done = state; } /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#insertSiblingAfter * (org.apache.axis2.om.OMNode) */ public void insertSiblingAfter(OMNode sibling) throws OMException { // Overridden in ChildNode throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#insertSiblingBefore * (org.apache.axis2.om.OMNode) */ public void insertSiblingBefore(OMNode sibling) throws OMException { // Overridden in ChildNode throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /** Default behavior returns null, overriden in ChildNode. */ public OMNode getPreviousOMSibling() { return null; } /** Default behavior returns null, overriden in ChildNode. */ public OMNode getNextOMSibling() { return null; } public OMNode getNextOMSiblingIfAvailable() { return null; } public void setPreviousOMSibling(OMNode previousSibling) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } public void setNextOMSibling(OMNode previousSibling) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /** Builds next element. */ public void build() { while (!done) this.builder.next(); } /** * Parses this node and builds the object structure in memory. AXIOM supports two levels of * deffered building. First is deffered building of AXIOM using StAX. Second level is the deffered * building of attachments. AXIOM reads in the attachements from the stream only when user asks by * calling getDataHandler(). build() method builds the OM without the attachments. buildAll() * builds the OM together with attachement data. This becomes handy when user wants to free the * input stream. */ public void buildWithAttachments() { if (!this.done) { this.build(); } } public void close(boolean build) { if (build) { this.build(); } this.done = true; // If this is a StAXBuilder, close it. if (builder instanceof StAXBuilder && !((StAXBuilder) builder).isClosed()) { ((StAXBuilder) builder).releaseParserOnClose(true); ((StAXBuilder) builder).close(); } } /** * Sets the owner document. * * @param document */ protected void setOwnerDocument(DocumentImpl document) { this.ownerNode = document; this.isOwned(true); } public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException { serialize(xmlWriter, true); } public void serializeAndConsume(XMLStreamWriter xmlWriter) throws XMLStreamException { serialize(xmlWriter, false); } public void serialize(XMLStreamWriter xmlWriter, boolean cache) throws XMLStreamException { MTOMXMLStreamWriter writer = xmlWriter instanceof MTOMXMLStreamWriter ? (MTOMXMLStreamWriter) xmlWriter : new MTOMXMLStreamWriter(xmlWriter); internalSerialize(writer, cache); writer.flush(); } public OMNode detach() { throw new OMException( "Elements that doesn't have a parent can not be detached"); } /* * DOM-Level 3 methods */ public String getBaseURI() { // TODO TODO throw new UnsupportedOperationException("TODO"); } public short compareDocumentPosition(Node other) throws DOMException { // This is not yet implemented. In the meantime, we throw a DOMException // and not an UnsupportedOperationException, since this works better with // some other libraries (such as Saxon 8.9). throw new DOMException(DOMException.NOT_SUPPORTED_ERR, DOMMessageFormatter .formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_SUPPORTED_ERR, null)); } public String getTextContent() throws DOMException { return getNodeValue(); // overriden in some subclasses } // internal method taking a StringBuffer in parameter void getTextContent(StringBuffer buf) throws DOMException { String content = getNodeValue(); if (content != null) { buf.append(content); } } public void setTextContent(String textContent) throws DOMException { setNodeValue(textContent); // overriden in some subclasses } public boolean isSameNode(Node node) { // TODO : check return this == node; } public String lookupPrefix(String arg0) { // TODO TODO throw new UnsupportedOperationException("TODO"); } public boolean isDefaultNamespace(String arg0) { // TODO TODO throw new UnsupportedOperationException("TODO"); } public String lookupNamespaceURI(String arg0) { // TODO TODO throw new UnsupportedOperationException("TODO"); } /** * Tests whether two nodes are equal. <br>This method tests for equality of nodes, not sameness * (i.e., whether the two nodes are references to the same object) which can be tested with * <code>Node.isSameNode()</code>. All nodes that are the same will also be equal, though the * reverse may not be true. <br>Two nodes are equal if and only if the following conditions are * satisfied: <ul> <li>The two nodes are of the same type. </li> <li>The following string * attributes are equal: <code>nodeName</code>, <code>localName</code>, * <code>namespaceURI</code>, <code>prefix</code>, <code>nodeValue</code> . This is: they are * both <code>null</code>, or they have the same length and are character for character * identical. </li> <li>The <code>attributes</code> <code>NamedNodeMaps</code> are equal. This * is: they are both <code>null</code>, or they have the same length and for each node that * exists in one map there is a node that exists in the other map and is equal, although not * necessarily at the same index. </li> <li>The <code>childNodes</code> <code>NodeLists</code> * are equal. This is: they are both <code>null</code>, or they have the same length and contain * equal nodes at the same index. Note that normalization can affect equality; to avoid this, * nodes should be normalized before being compared. </li> </ul> <br>For two * <code>DocumentType</code> nodes to be equal, the following conditions must also be satisfied: * <ul> <li>The following string attributes are equal: <code>publicId</code>, * <code>systemId</code>, <code>internalSubset</code>. </li> <li>The <code>entities</code> * <code>NamedNodeMaps</code> are equal. </li> <li>The <code>notations</code> * <code>NamedNodeMaps</code> are equal. </li> </ul> <br>On the other hand, the following do not * affect equality: the <code>ownerDocument</code>, <code>baseURI</code>, and * <code>parentNode</code> attributes, the <code>specified</code> attribute for * <code>Attr</code> nodes, the <code>schemaTypeInfo</code> attribute for <code>Attr</code> and * <code>Element</code> nodes, the <code>Text.isElementContentWhitespace</code> attribute for * <code>Text</code> nodes, as well as any user data or event listeners registered on the nodes. * <p ><b>Note:</b> As a general rule, anything not mentioned in the description above is not * significant in consideration of equality checking. Note that future versions of this * specification may take into account more attributes and implementations conform to this * specification are expected to be updated accordingly. * * @param node The node to compare equality with. * @return Returns <code>true</code> if the nodes are equal, <code>false</code> otherwise. * @since DOM Level 3 */ //TODO : sumedha, complete public boolean isEqualNode(Node node) { final boolean equal = true; final boolean notEqual = false; if (this.getNodeType() != node.getNodeType()) { return notEqual; } if (checkStringAttributeEquality(node)) { if (checkNamedNodeMapEquality(node)) { } else { return notEqual; } } else { return notEqual; } return equal; } private boolean checkStringAttributeEquality(Node node) { final boolean equal = true; final boolean notEqual = false; // null not-null -> true // not-null null -> true // null null -> false // not-null not-null -> false //NodeName if (node.getNodeName() == null ^ this.getNodeName() == null) { return notEqual; } else { if (node.getNodeName() == null) { //This means both are null.do nothing } else { if (!(node.getNodeName().equals(this.getNodeName()))) { return notEqual; } } } //localName if (node.getLocalName() == null ^ this.getLocalName() == null) { return notEqual; } else { if (node.getLocalName() == null) { //This means both are null.do nothing } else { if (!(node.getLocalName().equals(this.getLocalName()))) { return notEqual; } } } //namespaceURI if (node.getNamespaceURI() == null ^ this.getNamespaceURI() == null) { return notEqual; } else { if (node.getNamespaceURI() == null) { //This means both are null.do nothing } else { if (!(node.getNamespaceURI().equals(this.getNamespaceURI()))) { return notEqual; } } } //prefix if (node.getPrefix() == null ^ this.getPrefix() == null) { return notEqual; } else { if (node.getPrefix() == null) { //This means both are null.do nothing } else { if (!(node.getPrefix().equals(this.getPrefix()))) { return notEqual; } } } //nodeValue if (node.getNodeValue() == null ^ this.getNodeValue() == null) { return notEqual; } else { if (node.getNodeValue() == null) { //This means both are null.do nothing } else { if (!(node.getNodeValue().equals(this.getNodeValue()))) { return notEqual; } } } return equal; } private boolean checkNamedNodeMapEquality(Node node) { final boolean equal = true; final boolean notEqual = false; if (node.getAttributes() == null ^ this.getAttributes() == null) { return notEqual; } NamedNodeMap thisNamedNodeMap = this.getAttributes(); NamedNodeMap nodeNamedNodeMap = node.getAttributes(); // null not-null -> true // not-null null -> true // null null -> false // not-null not-null -> false if (thisNamedNodeMap == null ^ nodeNamedNodeMap == null) { return notEqual; } else { if (thisNamedNodeMap == null) { //This means both are null.do nothing } else { if (thisNamedNodeMap.getLength() != nodeNamedNodeMap.getLength()) { return notEqual; } else { //they have the same length and for each node that exists in one map //there is a node that exists in the other map and is equal, although //not necessarily at the same index. int itemCount = thisNamedNodeMap.getLength(); for (int a = 0; a < itemCount; a++) { NodeImpl thisNode = (NodeImpl) thisNamedNodeMap.item(a); NodeImpl tmpNode = (NodeImpl) nodeNamedNodeMap.getNamedItem(thisNode.getNodeName()); if (tmpNode == null) { //i.e. no corresponding node return notEqual; } else { if (!(thisNode.isEqualNode(tmpNode))) { return notEqual; } } } } } } return equal; } public Object getFeature(String arg0, String arg1) { // TODO TODO throw new UnsupportedOperationException("TODO"); } /* * * userData storage/hashtable will be called only when the user needs to set user data. Previously, it was done as, * for every node a new Hashtable created making the excution very inefficient. According to profiles, no. of method * invocations to setUserData() method is very low, so this implementation is better. * Another option: * TODO do a profile and check the times for hashtable initialization. If it's still higher, we have to go to second option * Create a separate class(UserData) to store key and value pairs. Then put those objects to a array with a reasonable size. * then grow it accordingly. @ Kasun Gajasinghe * @param key userData key * @param value userData value * @param userDataHandler it seems all invocations sends null for this parameter. * Kept it for the moment just for being on the safe side. * @return previous Object if one is set before. */ public Object setUserData(String key, Object value, UserDataHandler userDataHandler) { if (userData == null) { userData = new Hashtable(); } return userData.put(key, value); } public Object getUserData(String key) { if (userData != null) { return userData.get(key); } return null; } public void serialize(OutputStream output) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output); try { serialize(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serialize(Writer writer) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer); try { serialize(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serializeAndConsume(OutputStream output) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output); try { serializeAndConsume(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serializeAndConsume(Writer writer) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer); try { serializeAndConsume(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serialize(OutputStream output, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format); try { internalSerialize(writer, true); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter writer.flush(); } finally { writer.close(); } } public void serialize(Writer writer2, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils .createXMLStreamWriter(writer2)); writer.setOutputFormat(format); try { internalSerialize(writer, true); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter writer.flush(); } finally { writer.close(); } } public void serializeAndConsume(OutputStream output, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format); try { internalSerialize(writer, false); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter writer.flush(); } finally { writer.close(); } } public void serializeAndConsume(Writer writer2, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils .createXMLStreamWriter(writer2)); try { writer.setOutputFormat(format); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter internalSerialize(writer, false); writer.flush(); } finally { writer.close(); } } /** Returns the <code>OMFactory</code> that created this node */ public OMFactory getOMFactory() { return this.factory; } public void internalSerialize(XMLStreamWriter writer) throws XMLStreamException { internalSerialize(writer, true); } public void internalSerializeAndConsume(XMLStreamWriter writer) throws XMLStreamException { internalSerialize(writer, false); } }
wso2/wso2-axiom
modules/axiom-dom/src/main/java/org/apache/axiom/om/impl/dom/NodeImpl.java
7,989
/* * DOM-Level 3 methods */
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.axiom.om.impl.dom; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMOutputFormat; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.MTOMXMLStreamWriter; import org.apache.axiom.om.impl.OMNodeEx; import org.apache.axiom.om.impl.builder.StAXBuilder; import org.apache.axiom.om.util.StAXUtils; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.OutputStream; import java.io.Writer; import java.util.Hashtable; public abstract class NodeImpl implements Node, NodeList, OMNodeEx, Cloneable { /** Holds the user data objects */ private Hashtable userData; // Will be initialized in setUserData() /** Field builder */ public OMXMLParserWrapper builder; /** Field done */ protected boolean done = false; protected DocumentImpl ownerNode; /** Factory that created this node */ protected final OMFactory factory; // data protected short flags; protected final static short OWNED = 0x1 << 1; protected final static short FIRSTCHILD = 0x1 << 2; protected final static short READONLY = 0x1 << 3; protected final static short SPECIFIED = 0x1 << 4; protected final static short NORMALIZED = 0x1 << 5; // // Constructors // protected NodeImpl(DocumentImpl ownerDocument, OMFactory factory) { //this(factory); this.factory = factory; this.ownerNode = ownerDocument; // this.isOwned(true); } protected NodeImpl(OMFactory factory) { this.factory = factory; } public void normalize() { //Parent node should override this } public boolean hasAttributes() { return false; // overridden in ElementImpl } public boolean hasChildNodes() { return false; // Override in ParentNode } public String getLocalName() { return null; // Override in AttrImpl and ElementImpl } public String getNamespaceURI() { return null; // Override in AttrImpl and ElementImpl } public String getNodeValue() throws DOMException { return null; } /* * Overidden in ElementImpl and AttrImpl. */ public String getPrefix() { return null; } public void setNodeValue(String arg0) throws DOMException { // Don't do anything, to be overridden in SOME Child classes } public void setPrefix(String prefix) throws DOMException { throw new DOMException(DOMException.NAMESPACE_ERR, DOMMessageFormatter .formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NAMESPACE_ERR, null)); } /** * Finds the document that this Node belongs to (the document in whose context the Node was * created). The Node may or may not */ public Document getOwnerDocument() { return this.ownerNode; } /** * Returns the collection of attributes associated with this node, or null if none. At this * writing, Element is the only type of node which will ever have attributes. * * @see ElementImpl */ public NamedNodeMap getAttributes() { return null; // overridden in ElementImpl } /** * Gets the first child of this Node, or null if none. * <p/> * By default we do not have any children, ParentNode overrides this. * * @see ParentNode */ public Node getFirstChild() { return null; } /** * Gets the last child of this Node, or null if none. * <p/> * By default we do not have any children, ParentNode overrides this. * * @see ParentNode */ public Node getLastChild() { return null; } /** Returns the next child of this node's parent, or null if none. */ public Node getNextSibling() { return null; // default behavior, overriden in ChildNode } public Node getParentNode() { return null; // overriden by ChildNode // Document, DocumentFragment, and Attribute will never have parents. } /* * Same as getParentNode but returns internal type NodeImpl. */ NodeImpl parentNode() { return null; } /** Returns the previous child of this node's parent, or null if none. */ public Node getPreviousSibling() { return null; // default behavior, overriden in ChildNode } // public Node cloneNode(boolean deep) { // if(this instanceof OMElement) { // return (Node)((OMElement)this).cloneOMElement(); // } else if(this instanceof OMText ){ // return ((TextImpl)this).cloneText(); // } else { // throw new UnsupportedOperationException("Only elements can be cloned // right now"); // } // } // public Node cloneNode(boolean deep) { NodeImpl newnode; try { newnode = (NodeImpl) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("**Internal Error**" + e); } newnode.ownerNode = this.ownerNode; newnode.isOwned(false); newnode.isReadonly(false); return newnode; } /* * (non-Javadoc) * * @see org.w3c.dom.Node#getChildNodes() */ public NodeList getChildNodes() { return this; } public boolean isSupported(String feature, String version) { throw new UnsupportedOperationException(); // TODO } /* * (non-Javadoc) * * @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node) */ public Node appendChild(Node newChild) throws DOMException { return insertBefore(newChild, null); } /* * (non-Javadoc) * * @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node) */ public Node removeChild(Node oldChild) throws DOMException { throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter .formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_FOUND_ERR, null)); } /* * (non-Javadoc) * * @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node insertBefore(Node newChild, Node refChild) throws DOMException { // Overridden in ParentNode throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /* * (non-Javadoc) * * @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node replaceChild(Node newChild, Node oldChild) throws DOMException { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } // // NodeList methods // /** * NodeList method: Returns the number of immediate children of this node. * <p/> * By default we do not have any children, ParentNode overrides this. * * @return Returns int. * @see ParentNode */ public int getLength() { return 0; } /** * NodeList method: Returns the Nth immediate child of this node, or null if the index is out of * bounds. * <p/> * By default we do not have any children, ParentNode overrides this. * * @param index * @return Returns org.w3c.dom.Node * @see ParentNode */ public Node item(int index) { return null; } /* * Flags setters and getters */ final boolean isOwned() { return (flags & OWNED) != 0; } final void isOwned(boolean value) { flags = (short) (value ? flags | OWNED : flags & ~OWNED); } final boolean isFirstChild() { return (flags & FIRSTCHILD) != 0; } final void isFirstChild(boolean value) { flags = (short) (value ? flags | FIRSTCHILD : flags & ~FIRSTCHILD); } final boolean isReadonly() { return (flags & READONLY) != 0; } final void isReadonly(boolean value) { flags = (short) (value ? flags | READONLY : flags & ~READONLY); } final boolean isSpecified() { return (flags & SPECIFIED) != 0; } final void isSpecified(boolean value) { flags = (short) (value ? flags | SPECIFIED : flags & ~SPECIFIED); } final boolean isNormalized() { return (flags & NORMALIZED) != 0; } final void isNormalized(boolean value) { // See if flag should propagate to parent. if (!value && isNormalized() && ownerNode != null) { ownerNode.isNormalized(false); } flags = (short) (value ? flags | NORMALIZED : flags & ~NORMALIZED); } // / // /OM Methods // / /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#getParent() */ public OMContainer getParent() throws OMException { return null; // overriden by ChildNode // Document, DocumentFragment, and Attribute will never have parents. } /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#isComplete() */ public boolean isComplete() { return this.done; } public void setComplete(boolean state) { this.done = state; } /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#insertSiblingAfter * (org.apache.axis2.om.OMNode) */ public void insertSiblingAfter(OMNode sibling) throws OMException { // Overridden in ChildNode throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /* * (non-Javadoc) * * @see org.apache.axis2.om.OMNode#insertSiblingBefore * (org.apache.axis2.om.OMNode) */ public void insertSiblingBefore(OMNode sibling) throws OMException { // Overridden in ChildNode throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /** Default behavior returns null, overriden in ChildNode. */ public OMNode getPreviousOMSibling() { return null; } /** Default behavior returns null, overriden in ChildNode. */ public OMNode getNextOMSibling() { return null; } public OMNode getNextOMSiblingIfAvailable() { return null; } public void setPreviousOMSibling(OMNode previousSibling) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } public void setNextOMSibling(OMNode previousSibling) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, DOMException.HIERARCHY_REQUEST_ERR, null)); } /** Builds next element. */ public void build() { while (!done) this.builder.next(); } /** * Parses this node and builds the object structure in memory. AXIOM supports two levels of * deffered building. First is deffered building of AXIOM using StAX. Second level is the deffered * building of attachments. AXIOM reads in the attachements from the stream only when user asks by * calling getDataHandler(). build() method builds the OM without the attachments. buildAll() * builds the OM together with attachement data. This becomes handy when user wants to free the * input stream. */ public void buildWithAttachments() { if (!this.done) { this.build(); } } public void close(boolean build) { if (build) { this.build(); } this.done = true; // If this is a StAXBuilder, close it. if (builder instanceof StAXBuilder && !((StAXBuilder) builder).isClosed()) { ((StAXBuilder) builder).releaseParserOnClose(true); ((StAXBuilder) builder).close(); } } /** * Sets the owner document. * * @param document */ protected void setOwnerDocument(DocumentImpl document) { this.ownerNode = document; this.isOwned(true); } public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException { serialize(xmlWriter, true); } public void serializeAndConsume(XMLStreamWriter xmlWriter) throws XMLStreamException { serialize(xmlWriter, false); } public void serialize(XMLStreamWriter xmlWriter, boolean cache) throws XMLStreamException { MTOMXMLStreamWriter writer = xmlWriter instanceof MTOMXMLStreamWriter ? (MTOMXMLStreamWriter) xmlWriter : new MTOMXMLStreamWriter(xmlWriter); internalSerialize(writer, cache); writer.flush(); } public OMNode detach() { throw new OMException( "Elements that doesn't have a parent can not be detached"); } /* * DOM-Level 3 methods<SUF>*/ public String getBaseURI() { // TODO TODO throw new UnsupportedOperationException("TODO"); } public short compareDocumentPosition(Node other) throws DOMException { // This is not yet implemented. In the meantime, we throw a DOMException // and not an UnsupportedOperationException, since this works better with // some other libraries (such as Saxon 8.9). throw new DOMException(DOMException.NOT_SUPPORTED_ERR, DOMMessageFormatter .formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_SUPPORTED_ERR, null)); } public String getTextContent() throws DOMException { return getNodeValue(); // overriden in some subclasses } // internal method taking a StringBuffer in parameter void getTextContent(StringBuffer buf) throws DOMException { String content = getNodeValue(); if (content != null) { buf.append(content); } } public void setTextContent(String textContent) throws DOMException { setNodeValue(textContent); // overriden in some subclasses } public boolean isSameNode(Node node) { // TODO : check return this == node; } public String lookupPrefix(String arg0) { // TODO TODO throw new UnsupportedOperationException("TODO"); } public boolean isDefaultNamespace(String arg0) { // TODO TODO throw new UnsupportedOperationException("TODO"); } public String lookupNamespaceURI(String arg0) { // TODO TODO throw new UnsupportedOperationException("TODO"); } /** * Tests whether two nodes are equal. <br>This method tests for equality of nodes, not sameness * (i.e., whether the two nodes are references to the same object) which can be tested with * <code>Node.isSameNode()</code>. All nodes that are the same will also be equal, though the * reverse may not be true. <br>Two nodes are equal if and only if the following conditions are * satisfied: <ul> <li>The two nodes are of the same type. </li> <li>The following string * attributes are equal: <code>nodeName</code>, <code>localName</code>, * <code>namespaceURI</code>, <code>prefix</code>, <code>nodeValue</code> . This is: they are * both <code>null</code>, or they have the same length and are character for character * identical. </li> <li>The <code>attributes</code> <code>NamedNodeMaps</code> are equal. This * is: they are both <code>null</code>, or they have the same length and for each node that * exists in one map there is a node that exists in the other map and is equal, although not * necessarily at the same index. </li> <li>The <code>childNodes</code> <code>NodeLists</code> * are equal. This is: they are both <code>null</code>, or they have the same length and contain * equal nodes at the same index. Note that normalization can affect equality; to avoid this, * nodes should be normalized before being compared. </li> </ul> <br>For two * <code>DocumentType</code> nodes to be equal, the following conditions must also be satisfied: * <ul> <li>The following string attributes are equal: <code>publicId</code>, * <code>systemId</code>, <code>internalSubset</code>. </li> <li>The <code>entities</code> * <code>NamedNodeMaps</code> are equal. </li> <li>The <code>notations</code> * <code>NamedNodeMaps</code> are equal. </li> </ul> <br>On the other hand, the following do not * affect equality: the <code>ownerDocument</code>, <code>baseURI</code>, and * <code>parentNode</code> attributes, the <code>specified</code> attribute for * <code>Attr</code> nodes, the <code>schemaTypeInfo</code> attribute for <code>Attr</code> and * <code>Element</code> nodes, the <code>Text.isElementContentWhitespace</code> attribute for * <code>Text</code> nodes, as well as any user data or event listeners registered on the nodes. * <p ><b>Note:</b> As a general rule, anything not mentioned in the description above is not * significant in consideration of equality checking. Note that future versions of this * specification may take into account more attributes and implementations conform to this * specification are expected to be updated accordingly. * * @param node The node to compare equality with. * @return Returns <code>true</code> if the nodes are equal, <code>false</code> otherwise. * @since DOM Level 3 */ //TODO : sumedha, complete public boolean isEqualNode(Node node) { final boolean equal = true; final boolean notEqual = false; if (this.getNodeType() != node.getNodeType()) { return notEqual; } if (checkStringAttributeEquality(node)) { if (checkNamedNodeMapEquality(node)) { } else { return notEqual; } } else { return notEqual; } return equal; } private boolean checkStringAttributeEquality(Node node) { final boolean equal = true; final boolean notEqual = false; // null not-null -> true // not-null null -> true // null null -> false // not-null not-null -> false //NodeName if (node.getNodeName() == null ^ this.getNodeName() == null) { return notEqual; } else { if (node.getNodeName() == null) { //This means both are null.do nothing } else { if (!(node.getNodeName().equals(this.getNodeName()))) { return notEqual; } } } //localName if (node.getLocalName() == null ^ this.getLocalName() == null) { return notEqual; } else { if (node.getLocalName() == null) { //This means both are null.do nothing } else { if (!(node.getLocalName().equals(this.getLocalName()))) { return notEqual; } } } //namespaceURI if (node.getNamespaceURI() == null ^ this.getNamespaceURI() == null) { return notEqual; } else { if (node.getNamespaceURI() == null) { //This means both are null.do nothing } else { if (!(node.getNamespaceURI().equals(this.getNamespaceURI()))) { return notEqual; } } } //prefix if (node.getPrefix() == null ^ this.getPrefix() == null) { return notEqual; } else { if (node.getPrefix() == null) { //This means both are null.do nothing } else { if (!(node.getPrefix().equals(this.getPrefix()))) { return notEqual; } } } //nodeValue if (node.getNodeValue() == null ^ this.getNodeValue() == null) { return notEqual; } else { if (node.getNodeValue() == null) { //This means both are null.do nothing } else { if (!(node.getNodeValue().equals(this.getNodeValue()))) { return notEqual; } } } return equal; } private boolean checkNamedNodeMapEquality(Node node) { final boolean equal = true; final boolean notEqual = false; if (node.getAttributes() == null ^ this.getAttributes() == null) { return notEqual; } NamedNodeMap thisNamedNodeMap = this.getAttributes(); NamedNodeMap nodeNamedNodeMap = node.getAttributes(); // null not-null -> true // not-null null -> true // null null -> false // not-null not-null -> false if (thisNamedNodeMap == null ^ nodeNamedNodeMap == null) { return notEqual; } else { if (thisNamedNodeMap == null) { //This means both are null.do nothing } else { if (thisNamedNodeMap.getLength() != nodeNamedNodeMap.getLength()) { return notEqual; } else { //they have the same length and for each node that exists in one map //there is a node that exists in the other map and is equal, although //not necessarily at the same index. int itemCount = thisNamedNodeMap.getLength(); for (int a = 0; a < itemCount; a++) { NodeImpl thisNode = (NodeImpl) thisNamedNodeMap.item(a); NodeImpl tmpNode = (NodeImpl) nodeNamedNodeMap.getNamedItem(thisNode.getNodeName()); if (tmpNode == null) { //i.e. no corresponding node return notEqual; } else { if (!(thisNode.isEqualNode(tmpNode))) { return notEqual; } } } } } } return equal; } public Object getFeature(String arg0, String arg1) { // TODO TODO throw new UnsupportedOperationException("TODO"); } /* * * userData storage/hashtable will be called only when the user needs to set user data. Previously, it was done as, * for every node a new Hashtable created making the excution very inefficient. According to profiles, no. of method * invocations to setUserData() method is very low, so this implementation is better. * Another option: * TODO do a profile and check the times for hashtable initialization. If it's still higher, we have to go to second option * Create a separate class(UserData) to store key and value pairs. Then put those objects to a array with a reasonable size. * then grow it accordingly. @ Kasun Gajasinghe * @param key userData key * @param value userData value * @param userDataHandler it seems all invocations sends null for this parameter. * Kept it for the moment just for being on the safe side. * @return previous Object if one is set before. */ public Object setUserData(String key, Object value, UserDataHandler userDataHandler) { if (userData == null) { userData = new Hashtable(); } return userData.put(key, value); } public Object getUserData(String key) { if (userData != null) { return userData.get(key); } return null; } public void serialize(OutputStream output) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output); try { serialize(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serialize(Writer writer) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer); try { serialize(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serializeAndConsume(OutputStream output) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output); try { serializeAndConsume(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serializeAndConsume(Writer writer) throws XMLStreamException { XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer); try { serializeAndConsume(xmlStreamWriter); } finally { xmlStreamWriter.close(); } } public void serialize(OutputStream output, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format); try { internalSerialize(writer, true); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter writer.flush(); } finally { writer.close(); } } public void serialize(Writer writer2, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils .createXMLStreamWriter(writer2)); writer.setOutputFormat(format); try { internalSerialize(writer, true); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter writer.flush(); } finally { writer.close(); } } public void serializeAndConsume(OutputStream output, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format); try { internalSerialize(writer, false); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter writer.flush(); } finally { writer.close(); } } public void serializeAndConsume(Writer writer2, OMOutputFormat format) throws XMLStreamException { MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils .createXMLStreamWriter(writer2)); try { writer.setOutputFormat(format); // TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter internalSerialize(writer, false); writer.flush(); } finally { writer.close(); } } /** Returns the <code>OMFactory</code> that created this node */ public OMFactory getOMFactory() { return this.factory; } public void internalSerialize(XMLStreamWriter writer) throws XMLStreamException { internalSerialize(writer, true); } public void internalSerializeAndConsume(XMLStreamWriter writer) throws XMLStreamException { internalSerialize(writer, false); } }
10080_6
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP 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 any later version. * * JMTP 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 LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package jmtp; import java.math.BigInteger; import java.util.Date; import be.derycke.pieter.com.COMException; import be.derycke.pieter.com.Guid; import be.derycke.pieter.com.OleDate; /** * * @author Pieter De Rycke */ class PortableDeviceObjectImplWin32 implements PortableDeviceObject { protected PortableDeviceContentImplWin32 content; protected PortableDevicePropertiesImplWin32 properties; protected PortableDeviceKeyCollectionImplWin32 keyCollection; protected PortableDeviceValuesImplWin32 values; protected String objectID; PortableDeviceObjectImplWin32(String objectID, PortableDeviceContentImplWin32 content, PortableDevicePropertiesImplWin32 properties) { this.objectID = objectID; this.content = content; this.properties = properties; try { this.keyCollection = new PortableDeviceKeyCollectionImplWin32(); this.values = new PortableDeviceValuesImplWin32(); } catch (COMException e) { e.printStackTrace(); } } /** * Een String property opvragen. * @param key * @return */ protected String retrieveStringValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getStringValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return null; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -> de string werd niet ingesteld } } } protected void changeStringValue(PropertyKey key, String value) { try { values.clear(); values.setStringValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected long retrieveLongValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return -1; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return -1; } } } protected void changeLongValue(PropertyKey key, long value) { try { values.clear(); values.setUnsignedIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected Date retrieveDateValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key)); } catch(COMException e) { return null; } } protected void changeDateValue(PropertyKey key, Date value) { try { values.clear(); values.setFloateValue(key, (float)new OleDate(value).toDouble()); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) {} } protected boolean retrieveBooleanValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getBoolValue(key); } catch(COMException e) { return false; } } protected Guid retrieveGuidValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getGuidValue(key); } catch(COMException e) { return null; } } protected BigInteger retrieveBigIntegerValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getUnsignedLargeIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return new BigInteger("-1"); else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -> de string werd niet ingesteld } } } protected void changeBigIntegerValue(PropertyKey key, BigInteger value) { try { values.clear(); values.setUnsignedLargeIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } public String getID() { return objectID; } public String getName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME); } public String getOriginalFileName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME); } public boolean canDelete() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE); } public boolean isHidden() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN); } public boolean isSystemObject() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM); } public Date getDateModified() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED); } public Date getDateCreated() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED); } public Date getDateAuthored() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED); } public PortableDeviceObject getParent() { String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID); if(parentID != null) return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties); else return null; } public BigInteger getSize() { return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE); } public String getPersistentUniqueIdentifier() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID); } public boolean isDrmProtected() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED); } public String getSyncID() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID); } //TODO slechts tijdelijk de guids geven -> enum aanmaken public Guid getFormat() { return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT); } public void setSyncID(String value) { changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value); } public void delete() { try { PortableDevicePropVariantCollectionImplWin32 collection = new PortableDevicePropVariantCollectionImplWin32(); collection.add(new PropVariant(this.objectID)); this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection); } catch(COMException e) { //TODO -> misschien een exception gooien? e.printStackTrace(); } } @Override public String toString() { return objectID; } public boolean equals(Object o) { if(o instanceof PortableDeviceObjectImplWin32) { PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o; return object.objectID.equals(this.objectID); } else return false; } }
wujingchao/jmtp
library/src/main/java/jmtp/PortableDeviceObjectImplWin32.java
2,927
//TODO -> misschien een exception gooien?
line_comment
nl
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP 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 any later version. * * JMTP 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 LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package jmtp; import java.math.BigInteger; import java.util.Date; import be.derycke.pieter.com.COMException; import be.derycke.pieter.com.Guid; import be.derycke.pieter.com.OleDate; /** * * @author Pieter De Rycke */ class PortableDeviceObjectImplWin32 implements PortableDeviceObject { protected PortableDeviceContentImplWin32 content; protected PortableDevicePropertiesImplWin32 properties; protected PortableDeviceKeyCollectionImplWin32 keyCollection; protected PortableDeviceValuesImplWin32 values; protected String objectID; PortableDeviceObjectImplWin32(String objectID, PortableDeviceContentImplWin32 content, PortableDevicePropertiesImplWin32 properties) { this.objectID = objectID; this.content = content; this.properties = properties; try { this.keyCollection = new PortableDeviceKeyCollectionImplWin32(); this.values = new PortableDeviceValuesImplWin32(); } catch (COMException e) { e.printStackTrace(); } } /** * Een String property opvragen. * @param key * @return */ protected String retrieveStringValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getStringValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return null; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -> de string werd niet ingesteld } } } protected void changeStringValue(PropertyKey key, String value) { try { values.clear(); values.setStringValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected long retrieveLongValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return -1; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return -1; } } } protected void changeLongValue(PropertyKey key, long value) { try { values.clear(); values.setUnsignedIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected Date retrieveDateValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key)); } catch(COMException e) { return null; } } protected void changeDateValue(PropertyKey key, Date value) { try { values.clear(); values.setFloateValue(key, (float)new OleDate(value).toDouble()); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) {} } protected boolean retrieveBooleanValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getBoolValue(key); } catch(COMException e) { return false; } } protected Guid retrieveGuidValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getGuidValue(key); } catch(COMException e) { return null; } } protected BigInteger retrieveBigIntegerValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getUnsignedLargeIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return new BigInteger("-1"); else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -> de string werd niet ingesteld } } } protected void changeBigIntegerValue(PropertyKey key, BigInteger value) { try { values.clear(); values.setUnsignedLargeIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } public String getID() { return objectID; } public String getName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME); } public String getOriginalFileName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME); } public boolean canDelete() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE); } public boolean isHidden() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN); } public boolean isSystemObject() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM); } public Date getDateModified() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED); } public Date getDateCreated() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED); } public Date getDateAuthored() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED); } public PortableDeviceObject getParent() { String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID); if(parentID != null) return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties); else return null; } public BigInteger getSize() { return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE); } public String getPersistentUniqueIdentifier() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID); } public boolean isDrmProtected() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED); } public String getSyncID() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID); } //TODO slechts tijdelijk de guids geven -> enum aanmaken public Guid getFormat() { return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT); } public void setSyncID(String value) { changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value); } public void delete() { try { PortableDevicePropVariantCollectionImplWin32 collection = new PortableDevicePropVariantCollectionImplWin32(); collection.add(new PropVariant(this.objectID)); this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection); } catch(COMException e) { //TODO -><SUF> e.printStackTrace(); } } @Override public String toString() { return objectID; } public boolean equals(Object o) { if(o instanceof PortableDeviceObjectImplWin32) { PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o; return object.objectID.equals(this.objectID); } else return false; } }
201019_4
/* @author Nick @version 1007 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; public class Datenbank { int zug = 0; Connection connection = null; public void datenbankErstellen() { try { // Pfad zur SQLite-Datenbankdatei angeben String dbFile = "datenbank.db"; // Verbindung zur Datenbank herstellen connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile); } catch (SQLException e) { e.printStackTrace(); } } Statement statement = null; ResultSet resultSet = null; public void tabelleErstellen(){ try { statement = connection.createStatement(); // Tabelle erstellen String createTableQuery = "CREATE TABLE IF NOT EXISTS zuege (Zugnummer INT, Zug TEXT)"; statement.executeUpdate(createTableQuery); } catch (SQLException e) { e.printStackTrace(); } } public void datenEinfuegen(Connection connection, String text){ try{ // SQL-Abfrage zum Einfügen von Daten String insertQuery = "INSERT INTO zuege (Zugnummer, Zug) VALUES (?, ?)"; // Prepared Statement vorbereiten PreparedStatement statement = connection.prepareStatement(insertQuery); // Werte für die Parameter festlegen statement.setInt(1, zug+1); statement.setString(2, text); // Einfügen der Daten ausführen statement.executeUpdate(); // Prepared Statement schließen statement.close(); } catch (SQLException e) { e.printStackTrace(); } } public void tabelleLeeren(Connection connection){ try{ //leert die komplette Tabelle String deleteQuery = "DELETE FROM zuege"; Statement statement = connection.createStatement(); statement.executeUpdate(deleteQuery); statement.close(); //Züge auf 0 setzen und die Standart Board-Position einfügen zug = 0; datenEinfuegen(connection, "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"); } catch (SQLException e){ e.printStackTrace(); } } public int letzterZug(Connection connection){ try{ //abfragen des Wertes des letzten Eintrags der Spalte "Zug" String selectQuery = "SELECT MAX(Zug) FROM zuege"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(selectQuery); int letzterZug = resultSet.getInt(1); resultSet.close(); statement.close(); return letzterZug; } catch(SQLException e){ e.printStackTrace(); return -1; } } public Datenbank(){ datenbankErstellen(); tabelleErstellen(); zug = letzterZug(connection); } }
wulusub/Schach
Datenbank.java
943
// Prepared Statement vorbereiten
line_comment
nl
/* @author Nick @version 1007 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; public class Datenbank { int zug = 0; Connection connection = null; public void datenbankErstellen() { try { // Pfad zur SQLite-Datenbankdatei angeben String dbFile = "datenbank.db"; // Verbindung zur Datenbank herstellen connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile); } catch (SQLException e) { e.printStackTrace(); } } Statement statement = null; ResultSet resultSet = null; public void tabelleErstellen(){ try { statement = connection.createStatement(); // Tabelle erstellen String createTableQuery = "CREATE TABLE IF NOT EXISTS zuege (Zugnummer INT, Zug TEXT)"; statement.executeUpdate(createTableQuery); } catch (SQLException e) { e.printStackTrace(); } } public void datenEinfuegen(Connection connection, String text){ try{ // SQL-Abfrage zum Einfügen von Daten String insertQuery = "INSERT INTO zuege (Zugnummer, Zug) VALUES (?, ?)"; // Prepared Statement<SUF> PreparedStatement statement = connection.prepareStatement(insertQuery); // Werte für die Parameter festlegen statement.setInt(1, zug+1); statement.setString(2, text); // Einfügen der Daten ausführen statement.executeUpdate(); // Prepared Statement schließen statement.close(); } catch (SQLException e) { e.printStackTrace(); } } public void tabelleLeeren(Connection connection){ try{ //leert die komplette Tabelle String deleteQuery = "DELETE FROM zuege"; Statement statement = connection.createStatement(); statement.executeUpdate(deleteQuery); statement.close(); //Züge auf 0 setzen und die Standart Board-Position einfügen zug = 0; datenEinfuegen(connection, "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"); } catch (SQLException e){ e.printStackTrace(); } } public int letzterZug(Connection connection){ try{ //abfragen des Wertes des letzten Eintrags der Spalte "Zug" String selectQuery = "SELECT MAX(Zug) FROM zuege"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(selectQuery); int letzterZug = resultSet.getInt(1); resultSet.close(); statement.close(); return letzterZug; } catch(SQLException e){ e.printStackTrace(); return -1; } } public Datenbank(){ datenbankErstellen(); tabelleErstellen(); zug = letzterZug(connection); } }
195476_8
import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests Infielder. * * Project 11 * @author Will Humphlett - COMP1210 - LLB001 * @version 4/17/2019 */ public class InfielderTest { /** Fixture initialization (common initialization * for all tests). **/ @Before public void setUp() { } /** * Tests infielder number. */ @Test public void numberTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setNumber("0"); Assert.assertEquals("0", player.getNumber()); } /** * Tests infielder name. */ @Test public void nameTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setName("empty"); Assert.assertEquals("empty", player.getName()); } /** * Tests infielder position. */ @Test public void positionTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setPosition("none"); Assert.assertEquals("none", player.getPosition()); } /** * Tests infielder specialization factor. */ @Test public void specializationTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setSpecializationFactor(99.9); Assert.assertEquals(99.9, player.getSpecializationFactor(), .000001); } /** * Tests infielder batting avg. */ @Test public void battingAvgTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setBattingAvg(0.999); Assert.assertEquals(0.999, player.getBattingAvg(), .000001); } /** * Tests infielder fielding avg. */ @Test public void infielderFieldingAvgTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setInfielderFieldingAvg(.999); Assert.assertEquals(.999, player.getInfielderFieldingAvg(), .000001); } /** * Tests infielder stats. */ @Test public void statsTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Assert.assertEquals(".275", player.stats()); } /** * Tests infielder rating override. */ @Test public void ratingTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Assert.assertEquals(2.921875, player.rating(), .000001); } /** * Tests infielder count. */ @Test public void countTest() { SoftballPlayer.resetCount(); Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Assert.assertEquals(1, SoftballPlayer.getCount()); } /** * Tests infielder compareTo. */ @Test public void toCompareTest() { Infielder player1 = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Infielder player2 = new Infielder("23", "Johnny Jay", "2B", 1.00, .200, .800); Infielder player3 = new Infielder("40", "Champ Chump", "1B", 1.29, .279, .950); Infielder player4 = new Infielder("10", "J Jackson", "SS", 1.55, .375, .250); Assert.assertEquals(0, player1.compareTo(player2)); Assert.assertEquals(-1, player1.compareTo(player3)); Assert.assertEquals(1, player1.compareTo(player4)); } /** * Tests infielder toString. */ @Test public void toStringTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); String test = "23 Jackie Smith (3B) .275"; test += "\nSpecialization Factor: 1.25 (class Infielder) Rating: 2.922"; Assert.assertEquals(test, player.toString()); } }
wumphlett/COMP-1210
P11-Exceptions/InfielderTest.java
1,317
/** * Tests infielder stats. */
block_comment
nl
import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests Infielder. * * Project 11 * @author Will Humphlett - COMP1210 - LLB001 * @version 4/17/2019 */ public class InfielderTest { /** Fixture initialization (common initialization * for all tests). **/ @Before public void setUp() { } /** * Tests infielder number. */ @Test public void numberTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setNumber("0"); Assert.assertEquals("0", player.getNumber()); } /** * Tests infielder name. */ @Test public void nameTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setName("empty"); Assert.assertEquals("empty", player.getName()); } /** * Tests infielder position. */ @Test public void positionTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setPosition("none"); Assert.assertEquals("none", player.getPosition()); } /** * Tests infielder specialization factor. */ @Test public void specializationTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setSpecializationFactor(99.9); Assert.assertEquals(99.9, player.getSpecializationFactor(), .000001); } /** * Tests infielder batting avg. */ @Test public void battingAvgTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setBattingAvg(0.999); Assert.assertEquals(0.999, player.getBattingAvg(), .000001); } /** * Tests infielder fielding avg. */ @Test public void infielderFieldingAvgTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); player.setInfielderFieldingAvg(.999); Assert.assertEquals(.999, player.getInfielderFieldingAvg(), .000001); } /** * Tests infielder stats.<SUF>*/ @Test public void statsTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Assert.assertEquals(".275", player.stats()); } /** * Tests infielder rating override. */ @Test public void ratingTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Assert.assertEquals(2.921875, player.rating(), .000001); } /** * Tests infielder count. */ @Test public void countTest() { SoftballPlayer.resetCount(); Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Assert.assertEquals(1, SoftballPlayer.getCount()); } /** * Tests infielder compareTo. */ @Test public void toCompareTest() { Infielder player1 = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); Infielder player2 = new Infielder("23", "Johnny Jay", "2B", 1.00, .200, .800); Infielder player3 = new Infielder("40", "Champ Chump", "1B", 1.29, .279, .950); Infielder player4 = new Infielder("10", "J Jackson", "SS", 1.55, .375, .250); Assert.assertEquals(0, player1.compareTo(player2)); Assert.assertEquals(-1, player1.compareTo(player3)); Assert.assertEquals(1, player1.compareTo(player4)); } /** * Tests infielder toString. */ @Test public void toStringTest() { Infielder player = new Infielder("23", "Jackie Smith", "3B", 1.25, .275, .850); String test = "23 Jackie Smith (3B) .275"; test += "\nSpecialization Factor: 1.25 (class Infielder) Rating: 2.922"; Assert.assertEquals(test, player.toString()); } }
146328_2
/* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.colorchooser.*; import javax.swing.plaf.ColorChooserUI; import javax.accessibility.*; import sun.swing.SwingUtilities2; /** * <code>JColorChooser</code> provides a pane of controls designed to allow * a user to manipulate and select a color. * For information about using color choosers, see * <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html">How to Use Color Choosers</a>, * a section in <em>The Java Tutorial</em>. * * <p> * * This class provides three levels of API: * <ol> * <li>A static convenience method which shows a modal color-chooser * dialog and returns the color selected by the user. * <li>A static convenience method for creating a color-chooser dialog * where <code>ActionListeners</code> can be specified to be invoked when * the user presses one of the dialog buttons. * <li>The ability to create instances of <code>JColorChooser</code> panes * directly (within any container). <code>PropertyChange</code> listeners * can be added to detect when the current "color" property changes. * </ol> * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * * @beaninfo * attribute: isContainer false * description: A component that supports selecting a Color. * * * @author James Gosling * @author Amy Fowler * @author Steve Wilson */ public class JColorChooser extends JComponent implements Accessible { /** * @see #getUIClassID * @see #readObject */ private static final String uiClassID = "ColorChooserUI"; private ColorSelectionModel selectionModel; private JComponent previewPanel = ColorChooserComponentFactory.getPreviewPanel(); private AbstractColorChooserPanel[] chooserPanels = new AbstractColorChooserPanel[0]; private boolean dragEnabled; /** * The selection model property name. */ public static final String SELECTION_MODEL_PROPERTY = "selectionModel"; /** * The preview panel property name. */ public static final String PREVIEW_PANEL_PROPERTY = "previewPanel"; /** * The chooserPanel array property name. */ public static final String CHOOSER_PANELS_PROPERTY = "chooserPanels"; /** * Shows a modal color-chooser dialog and blocks until the * dialog is hidden. If the user presses the "OK" button, then * this method hides/disposes the dialog and returns the selected color. * If the user presses the "Cancel" button or closes the dialog without * pressing "OK", then this method hides/disposes the dialog and returns * <code>null</code>. * * @param component the parent <code>Component</code> for the dialog * @param title the String containing the dialog's title * @param initialColor the initial Color set when the color-chooser is shown * @return the selected color or <code>null</code> if the user opted out * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static Color showDialog(Component component, String title, Color initialColor) throws HeadlessException { final JColorChooser pane = new JColorChooser(initialColor != null? initialColor : Color.white); ColorTracker ok = new ColorTracker(pane); JDialog dialog = createDialog(component, title, true, pane, ok, null); dialog.addComponentListener(new ColorChooserDialog.DisposeOnClose()); dialog.show(); // blocks until user brings dialog down... return ok.getColor(); } /** * Creates and returns a new dialog containing the specified * <code>ColorChooser</code> pane along with "OK", "Cancel", and "Reset" * buttons. If the "OK" or "Cancel" buttons are pressed, the dialog is * automatically hidden (but not disposed). If the "Reset" * button is pressed, the color-chooser's color will be reset to the * color which was set the last time <code>show</code> was invoked on the * dialog and the dialog will remain showing. * * @param c the parent component for the dialog * @param title the title for the dialog * @param modal a boolean. When true, the remainder of the program * is inactive until the dialog is closed. * @param chooserPane the color-chooser to be placed inside the dialog * @param okListener the ActionListener invoked when "OK" is pressed * @param cancelListener the ActionListener invoked when "Cancel" is pressed * @return a new dialog containing the color-chooser pane * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static JDialog createDialog(Component c, String title, boolean modal, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { Window window = JOptionPane.getWindowForComponent(c); ColorChooserDialog dialog; if (window instanceof Frame) { dialog = new ColorChooserDialog((Frame)window, title, modal, c, chooserPane, okListener, cancelListener); } else { dialog = new ColorChooserDialog((Dialog)window, title, modal, c, chooserPane, okListener, cancelListener); } dialog.getAccessibleContext().setAccessibleDescription(title); return dialog; } /** * Creates a color chooser pane with an initial color of white. */ public JColorChooser() { this(Color.white); } /** * Creates a color chooser pane with the specified initial color. * * @param initialColor the initial color set in the chooser */ public JColorChooser(Color initialColor) { this( new DefaultColorSelectionModel(initialColor) ); } /** * Creates a color chooser pane with the specified * <code>ColorSelectionModel</code>. * * @param model the <code>ColorSelectionModel</code> to be used */ public JColorChooser(ColorSelectionModel model) { selectionModel = model; updateUI(); dragEnabled = false; } /** * Returns the L&amp;F object that renders this component. * * @return the <code>ColorChooserUI</code> object that renders * this component */ public ColorChooserUI getUI() { return (ColorChooserUI)ui; } /** * Sets the L&amp;F object that renders this component. * * @param ui the <code>ColorChooserUI</code> L&amp;F object * @see UIDefaults#getUI * * @beaninfo * bound: true * hidden: true * description: The UI object that implements the color chooser's LookAndFeel. */ public void setUI(ColorChooserUI ui) { super.setUI(ui); } /** * Notification from the <code>UIManager</code> that the L&amp;F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see JComponent#updateUI */ public void updateUI() { setUI((ColorChooserUI)UIManager.getUI(this)); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ColorChooserUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Gets the current color value from the color chooser. * By default, this delegates to the model. * * @return the current color value of the color chooser */ public Color getColor() { return selectionModel.getSelectedColor(); } /** * Sets the current color of the color chooser to the specified color. * The <code>ColorSelectionModel</code> will fire a <code>ChangeEvent</code> * @param color the color to be set in the color chooser * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: false * hidden: false * description: The current color the chooser is to display. */ public void setColor(Color color) { selectionModel.setSelectedColor(color); } /** * Sets the current color of the color chooser to the * specified RGB color. Note that the values of red, green, * and blue should be between the numbers 0 and 255, inclusive. * * @param r an int specifying the amount of Red * @param g an int specifying the amount of Green * @param b an int specifying the amount of Blue * @exception IllegalArgumentException if r,g,b values are out of range * @see java.awt.Color */ public void setColor(int r, int g, int b) { setColor(new Color(r,g,b)); } /** * Sets the current color of the color chooser to the * specified color. * * @param c an integer value that sets the current color in the chooser * where the low-order 8 bits specify the Blue value, * the next 8 bits specify the Green value, and the 8 bits * above that specify the Red value. */ public void setColor(int c) { setColor((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF); } /** * Sets the <code>dragEnabled</code> property, * which must be <code>true</code> to enable * automatic drag handling (the first part of drag and drop) * on this component. * The <code>transferHandler</code> property needs to be set * to a non-<code>null</code> value for the drag to do * anything. The default value of the <code>dragEnabled</code> * property * is <code>false</code>. * * <p> * * When automatic drag handling is enabled, * most look and feels begin a drag-and-drop operation * when the user presses the mouse button over the preview panel. * Some look and feels might not support automatic drag and drop; * they will ignore this property. You can work around such * look and feels by modifying the component * to directly call the <code>exportAsDrag</code> method of a * <code>TransferHandler</code>. * * @param b the value to set the <code>dragEnabled</code> property to * @exception HeadlessException if * <code>b</code> is <code>true</code> and * <code>GraphicsEnvironment.isHeadless()</code> * returns <code>true</code> * * @since 1.4 * * @see java.awt.GraphicsEnvironment#isHeadless * @see #getDragEnabled * @see #setTransferHandler * @see TransferHandler * * @beaninfo * description: Determines whether automatic drag handling is enabled. * bound: false */ public void setDragEnabled(boolean b) { if (b && GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } dragEnabled = b; } /** * Gets the value of the <code>dragEnabled</code> property. * * @return the value of the <code>dragEnabled</code> property * @see #setDragEnabled * @since 1.4 */ public boolean getDragEnabled() { return dragEnabled; } /** * Sets the current preview panel. * This will fire a <code>PropertyChangeEvent</code> for the property * named "previewPanel". * * @param preview the <code>JComponent</code> which displays the current color * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: true * hidden: true * description: The UI component which displays the current color. */ public void setPreviewPanel(JComponent preview) { if (previewPanel != preview) { JComponent oldPreview = previewPanel; previewPanel = preview; firePropertyChange(JColorChooser.PREVIEW_PANEL_PROPERTY, oldPreview, preview); } } /** * Returns the preview panel that shows a chosen color. * * @return a <code>JComponent</code> object -- the preview panel */ public JComponent getPreviewPanel() { return previewPanel; } /** * Adds a color chooser panel to the color chooser. * * @param panel the <code>AbstractColorChooserPanel</code> to be added */ public void addChooserPanel( AbstractColorChooserPanel panel ) { AbstractColorChooserPanel[] oldPanels = getChooserPanels(); AbstractColorChooserPanel[] newPanels = new AbstractColorChooserPanel[oldPanels.length+1]; System.arraycopy(oldPanels, 0, newPanels, 0, oldPanels.length); newPanels[newPanels.length-1] = panel; setChooserPanels(newPanels); } /** * Removes the Color Panel specified. * * @param panel a string that specifies the panel to be removed * @return the color panel * @exception IllegalArgumentException if panel is not in list of * known chooser panels */ public AbstractColorChooserPanel removeChooserPanel( AbstractColorChooserPanel panel ) { int containedAt = -1; for (int i = 0; i < chooserPanels.length; i++) { if (chooserPanels[i] == panel) { containedAt = i; break; } } if (containedAt == -1) { throw new IllegalArgumentException("chooser panel not in this chooser"); } AbstractColorChooserPanel[] newArray = new AbstractColorChooserPanel[chooserPanels.length-1]; if (containedAt == chooserPanels.length-1) { // at end System.arraycopy(chooserPanels, 0, newArray, 0, newArray.length); } else if (containedAt == 0) { // at start System.arraycopy(chooserPanels, 1, newArray, 0, newArray.length); } else { // in middle System.arraycopy(chooserPanels, 0, newArray, 0, containedAt); System.arraycopy(chooserPanels, containedAt+1, newArray, containedAt, (chooserPanels.length - containedAt - 1)); } setChooserPanels(newArray); return panel; } /** * Specifies the Color Panels used to choose a color value. * * @param panels an array of <code>AbstractColorChooserPanel</code> * objects * * @beaninfo * bound: true * hidden: true * description: An array of different chooser types. */ public void setChooserPanels( AbstractColorChooserPanel[] panels) { AbstractColorChooserPanel[] oldValue = chooserPanels; chooserPanels = panels; firePropertyChange(CHOOSER_PANELS_PROPERTY, oldValue, panels); } /** * Returns the specified color panels. * * @return an array of <code>AbstractColorChooserPanel</code> objects */ public AbstractColorChooserPanel[] getChooserPanels() { return chooserPanels; } /** * Returns the data model that handles color selections. * * @return a <code>ColorSelectionModel</code> object */ public ColorSelectionModel getSelectionModel() { return selectionModel; } /** * Sets the model containing the selected color. * * @param newModel the new <code>ColorSelectionModel</code> object * * @beaninfo * bound: true * hidden: true * description: The model which contains the currently selected color. */ public void setSelectionModel(ColorSelectionModel newModel ) { ColorSelectionModel oldModel = selectionModel; selectionModel = newModel; firePropertyChange(JColorChooser.SELECTION_MODEL_PROPERTY, oldModel, newModel); } /** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } } /** * Returns a string representation of this <code>JColorChooser</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JColorChooser</code> */ protected String paramString() { StringBuffer chooserPanelsString = new StringBuffer(""); for (int i=0; i<chooserPanels.length; i++) { chooserPanelsString.append("[" + chooserPanels[i].toString() + "]"); } String previewPanelString = (previewPanel != null ? previewPanel.toString() : ""); return super.paramString() + ",chooserPanels=" + chooserPanelsString.toString() + ",previewPanel=" + previewPanelString; } ///////////////// // Accessibility support //////////////// protected AccessibleContext accessibleContext = null; /** * Gets the AccessibleContext associated with this JColorChooser. * For color choosers, the AccessibleContext takes the form of an * AccessibleJColorChooser. * A new AccessibleJColorChooser instance is created if necessary. * * @return an AccessibleJColorChooser that serves as the * AccessibleContext of this JColorChooser */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJColorChooser(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JColorChooser</code> class. It provides an implementation of the * Java Accessibility API appropriate to color chooser user-interface * elements. */ protected class AccessibleJColorChooser extends AccessibleJComponent { /** * Get the role of this object. * * @return an instance of AccessibleRole describing the role of the * object * @see AccessibleRole */ public AccessibleRole getAccessibleRole() { return AccessibleRole.COLOR_CHOOSER; } } // inner class AccessibleJColorChooser } /* * Class which builds a color chooser dialog consisting of * a JColorChooser with "Ok", "Cancel", and "Reset" buttons. * * Note: This needs to be fixed to deal with localization! */ class ColorChooserDialog extends JDialog { private Color initialColor; private JColorChooser chooserPane; private JButton cancelButton; public ColorChooserDialog(Dialog owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } public ColorChooserDialog(Frame owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } protected void initColorChooserDialog(Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) { //setResizable(false); this.chooserPane = chooserPane; Locale locale = getLocale(); String okString = UIManager.getString("ColorChooser.okText", locale); String cancelString = UIManager.getString("ColorChooser.cancelText", locale); String resetString = UIManager.getString("ColorChooser.resetText", locale); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(chooserPane, BorderLayout.CENTER); /* * Create Lower button panel */ JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); JButton okButton = new JButton(okString); getRootPane().setDefaultButton(okButton); okButton.getAccessibleContext().setAccessibleDescription(okString); okButton.setActionCommand("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (okListener != null) { okButton.addActionListener(okListener); } buttonPane.add(okButton); cancelButton = new JButton(cancelString); cancelButton.getAccessibleContext().setAccessibleDescription(cancelString); // The following few lines are used to register esc to close the dialog Action cancelKeyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { ((AbstractButton)e.getSource()).fireActionPerformed(e); } }; KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); InputMap inputMap = cancelButton.getInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = cancelButton.getActionMap(); if (inputMap != null && actionMap != null) { inputMap.put(cancelKeyStroke, "cancel"); actionMap.put("cancel", cancelKeyAction); } // end esc handling cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (cancelListener != null) { cancelButton.addActionListener(cancelListener); } buttonPane.add(cancelButton); JButton resetButton = new JButton(resetString); resetButton.getAccessibleContext().setAccessibleDescription(resetString); resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reset(); } }); int mnemonic = SwingUtilities2.getUIDefaultsInt("ColorChooser.resetMnemonic", locale, -1); if (mnemonic != -1) { resetButton.setMnemonic(mnemonic); } buttonPane.add(resetButton); contentPane.add(buttonPane, BorderLayout.SOUTH); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); if (supportsWindowDecorations) { getRootPane().setWindowDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG); } } applyComponentOrientation(((c == null) ? getRootPane() : c).getComponentOrientation()); pack(); setLocationRelativeTo(c); this.addWindowListener(new Closer()); } public void show() { initialColor = chooserPane.getColor(); super.show(); } public void reset() { chooserPane.setColor(initialColor); } class Closer extends WindowAdapter implements Serializable{ public void windowClosing(WindowEvent e) { cancelButton.doClick(0); Window w = e.getWindow(); w.hide(); } } static class DisposeOnClose extends ComponentAdapter implements Serializable{ public void componentHidden(ComponentEvent e) { Window w = (Window)e.getComponent(); w.dispose(); } } } class ColorTracker implements ActionListener, Serializable { JColorChooser chooser; Color color; public ColorTracker(JColorChooser c) { chooser = c; } public void actionPerformed(ActionEvent e) { color = chooser.getColor(); } public Color getColor() { return color; } }
wupeixuan/JDKSourceCode1.8
src/javax/swing/JColorChooser.java
7,008
/** * @see #getUIClassID * @see #readObject */
block_comment
nl
/* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.colorchooser.*; import javax.swing.plaf.ColorChooserUI; import javax.accessibility.*; import sun.swing.SwingUtilities2; /** * <code>JColorChooser</code> provides a pane of controls designed to allow * a user to manipulate and select a color. * For information about using color choosers, see * <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html">How to Use Color Choosers</a>, * a section in <em>The Java Tutorial</em>. * * <p> * * This class provides three levels of API: * <ol> * <li>A static convenience method which shows a modal color-chooser * dialog and returns the color selected by the user. * <li>A static convenience method for creating a color-chooser dialog * where <code>ActionListeners</code> can be specified to be invoked when * the user presses one of the dialog buttons. * <li>The ability to create instances of <code>JColorChooser</code> panes * directly (within any container). <code>PropertyChange</code> listeners * can be added to detect when the current "color" property changes. * </ol> * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * * @beaninfo * attribute: isContainer false * description: A component that supports selecting a Color. * * * @author James Gosling * @author Amy Fowler * @author Steve Wilson */ public class JColorChooser extends JComponent implements Accessible { /** * @see #getUIClassID <SUF>*/ private static final String uiClassID = "ColorChooserUI"; private ColorSelectionModel selectionModel; private JComponent previewPanel = ColorChooserComponentFactory.getPreviewPanel(); private AbstractColorChooserPanel[] chooserPanels = new AbstractColorChooserPanel[0]; private boolean dragEnabled; /** * The selection model property name. */ public static final String SELECTION_MODEL_PROPERTY = "selectionModel"; /** * The preview panel property name. */ public static final String PREVIEW_PANEL_PROPERTY = "previewPanel"; /** * The chooserPanel array property name. */ public static final String CHOOSER_PANELS_PROPERTY = "chooserPanels"; /** * Shows a modal color-chooser dialog and blocks until the * dialog is hidden. If the user presses the "OK" button, then * this method hides/disposes the dialog and returns the selected color. * If the user presses the "Cancel" button or closes the dialog without * pressing "OK", then this method hides/disposes the dialog and returns * <code>null</code>. * * @param component the parent <code>Component</code> for the dialog * @param title the String containing the dialog's title * @param initialColor the initial Color set when the color-chooser is shown * @return the selected color or <code>null</code> if the user opted out * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static Color showDialog(Component component, String title, Color initialColor) throws HeadlessException { final JColorChooser pane = new JColorChooser(initialColor != null? initialColor : Color.white); ColorTracker ok = new ColorTracker(pane); JDialog dialog = createDialog(component, title, true, pane, ok, null); dialog.addComponentListener(new ColorChooserDialog.DisposeOnClose()); dialog.show(); // blocks until user brings dialog down... return ok.getColor(); } /** * Creates and returns a new dialog containing the specified * <code>ColorChooser</code> pane along with "OK", "Cancel", and "Reset" * buttons. If the "OK" or "Cancel" buttons are pressed, the dialog is * automatically hidden (but not disposed). If the "Reset" * button is pressed, the color-chooser's color will be reset to the * color which was set the last time <code>show</code> was invoked on the * dialog and the dialog will remain showing. * * @param c the parent component for the dialog * @param title the title for the dialog * @param modal a boolean. When true, the remainder of the program * is inactive until the dialog is closed. * @param chooserPane the color-chooser to be placed inside the dialog * @param okListener the ActionListener invoked when "OK" is pressed * @param cancelListener the ActionListener invoked when "Cancel" is pressed * @return a new dialog containing the color-chooser pane * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static JDialog createDialog(Component c, String title, boolean modal, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { Window window = JOptionPane.getWindowForComponent(c); ColorChooserDialog dialog; if (window instanceof Frame) { dialog = new ColorChooserDialog((Frame)window, title, modal, c, chooserPane, okListener, cancelListener); } else { dialog = new ColorChooserDialog((Dialog)window, title, modal, c, chooserPane, okListener, cancelListener); } dialog.getAccessibleContext().setAccessibleDescription(title); return dialog; } /** * Creates a color chooser pane with an initial color of white. */ public JColorChooser() { this(Color.white); } /** * Creates a color chooser pane with the specified initial color. * * @param initialColor the initial color set in the chooser */ public JColorChooser(Color initialColor) { this( new DefaultColorSelectionModel(initialColor) ); } /** * Creates a color chooser pane with the specified * <code>ColorSelectionModel</code>. * * @param model the <code>ColorSelectionModel</code> to be used */ public JColorChooser(ColorSelectionModel model) { selectionModel = model; updateUI(); dragEnabled = false; } /** * Returns the L&amp;F object that renders this component. * * @return the <code>ColorChooserUI</code> object that renders * this component */ public ColorChooserUI getUI() { return (ColorChooserUI)ui; } /** * Sets the L&amp;F object that renders this component. * * @param ui the <code>ColorChooserUI</code> L&amp;F object * @see UIDefaults#getUI * * @beaninfo * bound: true * hidden: true * description: The UI object that implements the color chooser's LookAndFeel. */ public void setUI(ColorChooserUI ui) { super.setUI(ui); } /** * Notification from the <code>UIManager</code> that the L&amp;F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see JComponent#updateUI */ public void updateUI() { setUI((ColorChooserUI)UIManager.getUI(this)); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ColorChooserUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Gets the current color value from the color chooser. * By default, this delegates to the model. * * @return the current color value of the color chooser */ public Color getColor() { return selectionModel.getSelectedColor(); } /** * Sets the current color of the color chooser to the specified color. * The <code>ColorSelectionModel</code> will fire a <code>ChangeEvent</code> * @param color the color to be set in the color chooser * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: false * hidden: false * description: The current color the chooser is to display. */ public void setColor(Color color) { selectionModel.setSelectedColor(color); } /** * Sets the current color of the color chooser to the * specified RGB color. Note that the values of red, green, * and blue should be between the numbers 0 and 255, inclusive. * * @param r an int specifying the amount of Red * @param g an int specifying the amount of Green * @param b an int specifying the amount of Blue * @exception IllegalArgumentException if r,g,b values are out of range * @see java.awt.Color */ public void setColor(int r, int g, int b) { setColor(new Color(r,g,b)); } /** * Sets the current color of the color chooser to the * specified color. * * @param c an integer value that sets the current color in the chooser * where the low-order 8 bits specify the Blue value, * the next 8 bits specify the Green value, and the 8 bits * above that specify the Red value. */ public void setColor(int c) { setColor((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF); } /** * Sets the <code>dragEnabled</code> property, * which must be <code>true</code> to enable * automatic drag handling (the first part of drag and drop) * on this component. * The <code>transferHandler</code> property needs to be set * to a non-<code>null</code> value for the drag to do * anything. The default value of the <code>dragEnabled</code> * property * is <code>false</code>. * * <p> * * When automatic drag handling is enabled, * most look and feels begin a drag-and-drop operation * when the user presses the mouse button over the preview panel. * Some look and feels might not support automatic drag and drop; * they will ignore this property. You can work around such * look and feels by modifying the component * to directly call the <code>exportAsDrag</code> method of a * <code>TransferHandler</code>. * * @param b the value to set the <code>dragEnabled</code> property to * @exception HeadlessException if * <code>b</code> is <code>true</code> and * <code>GraphicsEnvironment.isHeadless()</code> * returns <code>true</code> * * @since 1.4 * * @see java.awt.GraphicsEnvironment#isHeadless * @see #getDragEnabled * @see #setTransferHandler * @see TransferHandler * * @beaninfo * description: Determines whether automatic drag handling is enabled. * bound: false */ public void setDragEnabled(boolean b) { if (b && GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } dragEnabled = b; } /** * Gets the value of the <code>dragEnabled</code> property. * * @return the value of the <code>dragEnabled</code> property * @see #setDragEnabled * @since 1.4 */ public boolean getDragEnabled() { return dragEnabled; } /** * Sets the current preview panel. * This will fire a <code>PropertyChangeEvent</code> for the property * named "previewPanel". * * @param preview the <code>JComponent</code> which displays the current color * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: true * hidden: true * description: The UI component which displays the current color. */ public void setPreviewPanel(JComponent preview) { if (previewPanel != preview) { JComponent oldPreview = previewPanel; previewPanel = preview; firePropertyChange(JColorChooser.PREVIEW_PANEL_PROPERTY, oldPreview, preview); } } /** * Returns the preview panel that shows a chosen color. * * @return a <code>JComponent</code> object -- the preview panel */ public JComponent getPreviewPanel() { return previewPanel; } /** * Adds a color chooser panel to the color chooser. * * @param panel the <code>AbstractColorChooserPanel</code> to be added */ public void addChooserPanel( AbstractColorChooserPanel panel ) { AbstractColorChooserPanel[] oldPanels = getChooserPanels(); AbstractColorChooserPanel[] newPanels = new AbstractColorChooserPanel[oldPanels.length+1]; System.arraycopy(oldPanels, 0, newPanels, 0, oldPanels.length); newPanels[newPanels.length-1] = panel; setChooserPanels(newPanels); } /** * Removes the Color Panel specified. * * @param panel a string that specifies the panel to be removed * @return the color panel * @exception IllegalArgumentException if panel is not in list of * known chooser panels */ public AbstractColorChooserPanel removeChooserPanel( AbstractColorChooserPanel panel ) { int containedAt = -1; for (int i = 0; i < chooserPanels.length; i++) { if (chooserPanels[i] == panel) { containedAt = i; break; } } if (containedAt == -1) { throw new IllegalArgumentException("chooser panel not in this chooser"); } AbstractColorChooserPanel[] newArray = new AbstractColorChooserPanel[chooserPanels.length-1]; if (containedAt == chooserPanels.length-1) { // at end System.arraycopy(chooserPanels, 0, newArray, 0, newArray.length); } else if (containedAt == 0) { // at start System.arraycopy(chooserPanels, 1, newArray, 0, newArray.length); } else { // in middle System.arraycopy(chooserPanels, 0, newArray, 0, containedAt); System.arraycopy(chooserPanels, containedAt+1, newArray, containedAt, (chooserPanels.length - containedAt - 1)); } setChooserPanels(newArray); return panel; } /** * Specifies the Color Panels used to choose a color value. * * @param panels an array of <code>AbstractColorChooserPanel</code> * objects * * @beaninfo * bound: true * hidden: true * description: An array of different chooser types. */ public void setChooserPanels( AbstractColorChooserPanel[] panels) { AbstractColorChooserPanel[] oldValue = chooserPanels; chooserPanels = panels; firePropertyChange(CHOOSER_PANELS_PROPERTY, oldValue, panels); } /** * Returns the specified color panels. * * @return an array of <code>AbstractColorChooserPanel</code> objects */ public AbstractColorChooserPanel[] getChooserPanels() { return chooserPanels; } /** * Returns the data model that handles color selections. * * @return a <code>ColorSelectionModel</code> object */ public ColorSelectionModel getSelectionModel() { return selectionModel; } /** * Sets the model containing the selected color. * * @param newModel the new <code>ColorSelectionModel</code> object * * @beaninfo * bound: true * hidden: true * description: The model which contains the currently selected color. */ public void setSelectionModel(ColorSelectionModel newModel ) { ColorSelectionModel oldModel = selectionModel; selectionModel = newModel; firePropertyChange(JColorChooser.SELECTION_MODEL_PROPERTY, oldModel, newModel); } /** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } } /** * Returns a string representation of this <code>JColorChooser</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JColorChooser</code> */ protected String paramString() { StringBuffer chooserPanelsString = new StringBuffer(""); for (int i=0; i<chooserPanels.length; i++) { chooserPanelsString.append("[" + chooserPanels[i].toString() + "]"); } String previewPanelString = (previewPanel != null ? previewPanel.toString() : ""); return super.paramString() + ",chooserPanels=" + chooserPanelsString.toString() + ",previewPanel=" + previewPanelString; } ///////////////// // Accessibility support //////////////// protected AccessibleContext accessibleContext = null; /** * Gets the AccessibleContext associated with this JColorChooser. * For color choosers, the AccessibleContext takes the form of an * AccessibleJColorChooser. * A new AccessibleJColorChooser instance is created if necessary. * * @return an AccessibleJColorChooser that serves as the * AccessibleContext of this JColorChooser */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJColorChooser(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JColorChooser</code> class. It provides an implementation of the * Java Accessibility API appropriate to color chooser user-interface * elements. */ protected class AccessibleJColorChooser extends AccessibleJComponent { /** * Get the role of this object. * * @return an instance of AccessibleRole describing the role of the * object * @see AccessibleRole */ public AccessibleRole getAccessibleRole() { return AccessibleRole.COLOR_CHOOSER; } } // inner class AccessibleJColorChooser } /* * Class which builds a color chooser dialog consisting of * a JColorChooser with "Ok", "Cancel", and "Reset" buttons. * * Note: This needs to be fixed to deal with localization! */ class ColorChooserDialog extends JDialog { private Color initialColor; private JColorChooser chooserPane; private JButton cancelButton; public ColorChooserDialog(Dialog owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } public ColorChooserDialog(Frame owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } protected void initColorChooserDialog(Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) { //setResizable(false); this.chooserPane = chooserPane; Locale locale = getLocale(); String okString = UIManager.getString("ColorChooser.okText", locale); String cancelString = UIManager.getString("ColorChooser.cancelText", locale); String resetString = UIManager.getString("ColorChooser.resetText", locale); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(chooserPane, BorderLayout.CENTER); /* * Create Lower button panel */ JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); JButton okButton = new JButton(okString); getRootPane().setDefaultButton(okButton); okButton.getAccessibleContext().setAccessibleDescription(okString); okButton.setActionCommand("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (okListener != null) { okButton.addActionListener(okListener); } buttonPane.add(okButton); cancelButton = new JButton(cancelString); cancelButton.getAccessibleContext().setAccessibleDescription(cancelString); // The following few lines are used to register esc to close the dialog Action cancelKeyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { ((AbstractButton)e.getSource()).fireActionPerformed(e); } }; KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); InputMap inputMap = cancelButton.getInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = cancelButton.getActionMap(); if (inputMap != null && actionMap != null) { inputMap.put(cancelKeyStroke, "cancel"); actionMap.put("cancel", cancelKeyAction); } // end esc handling cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (cancelListener != null) { cancelButton.addActionListener(cancelListener); } buttonPane.add(cancelButton); JButton resetButton = new JButton(resetString); resetButton.getAccessibleContext().setAccessibleDescription(resetString); resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reset(); } }); int mnemonic = SwingUtilities2.getUIDefaultsInt("ColorChooser.resetMnemonic", locale, -1); if (mnemonic != -1) { resetButton.setMnemonic(mnemonic); } buttonPane.add(resetButton); contentPane.add(buttonPane, BorderLayout.SOUTH); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); if (supportsWindowDecorations) { getRootPane().setWindowDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG); } } applyComponentOrientation(((c == null) ? getRootPane() : c).getComponentOrientation()); pack(); setLocationRelativeTo(c); this.addWindowListener(new Closer()); } public void show() { initialColor = chooserPane.getColor(); super.show(); } public void reset() { chooserPane.setColor(initialColor); } class Closer extends WindowAdapter implements Serializable{ public void windowClosing(WindowEvent e) { cancelButton.doClick(0); Window w = e.getWindow(); w.hide(); } } static class DisposeOnClose extends ComponentAdapter implements Serializable{ public void componentHidden(ComponentEvent e) { Window w = (Window)e.getComponent(); w.dispose(); } } } class ColorTracker implements ActionListener, Serializable { JColorChooser chooser; Color color; public ColorTracker(JColorChooser c) { chooser = c; } public void actionPerformed(ActionEvent e) { color = chooser.getColor(); } public Color getColor() { return color; } }
149318_0
import lejos.nxt.*; public class Lego { public static void main(String[] args) { int bedrag = 10; int tijdelijk; int motora =9; int motorb =19; int motorc = 49; int groot = 1; int normaal = 0; int klein = 0; //normaal biljetten if(groot==1){ while(bedrag>0) { while(bedrag>motorc) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>motorb) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>motora) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } //als je meer twintigjes wilt if(normaal==1) { while(bedrag >0) { while(bedrag>139) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>19) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } if(klein ==1) { while(bedrag >0) { while(bedrag>99) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>60) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } } }
wvanderp/project-3-4
web/Lego.java
1,715
//als je meer twintigjes wilt
line_comment
nl
import lejos.nxt.*; public class Lego { public static void main(String[] args) { int bedrag = 10; int tijdelijk; int motora =9; int motorb =19; int motorc = 49; int groot = 1; int normaal = 0; int klein = 0; //normaal biljetten if(groot==1){ while(bedrag>0) { while(bedrag>motorc) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>motorb) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>motora) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } //als je<SUF> if(normaal==1) { while(bedrag >0) { while(bedrag>139) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>19) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } if(klein ==1) { while(bedrag >0) { while(bedrag>99) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>60) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } } }
44747_7
package com.github.wycm.zhihu; import com.github.wycm.zhihu.task.ZhihuProxyPageDownloadTask; import com.github.wycm.zhihu.task.ZhihuTopicPageTask; public class ZhihuConstants { public static final String PROXY_PAGE_REDIS_KEY_PREFIX = "Zhihu:proxy:"; public static final String ZHIHU_PAGE_REDIS_KEY_PREFIX = "Zhihu:zhihu:"; public final static String USER_FOLLOWEES_URL = "https://www.zhihu.com/api/v4/members/%s/followees?" + "include=data[*].educations,employments,answer_count,business,locations,articles_count,follower_count," + "gender,following_count,question_count,voteup_count,thanked_count,is_followed,is_following," + "badge[?(type=best_answerer)].topics&offset=%d&limit=20"; public final static String PROXY_PAGE_DOWNLOAD_TASK_LOCK_KEY_PREFIX = ZhihuProxyPageDownloadTask.class.getSimpleName() + "LockKey:"; public final static String PROXY_PAGE_DOWNLOAD_TASK_QUEUE_NAME = ZhihuProxyPageDownloadTask.class.getSimpleName() + "Queue"; public final static String TOPIC_PAGE_TASK_LOCK_KEY_PREFIX = ZhihuTopicPageTask.class.getSimpleName() + "LockKey:"; public final static String TOPIC_PAGE_TASK_QUEUE_NAME = ZhihuTopicPageTask.class.getSimpleName() + "Queue"; // public final static String TOPIC_ACTIVITY_PAGE_TASK_LOCK_KEY_PREFIX = TopicActivityPageTask.class.getSimpleName() + "LockKey:"; // // public final static String TOPIC_ACTIVITY_PAGE_TASK_QUEUE_NAME = TopicActivityPageTask.class.getSimpleName() + "Queue"; // // public final static String TOPIC_ACTIVITY_PAGE_TASK_PERSISTENCE_QUEUE_NAME = TopicActivityPageTask.class.getSimpleName() + "PersistenceQueue"; // // public final static String QUESTION_ANSWER_TASK_LOCK_KEY_PREFIX = QuestionAnswerPageTask.class.getSimpleName() + "LockKey:"; // // public final static String QUESTION_ANSWER_TASK_QUEUE_NAME = QuestionAnswerPageTask.class.getSimpleName() + "Queue"; // // public final static String QUESTION_ANSWER_TASK_PERSISTENCE_QUEUE_NAME = QuestionAnswerPageTask.class.getSimpleName() + "PersistenceQueue"; public final static String ANSWER_URL_TEMPLATE = "https://www.zhihu.com/question/${questionId}/answer/${answerId}"; public final static String QUESTION_URL_TEMPLATE = "https://www.zhihu.com/question/${questionId}"; public final static String ARTICLE_URL_TEMPLATE = "https://zhuanlan.zhihu.com/p/${articleId}"; public final static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; public final static String ZHIHU_ROOT_TOPIC_CHILDREN_URL_TEMPLATE = "https://www.zhihu.com/api/v3/topics/${topicId}/children"; /** * 话题动态url */ public final static String ZHIHU_TOPIC_ACTIVITY_URL_TEMPLATE = "https://www.zhihu.com/api/v4/topics/${topicId}/feeds/timeline_activity?include=data%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Danswer%29%5D.target.content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Danswer%29%5D.target.is_normal%2Ccomment_count%2Cvoteup_count%2Ccontent%2Crelevant_info%2Cexcerpt.author.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Darticle%29%5D.target.content%2Cvoteup_count%2Ccomment_count%2Cvoting%2Cauthor.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Dpeople%29%5D.target.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Danswer%29%5D.target.annotation_detail%2Ccontent%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%3Bdata%5B%3F%28target.type%3Danswer%29%5D.target.author.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Darticle%29%5D.target.annotation_detail%2Ccontent%2Cauthor.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dquestion%29%5D.target.annotation_detail%2Ccomment_count&limit=20&offset=0"; /** * 问题答案url */ public final static String ZHIHU_ANSWER_URL_TEMPLATE = "https://www.zhihu.com/api/v4/questions/${questionId}/answers?data%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics=&data%5B%2A%5D.mark_infos%5B%2A%5D.url=&include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp&limit=${limit}&offset=${offset}&sort_by=created"; /** * 问题详细detail url */ public final static String ZHIHU_QUESTION_DETAIL_URL_TEMPLATE = "https://www.zhihu.com/question/${questionId}"; }
wycm/zhihu-crawler
zhihu/src/main/java/com/github/wycm/zhihu/ZhihuConstants.java
2,028
/** * 问题答案url */
block_comment
nl
package com.github.wycm.zhihu; import com.github.wycm.zhihu.task.ZhihuProxyPageDownloadTask; import com.github.wycm.zhihu.task.ZhihuTopicPageTask; public class ZhihuConstants { public static final String PROXY_PAGE_REDIS_KEY_PREFIX = "Zhihu:proxy:"; public static final String ZHIHU_PAGE_REDIS_KEY_PREFIX = "Zhihu:zhihu:"; public final static String USER_FOLLOWEES_URL = "https://www.zhihu.com/api/v4/members/%s/followees?" + "include=data[*].educations,employments,answer_count,business,locations,articles_count,follower_count," + "gender,following_count,question_count,voteup_count,thanked_count,is_followed,is_following," + "badge[?(type=best_answerer)].topics&offset=%d&limit=20"; public final static String PROXY_PAGE_DOWNLOAD_TASK_LOCK_KEY_PREFIX = ZhihuProxyPageDownloadTask.class.getSimpleName() + "LockKey:"; public final static String PROXY_PAGE_DOWNLOAD_TASK_QUEUE_NAME = ZhihuProxyPageDownloadTask.class.getSimpleName() + "Queue"; public final static String TOPIC_PAGE_TASK_LOCK_KEY_PREFIX = ZhihuTopicPageTask.class.getSimpleName() + "LockKey:"; public final static String TOPIC_PAGE_TASK_QUEUE_NAME = ZhihuTopicPageTask.class.getSimpleName() + "Queue"; // public final static String TOPIC_ACTIVITY_PAGE_TASK_LOCK_KEY_PREFIX = TopicActivityPageTask.class.getSimpleName() + "LockKey:"; // // public final static String TOPIC_ACTIVITY_PAGE_TASK_QUEUE_NAME = TopicActivityPageTask.class.getSimpleName() + "Queue"; // // public final static String TOPIC_ACTIVITY_PAGE_TASK_PERSISTENCE_QUEUE_NAME = TopicActivityPageTask.class.getSimpleName() + "PersistenceQueue"; // // public final static String QUESTION_ANSWER_TASK_LOCK_KEY_PREFIX = QuestionAnswerPageTask.class.getSimpleName() + "LockKey:"; // // public final static String QUESTION_ANSWER_TASK_QUEUE_NAME = QuestionAnswerPageTask.class.getSimpleName() + "Queue"; // // public final static String QUESTION_ANSWER_TASK_PERSISTENCE_QUEUE_NAME = QuestionAnswerPageTask.class.getSimpleName() + "PersistenceQueue"; public final static String ANSWER_URL_TEMPLATE = "https://www.zhihu.com/question/${questionId}/answer/${answerId}"; public final static String QUESTION_URL_TEMPLATE = "https://www.zhihu.com/question/${questionId}"; public final static String ARTICLE_URL_TEMPLATE = "https://zhuanlan.zhihu.com/p/${articleId}"; public final static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; public final static String ZHIHU_ROOT_TOPIC_CHILDREN_URL_TEMPLATE = "https://www.zhihu.com/api/v3/topics/${topicId}/children"; /** * 话题动态url */ public final static String ZHIHU_TOPIC_ACTIVITY_URL_TEMPLATE = "https://www.zhihu.com/api/v4/topics/${topicId}/feeds/timeline_activity?include=data%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Danswer%29%5D.target.content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Danswer%29%5D.target.is_normal%2Ccomment_count%2Cvoteup_count%2Ccontent%2Crelevant_info%2Cexcerpt.author.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Darticle%29%5D.target.content%2Cvoteup_count%2Ccomment_count%2Cvoting%2Cauthor.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Dpeople%29%5D.target.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Danswer%29%5D.target.annotation_detail%2Ccontent%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%3Bdata%5B%3F%28target.type%3Danswer%29%5D.target.author.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Darticle%29%5D.target.annotation_detail%2Ccontent%2Cauthor.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dquestion%29%5D.target.annotation_detail%2Ccomment_count&limit=20&offset=0"; /** * 问题答案url <SUF>*/ public final static String ZHIHU_ANSWER_URL_TEMPLATE = "https://www.zhihu.com/api/v4/questions/${questionId}/answers?data%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics=&data%5B%2A%5D.mark_infos%5B%2A%5D.url=&include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp&limit=${limit}&offset=${offset}&sort_by=created"; /** * 问题详细detail url */ public final static String ZHIHU_QUESTION_DETAIL_URL_TEMPLATE = "https://www.zhihu.com/question/${questionId}"; }
133266_1
package com.wyona.katie.answers; import com.fasterxml.jackson.databind.JsonNode; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; /** * Add to a Katie domain a QnA with an answer containing <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarPaper(ak-entity:number,'de')</ak-exec></p> or <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarCardboard(ak-entity:number,'de')</ak-exec></p> * IMPORTANT: Make sure that NER can recognize numbers, like for example set <ner impl="MOCK"/> inside domain configuration */ @Slf4j public class OpenERZ { private String baseUrl = "https://openerz.metaodi.ch"; /** * */ public OpenERZ() { } /** * @param zip ZIP code, e.g. "8044" * @param language Language of answer, e.g. "de" or "en" */ public String getCalendarPaper(String zip, String language) { if (zip == null) { return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Papiersammlung 8032?'"; } List<Date> dates = getDates(zip, "paper"); Locale locale = new Locale(language); java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale); StringBuilder answer = new StringBuilder(); if (dates.size() > 0) { //answer.append("<p>Die Abholtermine für Papier an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>"); answer.append("<p>Die Abholtermine für Papier in " + zip + " Zürich sind wie folgt:</p>"); answer.append("<ul>"); for (Date date : dates) { answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023 } answer.append("</ul>"); } else { answer.append("<p>Leider konnten keine Abholtermine für Papier in " + zip + " Zürich gefunden werden.</p>"); } return answer.toString(); } /** * @param zip ZIP code, e.g. "8044" * @param language Language of answer, e.g. "de" or "en" */ public String getCalendarCardboard(String zip, String language) { if (zip == null) { return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Kartonsammlung 8032?'"; } List<Date> dates = getDates(zip, "cardboard"); Locale locale = new Locale(language); java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale); StringBuilder answer = new StringBuilder(); if (dates.size() > 0) { //answer.append("<p>Die Abholtermine für Karton an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>"); answer.append("<p>Die Abholtermine für Karton in " + zip + " Zürich sind wie folgt:</p>"); answer.append("<ul>"); for (Date date : dates) { answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023 } answer.append("</ul>"); } else { answer.append("<p>Leider konnten keine Abholtermine für Karton in " + zip + " Zürich gefunden werden.</p>"); } return answer.toString(); } /** * @param zip ZIP code, e.g. "8044" * @param type Waste type, e.g. "paper" or "cardboard" */ private List<Date> getDates(String zip, String type) { List<Date> dates = new ArrayList<Date>(); java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd"); // INFO: See https://openerz.metaodi.ch/documentation Date current = new Date(); String requestUrl = baseUrl + "/api/calendar.json?types=" + type + "&zip=" + zip + "&start=" + dateFormat.format(current) + "&sort=date&offset=0&limit=500"; log.info("Get dates from '" + requestUrl + "' ..."); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = getHttpHeaders(); headers.set("Accept", "application/json"); //headers.set("Content-Type", "application/json; charset=UTF-8"); HttpEntity<String> request = new HttpEntity<String>(headers); try { ResponseEntity<JsonNode> response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, JsonNode.class); JsonNode bodyNode = response.getBody(); log.info("Response JSON: " + bodyNode); JsonNode resultNode = bodyNode.get("result"); if (resultNode.isArray()) { for (int i = 0; i < resultNode.size(); i++) { JsonNode dateNode = resultNode.get(i); String dateAsString = dateNode.get("date").asText(); // INFO: 2023-07-04" try { dates.add(dateFormat.parse(dateAsString)); } catch (Exception e) { log.error(e.getMessage(), e); } } } else { log.error("No dates received!"); } } catch (Exception e) { log.error(e.getMessage(), e); } return dates; } /** * */ private HttpHeaders getHttpHeaders() { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); //headers.set("Content-Type", "application/json; charset=UTF-8"); return headers; } }
wyona/katie-backend
src/main/java/com/wyona/katie/answers/OpenERZ.java
1,758
/** * @param zip ZIP code, e.g. "8044" * @param language Language of answer, e.g. "de" or "en" */
block_comment
nl
package com.wyona.katie.answers; import com.fasterxml.jackson.databind.JsonNode; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; /** * Add to a Katie domain a QnA with an answer containing <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarPaper(ak-entity:number,'de')</ak-exec></p> or <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarCardboard(ak-entity:number,'de')</ak-exec></p> * IMPORTANT: Make sure that NER can recognize numbers, like for example set <ner impl="MOCK"/> inside domain configuration */ @Slf4j public class OpenERZ { private String baseUrl = "https://openerz.metaodi.ch"; /** * */ public OpenERZ() { } /** * @param zip ZIP<SUF>*/ public String getCalendarPaper(String zip, String language) { if (zip == null) { return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Papiersammlung 8032?'"; } List<Date> dates = getDates(zip, "paper"); Locale locale = new Locale(language); java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale); StringBuilder answer = new StringBuilder(); if (dates.size() > 0) { //answer.append("<p>Die Abholtermine für Papier an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>"); answer.append("<p>Die Abholtermine für Papier in " + zip + " Zürich sind wie folgt:</p>"); answer.append("<ul>"); for (Date date : dates) { answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023 } answer.append("</ul>"); } else { answer.append("<p>Leider konnten keine Abholtermine für Papier in " + zip + " Zürich gefunden werden.</p>"); } return answer.toString(); } /** * @param zip ZIP code, e.g. "8044" * @param language Language of answer, e.g. "de" or "en" */ public String getCalendarCardboard(String zip, String language) { if (zip == null) { return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Kartonsammlung 8032?'"; } List<Date> dates = getDates(zip, "cardboard"); Locale locale = new Locale(language); java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale); StringBuilder answer = new StringBuilder(); if (dates.size() > 0) { //answer.append("<p>Die Abholtermine für Karton an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>"); answer.append("<p>Die Abholtermine für Karton in " + zip + " Zürich sind wie folgt:</p>"); answer.append("<ul>"); for (Date date : dates) { answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023 } answer.append("</ul>"); } else { answer.append("<p>Leider konnten keine Abholtermine für Karton in " + zip + " Zürich gefunden werden.</p>"); } return answer.toString(); } /** * @param zip ZIP code, e.g. "8044" * @param type Waste type, e.g. "paper" or "cardboard" */ private List<Date> getDates(String zip, String type) { List<Date> dates = new ArrayList<Date>(); java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd"); // INFO: See https://openerz.metaodi.ch/documentation Date current = new Date(); String requestUrl = baseUrl + "/api/calendar.json?types=" + type + "&zip=" + zip + "&start=" + dateFormat.format(current) + "&sort=date&offset=0&limit=500"; log.info("Get dates from '" + requestUrl + "' ..."); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = getHttpHeaders(); headers.set("Accept", "application/json"); //headers.set("Content-Type", "application/json; charset=UTF-8"); HttpEntity<String> request = new HttpEntity<String>(headers); try { ResponseEntity<JsonNode> response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, JsonNode.class); JsonNode bodyNode = response.getBody(); log.info("Response JSON: " + bodyNode); JsonNode resultNode = bodyNode.get("result"); if (resultNode.isArray()) { for (int i = 0; i < resultNode.size(); i++) { JsonNode dateNode = resultNode.get(i); String dateAsString = dateNode.get("date").asText(); // INFO: 2023-07-04" try { dates.add(dateFormat.parse(dateAsString)); } catch (Exception e) { log.error(e.getMessage(), e); } } } else { log.error("No dates received!"); } } catch (Exception e) { log.error(e.getMessage(), e); } return dates; } /** * */ private HttpHeaders getHttpHeaders() { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); //headers.set("Content-Type", "application/json; charset=UTF-8"); return headers; } }
63221_2
package apps.ganzenbord; import model.ganzenbord.Player; import java.util.*; public class GanzenbordApplication { public static void main(String[] args) { System.out.println("Welkom bij het Ganzenbord!"); System.out.println("--------------------------"); Scanner scanner = new Scanner(System.in); System.out.println("Met hoeveel personen wil je het spel spelen?"); int numberOfPlayers = scanner.nextInt(); System.out.println("Je speelt het spel met " + numberOfPlayers + " speler(s)."); Player[] players = new Player[numberOfPlayers]; for (int i = 0; i < players.length; i++) { int playerNumber = i + 1; scanner = new Scanner(System.in); System.out.println("Naam speler " + playerNumber + "?"); String playerName = scanner.nextLine(); players[i] = new Player(playerName); } System.out.println("--------------------------"); System.out.println("De volgende speler(s) doe(n)(t) mee:"); for (Player player : players) { System.out.println(player.getName()); } System.out.println("--------------------------"); /* start game */ System.out.println("Het spel begint!"); System.out.println("--------------------------"); /* variables */ boolean endGame = false; int brugNumber = 6; int herbergNumber = 19; int putNumber = 31; int doolhofNumber = 42; int inJail = 52; int doodNumber = 58; int finish = 63; List<Integer> backToStart = Arrays.asList(25, 45); List<Integer> bonusPlaces = Arrays.asList(10, 20, 30, 40, 50, 60); outer: do { for (Player player : players) { if (endGame) { break outer; } else if (!player.isActivePlayer() && !endGame) { /* logic for skipTurn */ if (player.isSkipTurn() && player.getSkipNumberOfTurns() > 0) { int tempSkipNumberOfTurns = player.getSkipNumberOfTurns(); player.setSkipNumberOfTurns(tempSkipNumberOfTurns - 1); if (player.getSkipNumberOfTurns() == 0) { player.setSkipTurn(false); } } else if (player.isInPut()) { continue; } else { System.out.println(player.getName() + " is aan de beurt. Gooi je dobbelsteen (g)."); do { int thrownNumber = throwDice(); int currentPlace = player.getCurrentPlace(); player.setCurrentPlace(currentPlace += thrownNumber); /* special place: 10, 20, 30, 40, 50 en 60 houdt in dat je het geworpen aantal nog een keer loopt. */ if (bonusPlaces.contains(player.getCurrentPlace())) { System.out.println("Je hebt " + thrownNumber + " gegooid, je staat op plaats " + player.getCurrentPlace() + "."); int tempCurrentPlace = player.getCurrentPlace(); player.setCurrentPlace(tempCurrentPlace += thrownNumber); System.out.println("Yeah! Dit is een bonusplaats! Je bent nog eens " + thrownNumber + " vooruit gegaan en staat nu op " + player.getCurrentPlace() + "."); if (player.getCurrentPlace() == putNumber) { inPutLogica(players, player); } endGame = currentPlaceAboveFinish(endGame, finish, player, thrownNumber); } /* special place: 25 en 45 is terug naar start. */ else if (backToStart.contains(player.getCurrentPlace())) { System.out.println("Helaas! Je staat op " + player.getCurrentPlace() + ". Je moet terug naar start."); player.setCurrentPlace(0); } /* special price: 31, put, Wie hier komt moet er blijven tot een andere speler er komt. Degene die er het eerst was speelt dan verder. */ else if (player.getCurrentPlace() == putNumber) { inPutLogica(players, player); } /* special place: 52, gevangenis, drie beurten overslaan */ else if (player.getCurrentPlace() == inJail) { System.out.println("Helaas! Je moet 3 beurten overslaan."); player.setSkipTurn(true); player.setSkipNumberOfTurns(3); } else if (player.getCurrentPlace() == brugNumber) { System.out.println("Yeah! De brug. Je gaat verder naar 12!"); player.setCurrentPlace(12); } else if (player.getCurrentPlace() == doolhofNumber) { System.out.println("Helaas! Je bent in het doolhof. Je moet terug naar 39."); player.setCurrentPlace(39); } else if (player.getCurrentPlace() == doodNumber) { System.out.println("Helaas! Je bent dood. Je gaat terug naar start."); player.setCurrentPlace(0); } /* 19, herberg, Een beurt overslaan */ else if (player.getCurrentPlace() == herbergNumber) { System.out.println("Helaas! Je moet een beurt overslaan."); player.setSkipTurn(true); player.setSkipNumberOfTurns(1); } /* finish */ else if (player.getCurrentPlace() >= finish) { endGame = currentPlaceAboveFinish(endGame, finish, player, thrownNumber); } else { System.out.println("Je hebt " + thrownNumber + " gegooid, je staat op plaats " + player.getCurrentPlace() + ", niks aan de hand."); } player.setActivePlayer(false); System.out.println("--------------------------"); System.out.println("Actuele plaatsen:"); for (Player element : players) { System.out.println(element.getName() + ": " + element.getCurrentPlace()); } System.out.println("--------------------------"); } while (player.isActivePlayer() && !endGame); } } } } while (!endGame); } private static void inPutLogica(Player[] players, Player player) { for (Player element : players) { if (element.isInPut() && (!element.getName().equals(player.getName()))) { element.setInPut(false); player.setInPut(true); } else { System.out.println("Helaas! In de put. Je mag verder spelen als er een andere speler in komt"); player.setInPut(true); } } } private static boolean currentPlaceAboveFinish(boolean endGame, int finish, Player player, int thrownNumber) { if (player.getCurrentPlace() >= finish) { if (player.getCurrentPlace() == finish) { System.out.println("Yeah! " + player.getName() + " heeft gewonnen!"); player.setWinner(true); endGame = true; } else { System.out.println("Je hebt " + thrownNumber + " gegooid."); int tooManyThrownEyes = player.getCurrentPlace() - finish; player.setCurrentPlace(finish - tooManyThrownEyes); System.out.println("Helaas! Dat is te ver. Je moet precies op " + finish + " eindigen om te winnen. Je staat nu weer op " + player.getCurrentPlace() + "."); endGame = false; } } return endGame; } private static int throwDice() { Random random = new Random(); return random.nextInt(6) + 1; } }
wytzejan/Java4DevOps
src/apps/ganzenbord/GanzenbordApplication.java
2,270
/* special place: 25 en 45 is terug naar start. */
block_comment
nl
package apps.ganzenbord; import model.ganzenbord.Player; import java.util.*; public class GanzenbordApplication { public static void main(String[] args) { System.out.println("Welkom bij het Ganzenbord!"); System.out.println("--------------------------"); Scanner scanner = new Scanner(System.in); System.out.println("Met hoeveel personen wil je het spel spelen?"); int numberOfPlayers = scanner.nextInt(); System.out.println("Je speelt het spel met " + numberOfPlayers + " speler(s)."); Player[] players = new Player[numberOfPlayers]; for (int i = 0; i < players.length; i++) { int playerNumber = i + 1; scanner = new Scanner(System.in); System.out.println("Naam speler " + playerNumber + "?"); String playerName = scanner.nextLine(); players[i] = new Player(playerName); } System.out.println("--------------------------"); System.out.println("De volgende speler(s) doe(n)(t) mee:"); for (Player player : players) { System.out.println(player.getName()); } System.out.println("--------------------------"); /* start game */ System.out.println("Het spel begint!"); System.out.println("--------------------------"); /* variables */ boolean endGame = false; int brugNumber = 6; int herbergNumber = 19; int putNumber = 31; int doolhofNumber = 42; int inJail = 52; int doodNumber = 58; int finish = 63; List<Integer> backToStart = Arrays.asList(25, 45); List<Integer> bonusPlaces = Arrays.asList(10, 20, 30, 40, 50, 60); outer: do { for (Player player : players) { if (endGame) { break outer; } else if (!player.isActivePlayer() && !endGame) { /* logic for skipTurn */ if (player.isSkipTurn() && player.getSkipNumberOfTurns() > 0) { int tempSkipNumberOfTurns = player.getSkipNumberOfTurns(); player.setSkipNumberOfTurns(tempSkipNumberOfTurns - 1); if (player.getSkipNumberOfTurns() == 0) { player.setSkipTurn(false); } } else if (player.isInPut()) { continue; } else { System.out.println(player.getName() + " is aan de beurt. Gooi je dobbelsteen (g)."); do { int thrownNumber = throwDice(); int currentPlace = player.getCurrentPlace(); player.setCurrentPlace(currentPlace += thrownNumber); /* special place: 10, 20, 30, 40, 50 en 60 houdt in dat je het geworpen aantal nog een keer loopt. */ if (bonusPlaces.contains(player.getCurrentPlace())) { System.out.println("Je hebt " + thrownNumber + " gegooid, je staat op plaats " + player.getCurrentPlace() + "."); int tempCurrentPlace = player.getCurrentPlace(); player.setCurrentPlace(tempCurrentPlace += thrownNumber); System.out.println("Yeah! Dit is een bonusplaats! Je bent nog eens " + thrownNumber + " vooruit gegaan en staat nu op " + player.getCurrentPlace() + "."); if (player.getCurrentPlace() == putNumber) { inPutLogica(players, player); } endGame = currentPlaceAboveFinish(endGame, finish, player, thrownNumber); } /* special place: 25<SUF>*/ else if (backToStart.contains(player.getCurrentPlace())) { System.out.println("Helaas! Je staat op " + player.getCurrentPlace() + ". Je moet terug naar start."); player.setCurrentPlace(0); } /* special price: 31, put, Wie hier komt moet er blijven tot een andere speler er komt. Degene die er het eerst was speelt dan verder. */ else if (player.getCurrentPlace() == putNumber) { inPutLogica(players, player); } /* special place: 52, gevangenis, drie beurten overslaan */ else if (player.getCurrentPlace() == inJail) { System.out.println("Helaas! Je moet 3 beurten overslaan."); player.setSkipTurn(true); player.setSkipNumberOfTurns(3); } else if (player.getCurrentPlace() == brugNumber) { System.out.println("Yeah! De brug. Je gaat verder naar 12!"); player.setCurrentPlace(12); } else if (player.getCurrentPlace() == doolhofNumber) { System.out.println("Helaas! Je bent in het doolhof. Je moet terug naar 39."); player.setCurrentPlace(39); } else if (player.getCurrentPlace() == doodNumber) { System.out.println("Helaas! Je bent dood. Je gaat terug naar start."); player.setCurrentPlace(0); } /* 19, herberg, Een beurt overslaan */ else if (player.getCurrentPlace() == herbergNumber) { System.out.println("Helaas! Je moet een beurt overslaan."); player.setSkipTurn(true); player.setSkipNumberOfTurns(1); } /* finish */ else if (player.getCurrentPlace() >= finish) { endGame = currentPlaceAboveFinish(endGame, finish, player, thrownNumber); } else { System.out.println("Je hebt " + thrownNumber + " gegooid, je staat op plaats " + player.getCurrentPlace() + ", niks aan de hand."); } player.setActivePlayer(false); System.out.println("--------------------------"); System.out.println("Actuele plaatsen:"); for (Player element : players) { System.out.println(element.getName() + ": " + element.getCurrentPlace()); } System.out.println("--------------------------"); } while (player.isActivePlayer() && !endGame); } } } } while (!endGame); } private static void inPutLogica(Player[] players, Player player) { for (Player element : players) { if (element.isInPut() && (!element.getName().equals(player.getName()))) { element.setInPut(false); player.setInPut(true); } else { System.out.println("Helaas! In de put. Je mag verder spelen als er een andere speler in komt"); player.setInPut(true); } } } private static boolean currentPlaceAboveFinish(boolean endGame, int finish, Player player, int thrownNumber) { if (player.getCurrentPlace() >= finish) { if (player.getCurrentPlace() == finish) { System.out.println("Yeah! " + player.getName() + " heeft gewonnen!"); player.setWinner(true); endGame = true; } else { System.out.println("Je hebt " + thrownNumber + " gegooid."); int tooManyThrownEyes = player.getCurrentPlace() - finish; player.setCurrentPlace(finish - tooManyThrownEyes); System.out.println("Helaas! Dat is te ver. Je moet precies op " + finish + " eindigen om te winnen. Je staat nu weer op " + player.getCurrentPlace() + "."); endGame = false; } } return endGame; } private static int throwDice() { Random random = new Random(); return random.nextInt(6) + 1; } }
13273_1
package net.vulkanmod.render.chunk; import net.minecraft.util.Mth; import net.vulkanmod.render.chunk.buffer.DrawBuffers; import net.vulkanmod.render.chunk.util.CircularIntList; import net.vulkanmod.render.chunk.util.Util; import org.joml.Vector3i; public class ChunkAreaManager { static final int WIDTH = 8; static final int HEIGHT = 8; static final int AREA_SH_XZ = Util.flooredLog(WIDTH); static final int AREA_SH_Y = Util.flooredLog(HEIGHT); static final int SEC_SH = 4; static final int BLOCK_TO_AREA_SH_XZ = AREA_SH_XZ + SEC_SH; static final int BLOCK_TO_AREA_SH_Y = AREA_SH_Y + SEC_SH; public final int size; final int sectionGridWidth; final int xzSize; final int ySize; final int minHeight; final ChunkArea[] chunkAreasArr; int prevX; int prevZ; public ChunkAreaManager(int width, int height, int minHeight) { this.minHeight = minHeight; this.sectionGridWidth = width; int t = (width >> AREA_SH_XZ) + 2; int relativeHeight = height - (minHeight >> 4); this.ySize = (relativeHeight & 0x5) == 0 ? (relativeHeight >> AREA_SH_Y) : (relativeHeight >> AREA_SH_Y) + 1; //check if width is even if ((t & 1) == 0) t++; this.xzSize = t; //TODO make even size work this.size = xzSize * ySize * xzSize; this.chunkAreasArr = new ChunkArea[size]; for (int j = 0; j < this.xzSize; ++j) { for (int k = 0; k < this.ySize; ++k) { for (int l = 0; l < this.xzSize; ++l) { int i1 = this.getAreaIndex(j, k, l); Vector3i vector3i = new Vector3i(j << BLOCK_TO_AREA_SH_XZ, k << BLOCK_TO_AREA_SH_Y, l << BLOCK_TO_AREA_SH_XZ); this.chunkAreasArr[i1] = new ChunkArea(i1, vector3i, minHeight); } } } this.prevX = Integer.MIN_VALUE; this.prevZ = Integer.MIN_VALUE; } public void repositionAreas(int secX, int secZ) { int xS = secX >> AREA_SH_XZ; int zS = secZ >> AREA_SH_XZ; int deltaX = Mth.clamp(xS - this.prevX, -this.xzSize, this.xzSize); int deltaZ = Mth.clamp(zS - this.prevZ, -this.xzSize, this.xzSize); int xAbsChunkIndex = xS - this.xzSize / 2; int xStart = Math.floorMod(xAbsChunkIndex, this.xzSize); // needs positive modulo int zAbsChunkIndex = zS - this.xzSize / 2; int zStart = Math.floorMod(zAbsChunkIndex, this.xzSize); CircularIntList xList = new CircularIntList(this.xzSize, xStart); CircularIntList zList = new CircularIntList(this.xzSize, zStart); CircularIntList.OwnIterator xIterator = xList.iterator(); CircularIntList.OwnIterator zIterator = zList.iterator(); int xRangeStart; int xRangeEnd; int xComplStart; int xComplEnd; if (deltaX >= 0) { xRangeStart = this.xzSize - deltaX; xRangeEnd = this.xzSize - 1; xComplStart = 0; xComplEnd = xRangeStart - 1; } else { xRangeStart = 0; xRangeEnd = -deltaX - 1; xComplStart = xRangeEnd; xComplEnd = this.xzSize - 1; } int zRangeStart; int zRangeEnd; if (deltaZ >= 0) { zRangeStart = this.xzSize - deltaZ; zRangeEnd = this.xzSize - 1; } else { zRangeStart = 0; zRangeEnd = -deltaZ - 1; } CircularIntList.RangeIterator xRangeIterator = xList.rangeIterator(xRangeStart, xRangeEnd); CircularIntList.RangeIterator xComplIterator = xList.rangeIterator(xComplStart, xComplEnd); CircularIntList.RangeIterator zRangeIterator = zList.rangeIterator(zRangeStart, zRangeEnd); xAbsChunkIndex = xS - this.xzSize / 2 + xRangeStart; for (int xRelativeIndex; xRangeIterator.hasNext(); xAbsChunkIndex++) { xRelativeIndex = xRangeIterator.next(); int x1 = (xAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); zIterator.restart(); zAbsChunkIndex = zS - (this.xzSize >> 1); for (int zRelativeIndex; zIterator.hasNext(); zAbsChunkIndex++) { zRelativeIndex = zIterator.next(); int z1 = (zAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); for (int yRel = 0; yRel < this.ySize; ++yRel) { int y1 = this.minHeight + (yRel << (AREA_SH_Y + SEC_SH)); ChunkArea chunkArea = this.chunkAreasArr[this.getAreaIndex(xRelativeIndex, yRel, zRelativeIndex)]; chunkArea.setPosition(x1, y1, z1); chunkArea.releaseBuffers(); } } } xAbsChunkIndex = xS - this.xzSize / 2 + xComplStart; for (int xRelativeIndex; xComplIterator.hasNext(); xAbsChunkIndex++) { xRelativeIndex = xComplIterator.next(); int x1 = (xAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); zRangeIterator.restart(); zAbsChunkIndex = zS - (this.xzSize >> 1) + zRangeStart; for (int zRelativeIndex; zRangeIterator.hasNext(); zAbsChunkIndex++) { zRelativeIndex = zRangeIterator.next(); int z1 = (zAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); for (int yRel = 0; yRel < this.ySize; ++yRel) { int y1 = this.minHeight + (yRel << (AREA_SH_Y + SEC_SH)); ChunkArea chunkArea = this.chunkAreasArr[this.getAreaIndex(xRelativeIndex, yRel, zRelativeIndex)]; chunkArea.setPosition(x1, y1, z1); chunkArea.releaseBuffers(); } } } this.prevX = xS; this.prevZ = zS; } public ChunkArea getChunkArea(RenderSection section, int x, int y, int z) { ChunkArea chunkArea; int shX = AREA_SH_XZ + 4; int shY = AREA_SH_Y + 4; int shZ = AREA_SH_XZ + 4; int AreaX = x >> shX; int AreaY = (y - this.minHeight) >> shY; int AreaZ = z >> shZ; int x1 = Math.floorMod(AreaX, this.xzSize); int z1 = Math.floorMod(AreaZ, this.xzSize); chunkArea = this.chunkAreasArr[this.getAreaIndex(x1, AreaY, z1)]; return chunkArea; } public void updateFrustumVisibility(VFrustum frustum) { for (ChunkArea chunkArea : this.chunkAreasArr) { chunkArea.updateFrustum(frustum); } } public void resetQueues() { for (ChunkArea chunkArea : this.chunkAreasArr) { chunkArea.resetQueue(); } } private int getAreaIndex(int x, int y, int z) { return (z * this.ySize + y) * this.xzSize + x; } public void releaseAllBuffers() { for (ChunkArea chunkArea : this.chunkAreasArr) { chunkArea.releaseBuffers(); } } public String[] getStats() { long vbSize = 0, ibSize = 0, frag = 0; long vbUsed = 0, ibUsed = 0; int count = 0; for (ChunkArea chunkArea : this.chunkAreasArr) { DrawBuffers drawBuffers = chunkArea.drawBuffers; if (drawBuffers.isAllocated()) { var vertexBuffers = drawBuffers.getVertexBuffers(); for (var buffer : vertexBuffers.values()) { vbSize += buffer.getSize(); vbUsed += buffer.getUsed(); frag += buffer.fragmentation(); } var indexBuffer = drawBuffers.getIndexBuffer(); if (indexBuffer != null) { ibSize += indexBuffer.getSize(); ibUsed += indexBuffer.getUsed(); frag += indexBuffer.fragmentation(); } count++; } } vbSize /= 1024 * 1024; vbUsed /= 1024 * 1024; ibSize /= 1024 * 1024; ibUsed /= 1024 * 1024; frag /= 1024 * 1024; return new String[]{ String.format("Vertex Buffers: %d/%d MB", vbUsed, vbSize), String.format("Index Buffers: %d/%d MB", ibUsed, ibSize), String.format("Allocations: %d Frag: %d MB", count, frag) }; } }
xCollateral/VulkanMod
src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java
2,785
//TODO make even size work
line_comment
nl
package net.vulkanmod.render.chunk; import net.minecraft.util.Mth; import net.vulkanmod.render.chunk.buffer.DrawBuffers; import net.vulkanmod.render.chunk.util.CircularIntList; import net.vulkanmod.render.chunk.util.Util; import org.joml.Vector3i; public class ChunkAreaManager { static final int WIDTH = 8; static final int HEIGHT = 8; static final int AREA_SH_XZ = Util.flooredLog(WIDTH); static final int AREA_SH_Y = Util.flooredLog(HEIGHT); static final int SEC_SH = 4; static final int BLOCK_TO_AREA_SH_XZ = AREA_SH_XZ + SEC_SH; static final int BLOCK_TO_AREA_SH_Y = AREA_SH_Y + SEC_SH; public final int size; final int sectionGridWidth; final int xzSize; final int ySize; final int minHeight; final ChunkArea[] chunkAreasArr; int prevX; int prevZ; public ChunkAreaManager(int width, int height, int minHeight) { this.minHeight = minHeight; this.sectionGridWidth = width; int t = (width >> AREA_SH_XZ) + 2; int relativeHeight = height - (minHeight >> 4); this.ySize = (relativeHeight & 0x5) == 0 ? (relativeHeight >> AREA_SH_Y) : (relativeHeight >> AREA_SH_Y) + 1; //check if width is even if ((t & 1) == 0) t++; this.xzSize = t; //TODO make<SUF> this.size = xzSize * ySize * xzSize; this.chunkAreasArr = new ChunkArea[size]; for (int j = 0; j < this.xzSize; ++j) { for (int k = 0; k < this.ySize; ++k) { for (int l = 0; l < this.xzSize; ++l) { int i1 = this.getAreaIndex(j, k, l); Vector3i vector3i = new Vector3i(j << BLOCK_TO_AREA_SH_XZ, k << BLOCK_TO_AREA_SH_Y, l << BLOCK_TO_AREA_SH_XZ); this.chunkAreasArr[i1] = new ChunkArea(i1, vector3i, minHeight); } } } this.prevX = Integer.MIN_VALUE; this.prevZ = Integer.MIN_VALUE; } public void repositionAreas(int secX, int secZ) { int xS = secX >> AREA_SH_XZ; int zS = secZ >> AREA_SH_XZ; int deltaX = Mth.clamp(xS - this.prevX, -this.xzSize, this.xzSize); int deltaZ = Mth.clamp(zS - this.prevZ, -this.xzSize, this.xzSize); int xAbsChunkIndex = xS - this.xzSize / 2; int xStart = Math.floorMod(xAbsChunkIndex, this.xzSize); // needs positive modulo int zAbsChunkIndex = zS - this.xzSize / 2; int zStart = Math.floorMod(zAbsChunkIndex, this.xzSize); CircularIntList xList = new CircularIntList(this.xzSize, xStart); CircularIntList zList = new CircularIntList(this.xzSize, zStart); CircularIntList.OwnIterator xIterator = xList.iterator(); CircularIntList.OwnIterator zIterator = zList.iterator(); int xRangeStart; int xRangeEnd; int xComplStart; int xComplEnd; if (deltaX >= 0) { xRangeStart = this.xzSize - deltaX; xRangeEnd = this.xzSize - 1; xComplStart = 0; xComplEnd = xRangeStart - 1; } else { xRangeStart = 0; xRangeEnd = -deltaX - 1; xComplStart = xRangeEnd; xComplEnd = this.xzSize - 1; } int zRangeStart; int zRangeEnd; if (deltaZ >= 0) { zRangeStart = this.xzSize - deltaZ; zRangeEnd = this.xzSize - 1; } else { zRangeStart = 0; zRangeEnd = -deltaZ - 1; } CircularIntList.RangeIterator xRangeIterator = xList.rangeIterator(xRangeStart, xRangeEnd); CircularIntList.RangeIterator xComplIterator = xList.rangeIterator(xComplStart, xComplEnd); CircularIntList.RangeIterator zRangeIterator = zList.rangeIterator(zRangeStart, zRangeEnd); xAbsChunkIndex = xS - this.xzSize / 2 + xRangeStart; for (int xRelativeIndex; xRangeIterator.hasNext(); xAbsChunkIndex++) { xRelativeIndex = xRangeIterator.next(); int x1 = (xAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); zIterator.restart(); zAbsChunkIndex = zS - (this.xzSize >> 1); for (int zRelativeIndex; zIterator.hasNext(); zAbsChunkIndex++) { zRelativeIndex = zIterator.next(); int z1 = (zAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); for (int yRel = 0; yRel < this.ySize; ++yRel) { int y1 = this.minHeight + (yRel << (AREA_SH_Y + SEC_SH)); ChunkArea chunkArea = this.chunkAreasArr[this.getAreaIndex(xRelativeIndex, yRel, zRelativeIndex)]; chunkArea.setPosition(x1, y1, z1); chunkArea.releaseBuffers(); } } } xAbsChunkIndex = xS - this.xzSize / 2 + xComplStart; for (int xRelativeIndex; xComplIterator.hasNext(); xAbsChunkIndex++) { xRelativeIndex = xComplIterator.next(); int x1 = (xAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); zRangeIterator.restart(); zAbsChunkIndex = zS - (this.xzSize >> 1) + zRangeStart; for (int zRelativeIndex; zRangeIterator.hasNext(); zAbsChunkIndex++) { zRelativeIndex = zRangeIterator.next(); int z1 = (zAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); for (int yRel = 0; yRel < this.ySize; ++yRel) { int y1 = this.minHeight + (yRel << (AREA_SH_Y + SEC_SH)); ChunkArea chunkArea = this.chunkAreasArr[this.getAreaIndex(xRelativeIndex, yRel, zRelativeIndex)]; chunkArea.setPosition(x1, y1, z1); chunkArea.releaseBuffers(); } } } this.prevX = xS; this.prevZ = zS; } public ChunkArea getChunkArea(RenderSection section, int x, int y, int z) { ChunkArea chunkArea; int shX = AREA_SH_XZ + 4; int shY = AREA_SH_Y + 4; int shZ = AREA_SH_XZ + 4; int AreaX = x >> shX; int AreaY = (y - this.minHeight) >> shY; int AreaZ = z >> shZ; int x1 = Math.floorMod(AreaX, this.xzSize); int z1 = Math.floorMod(AreaZ, this.xzSize); chunkArea = this.chunkAreasArr[this.getAreaIndex(x1, AreaY, z1)]; return chunkArea; } public void updateFrustumVisibility(VFrustum frustum) { for (ChunkArea chunkArea : this.chunkAreasArr) { chunkArea.updateFrustum(frustum); } } public void resetQueues() { for (ChunkArea chunkArea : this.chunkAreasArr) { chunkArea.resetQueue(); } } private int getAreaIndex(int x, int y, int z) { return (z * this.ySize + y) * this.xzSize + x; } public void releaseAllBuffers() { for (ChunkArea chunkArea : this.chunkAreasArr) { chunkArea.releaseBuffers(); } } public String[] getStats() { long vbSize = 0, ibSize = 0, frag = 0; long vbUsed = 0, ibUsed = 0; int count = 0; for (ChunkArea chunkArea : this.chunkAreasArr) { DrawBuffers drawBuffers = chunkArea.drawBuffers; if (drawBuffers.isAllocated()) { var vertexBuffers = drawBuffers.getVertexBuffers(); for (var buffer : vertexBuffers.values()) { vbSize += buffer.getSize(); vbUsed += buffer.getUsed(); frag += buffer.fragmentation(); } var indexBuffer = drawBuffers.getIndexBuffer(); if (indexBuffer != null) { ibSize += indexBuffer.getSize(); ibUsed += indexBuffer.getUsed(); frag += indexBuffer.fragmentation(); } count++; } } vbSize /= 1024 * 1024; vbUsed /= 1024 * 1024; ibSize /= 1024 * 1024; ibUsed /= 1024 * 1024; frag /= 1024 * 1024; return new String[]{ String.format("Vertex Buffers: %d/%d MB", vbUsed, vbSize), String.format("Index Buffers: %d/%d MB", ibUsed, ibSize), String.format("Allocations: %d Frag: %d MB", count, frag) }; } }
175965_2
package gui; import controller.Controller; import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import model.Bestilling; import model.Forestilling; import model.Kunde; import model.Plads; import storage.Storage; import java.time.LocalDate; import java.util.ArrayList; public class Gui extends Application { public void start(Stage stage) { stage.setTitle("Konferencer"); GridPane pane = new GridPane(); this.initContent(pane); Scene scene = new Scene(pane); stage.setScene(scene); stage.show(); } // ----------------------------------------------------------- private final ListView<Forestilling> lvwForestilling = new ListView<Forestilling>(); private final ListView<Kunde> lvwKunder = new ListView<Kunde>(); private final TextArea txaBestilling = new TextArea(); private final Label lblError = new Label(""); private final Label lblForestillinger = new Label("Forestillinger"); private final Label lblKunder = new Label("kunder"); private final Label lblDato = new Label("Dato:"); private final Label lblKundeNavn = new Label("Kunde Navn"); private final Label lblKundeMobil = new Label("Kunde Mobil"); private final Label lblBestiltePladser = new Label("Bestilte pladser"); private final TextField txfDato = new TextField(); private final TextField txfKundeNavn = new TextField(); private final TextField txfKundeMobil = new TextField(); private final Button btnBestiltePladser = new Button("Vis bestilte pladser"); private final Button btnOpretKunde = new Button("Opret kunde"); private final ToggleGroup toggleGroup = new ToggleGroup(); // ----------------------------------------------------------- private void initContent(GridPane pane) { // show or hide grid lines pane.setGridLinesVisible(false); // set padding of the pane pane.setPadding(new Insets(20)); // set horizontal gap between components pane.setHgap(10); // set vertical gap between components pane.setVgap(10); // Labels pane.add(lblForestillinger, 0, 0); // Listview pane.add(lvwForestilling, 0, 1, 3, 5); lvwForestilling.setPrefHeight(250); lvwForestilling.setPrefWidth(250); lvwForestilling.getItems().setAll(Storage.getForestillinger()); lvwForestilling.setOnMouseClicked(mouseEvent -> forestillingerClick(mouseEvent)); // Hoteller listview pane.add(lblKunder, 4, 0); pane.add(lvwKunder, 4, 1, 3, 5); lvwKunder.setPrefHeight(250); lvwKunder.setPrefWidth(250); pane.add(lblDato, 8,0); pane.add(txfDato, 8,1); pane.add(btnBestiltePladser, 8,2); btnBestiltePladser.setOnAction(event -> visBestiltePladser()); // Udflugter listview pane.add(lblBestiltePladser, 8, 3); pane.add(txaBestilling, 8, 4, 3, 5); txaBestilling.setPrefHeight(200); txaBestilling.setPrefWidth(250); txaBestilling.setEditable(false); pane.add(lblKundeNavn,4,6); pane.add(txfKundeNavn,4,7); pane.add(lblKundeMobil,4,8); pane.add(txfKundeMobil,4,9); pane.add(btnOpretKunde, 4,10); btnOpretKunde.setOnAction(event -> lavKunde()); lblError.setTextFill(Color.RED); pane.add(lblError, 0, 11, 3, 1); } private void lavKunde() { if (txfKundeNavn.getText().length() < 1) { lblError.setText("Error you need to input a navn"); return; } if (txfKundeMobil.getText().length() < 1) { lblError.setText("Error you need to input a mobile number"); return; } String navn = txfKundeNavn.getText(); String mobil = txfKundeMobil.getText(); Controller.createKunde(navn, mobil); lblError.setText("Worked :)"); } private void visBestiltePladser(){ LocalDate date = LocalDate.now(); try { date = LocalDate.parse(txfDato.getText()); } catch(Exception exception){ lblError.setText("ERROR wrong date input"); return; } if (lvwForestilling.getSelectionModel().isEmpty()){ lblError.setText("Please select a forestilling"); return; } Forestilling forestilling = lvwForestilling.getSelectionModel().getSelectedItem(); if (lvwKunder.getSelectionModel().isEmpty()){ lblError.setText("Please select a customer"); return; } Kunde kunde = lvwKunder.getSelectionModel().getSelectedItem(); txaBestilling.clear(); ArrayList<Plads> bestilte = kunde.bestiltePladserTilForestillingPådag(forestilling,date); if (bestilte.size() == 0) { lblError.setText("No plads ordered for this customer on this forestilling"); return; } for(Plads plads : bestilte) { txaBestilling.appendText(plads.toString() + System.lineSeparator()); } } private void forestillingerClick(MouseEvent event) { System.out.println("Called"); ListView<Forestilling> forestillinger = (ListView) event.getSource(); if (forestillinger.getSelectionModel().isEmpty()){ System.out.println("weird"); return; } Forestilling forestilling = forestillinger.getSelectionModel().getSelectedItem(); System.out.println("Faget clicked " + forestilling); if (forestilling != null) { lvwKunder.getItems().clear(); lvwKunder.getItems().addAll(forestilling.hentKunder()); } } }
xGuysOG/Programmering1
SemesterproeveJanuar2019/src/gui/Gui.java
1,904
// set horizontal gap between components
line_comment
nl
package gui; import controller.Controller; import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import model.Bestilling; import model.Forestilling; import model.Kunde; import model.Plads; import storage.Storage; import java.time.LocalDate; import java.util.ArrayList; public class Gui extends Application { public void start(Stage stage) { stage.setTitle("Konferencer"); GridPane pane = new GridPane(); this.initContent(pane); Scene scene = new Scene(pane); stage.setScene(scene); stage.show(); } // ----------------------------------------------------------- private final ListView<Forestilling> lvwForestilling = new ListView<Forestilling>(); private final ListView<Kunde> lvwKunder = new ListView<Kunde>(); private final TextArea txaBestilling = new TextArea(); private final Label lblError = new Label(""); private final Label lblForestillinger = new Label("Forestillinger"); private final Label lblKunder = new Label("kunder"); private final Label lblDato = new Label("Dato:"); private final Label lblKundeNavn = new Label("Kunde Navn"); private final Label lblKundeMobil = new Label("Kunde Mobil"); private final Label lblBestiltePladser = new Label("Bestilte pladser"); private final TextField txfDato = new TextField(); private final TextField txfKundeNavn = new TextField(); private final TextField txfKundeMobil = new TextField(); private final Button btnBestiltePladser = new Button("Vis bestilte pladser"); private final Button btnOpretKunde = new Button("Opret kunde"); private final ToggleGroup toggleGroup = new ToggleGroup(); // ----------------------------------------------------------- private void initContent(GridPane pane) { // show or hide grid lines pane.setGridLinesVisible(false); // set padding of the pane pane.setPadding(new Insets(20)); // set horizontal<SUF> pane.setHgap(10); // set vertical gap between components pane.setVgap(10); // Labels pane.add(lblForestillinger, 0, 0); // Listview pane.add(lvwForestilling, 0, 1, 3, 5); lvwForestilling.setPrefHeight(250); lvwForestilling.setPrefWidth(250); lvwForestilling.getItems().setAll(Storage.getForestillinger()); lvwForestilling.setOnMouseClicked(mouseEvent -> forestillingerClick(mouseEvent)); // Hoteller listview pane.add(lblKunder, 4, 0); pane.add(lvwKunder, 4, 1, 3, 5); lvwKunder.setPrefHeight(250); lvwKunder.setPrefWidth(250); pane.add(lblDato, 8,0); pane.add(txfDato, 8,1); pane.add(btnBestiltePladser, 8,2); btnBestiltePladser.setOnAction(event -> visBestiltePladser()); // Udflugter listview pane.add(lblBestiltePladser, 8, 3); pane.add(txaBestilling, 8, 4, 3, 5); txaBestilling.setPrefHeight(200); txaBestilling.setPrefWidth(250); txaBestilling.setEditable(false); pane.add(lblKundeNavn,4,6); pane.add(txfKundeNavn,4,7); pane.add(lblKundeMobil,4,8); pane.add(txfKundeMobil,4,9); pane.add(btnOpretKunde, 4,10); btnOpretKunde.setOnAction(event -> lavKunde()); lblError.setTextFill(Color.RED); pane.add(lblError, 0, 11, 3, 1); } private void lavKunde() { if (txfKundeNavn.getText().length() < 1) { lblError.setText("Error you need to input a navn"); return; } if (txfKundeMobil.getText().length() < 1) { lblError.setText("Error you need to input a mobile number"); return; } String navn = txfKundeNavn.getText(); String mobil = txfKundeMobil.getText(); Controller.createKunde(navn, mobil); lblError.setText("Worked :)"); } private void visBestiltePladser(){ LocalDate date = LocalDate.now(); try { date = LocalDate.parse(txfDato.getText()); } catch(Exception exception){ lblError.setText("ERROR wrong date input"); return; } if (lvwForestilling.getSelectionModel().isEmpty()){ lblError.setText("Please select a forestilling"); return; } Forestilling forestilling = lvwForestilling.getSelectionModel().getSelectedItem(); if (lvwKunder.getSelectionModel().isEmpty()){ lblError.setText("Please select a customer"); return; } Kunde kunde = lvwKunder.getSelectionModel().getSelectedItem(); txaBestilling.clear(); ArrayList<Plads> bestilte = kunde.bestiltePladserTilForestillingPådag(forestilling,date); if (bestilte.size() == 0) { lblError.setText("No plads ordered for this customer on this forestilling"); return; } for(Plads plads : bestilte) { txaBestilling.appendText(plads.toString() + System.lineSeparator()); } } private void forestillingerClick(MouseEvent event) { System.out.println("Called"); ListView<Forestilling> forestillinger = (ListView) event.getSource(); if (forestillinger.getSelectionModel().isEmpty()){ System.out.println("weird"); return; } Forestilling forestilling = forestillinger.getSelectionModel().getSelectedItem(); System.out.println("Faget clicked " + forestilling); if (forestilling != null) { lvwKunder.getItems().clear(); lvwKunder.getItems().addAll(forestilling.hentKunder()); } } }
107864_7
package mai.scenes.game.normalgame; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.effect.Bloom; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.shape.Circle; import mai.audio.ButtonAudio; import mai.audio.Sound; import mai.data.User; import mai.datastructs.Stapel; import mai.enums.ButtonType; import mai.enums.GameOverType; import mai.exceptions.UnderflowException; import mai.scenes.game.Parts.UserInfoBox; import mai.scenes.game.logic.*; import mai.scenes.gamemenu.GameMenuController; import mai.scenes.gameover.GameOverData; import mai.scenes.abstractscene.AbstractController; import mai.audio.SoundPlayer; import java.net.URL; import java.util.Random; import java.util.ResourceBundle; public class GameController extends AbstractController implements Initializable { // ----- Game Data ----- private final int spaceMinSize, spaceMaxSize; private final Stapel<GameData> gameGeschiedenis; public HBox[] bordRows; //move gameData to stack? public GameData gameData; public GameData oldGameData; // ----- Board Interface ----- @FXML private HBox GameBoardContainer; @FXML private VBox bordColumnBox; @FXML private Label turnInfo; @FXML private Label currentPlayerLabel; @FXML private Button gameOverButton; @FXML private Button resetTurnButton; private Button controllerResetTurnButton; @FXML private HBox resetButtonBox; // ----- UserDetails ----- UserInfoBox horizontalPlayerOneInfo; UserInfoBox horizontalPlayerTwoInfo; @FXML private VBox HorizontalPlayerOneInfoContainer; @FXML private VBox HorizontalPlayerTwoInfoContainer; private final GameMenuController gameMenuController; public GameController(GameData gameData, int spaceMinSize, int spaceMaxSize, GameMenuController gameMenuController) { this.gameData = gameData; this.spaceMaxSize = spaceMaxSize; this.gameMenuController = gameMenuController; this.gameGeschiedenis = new Stapel<>(); this.spaceMinSize = spaceMinSize; } @Override public void initialize(URL url, ResourceBundle resourceBundle) { controllerResetTurnButton = resetTurnButton; SoundPlayer.playAudioFile(Sound.SUMMON.getAudio()); configButtons(); horizontalPlayerOneInfo = new UserInfoBox(gameData.getPlayer1(), gameData.getPlayerOneScore(), "Hoodie",60); horizontalPlayerTwoInfo = new UserInfoBox(gameData.getPlayer2(), gameData.getPlayerTwoScore(), "Baggy Sweater",60); HorizontalPlayerOneInfoContainer.getChildren().add(horizontalPlayerOneInfo); HorizontalPlayerTwoInfoContainer.getChildren().add(horizontalPlayerTwoInfo); configBoard(); setInitialTurn(); setOldGameData(); } private void configButtons() { gameOverButton.setOnMouseEntered(select()); resetTurnButton.setOnMouseEntered(select()); } // ----- methods when player ends his move ----- protected void endTurn() { gameData.increaseTurnNumber(); gameData.player1Finished = false; gameData.player2Finished = false; setTurnInfo(); setOldGameData(); } private void setOldGameData() { Space[][] bord = gameData.gameBoard.copyBord(); GameBoard oldGameBoard = new GameBoard(gameData.gameBoard.xGroote, gameData.gameBoard.yGroote, bord); oldGameData = new GameData(gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber(), gameData.getPlayer1(), gameData.getPlayer2(), oldGameBoard); } public void endPlayerMove() { int oldP, newP; if (gameData.currentPlayer.getPlayerNumber() == 1) { gameData.player1Finished = true; gameData.currentPlayer = gameData.getPlayer2(); newP = 2; oldP = 1; } else { oldP = 2; newP = 1; gameData.player2Finished = true; gameData.currentPlayer = gameData.getPlayer1(); } if (checkGameConditions(newP)) { endGame(oldP, newP); } else { if (gameData.player1Finished && gameData.player2Finished) endTurn(); setNewPlayerMove(); } } protected void setNewPlayerMove() { setTurnGlow(gameData.currentPlayer.getPlayerNumber()); setCurrentPlayer(); setSelectAble(gameData.gameBoard.getPlayerMoves(gameData.currentPlayer.getPlayerNumber())); } protected boolean checkGameConditions(int newP) { return gameData.gameBoard.checkBoard(newP); } protected void addGameHistory(GameData data) { data.currentPlayer = gameData.currentPlayer; gameGeschiedenis.push(data); } // ----- make the tiles for the current player selectable ----- private void setSelectAble(Stapel<Space> selectAbles) { while (!selectAbles.isEmpty()){ try { makeSelectAble(selectAbles.pop()); } catch (UnderflowException e) { e.printStackTrace(); } } } private void makeSelectAble(Space space) { bordRows[space.y].getChildren().get(space.x).getStyleClass().add(ButtonType.SELECT.getType()); bordRows[space.y].getChildren().get(space.x).setOnMouseClicked(showPossible()); } protected void removeSelectAble(Stapel<Space> removeAbles) { while (!removeAbles.isEmpty()){ try { deselectBlock(removeAbles.pop()); } catch (UnderflowException e) { e.printStackTrace(); } } } private void deselectBlock(Space space) { bordRows[space.y].getChildren().get(space.x).getStyleClass().clear(); bordRows[space.y].getChildren().get(space.x).setOnMouseClicked(null); bordRows[space.y].getChildren().get(space.x).setOnMouseEntered(null); } // ----- setting selectable tiles ----- private Space selected; private EventHandler<? super MouseEvent> showPossible() { return (EventHandler<MouseEvent>) event -> { SpaceBox space = (SpaceBox) event.getSource(); if (selected != null && (selected.y == space.y && selected.x == space.x)) { cancelAttack(space); } else { showPossibleAttacks(space); } }; } private void cancelAttack(SpaceBox space){ SoundPlayer.playAudioFile(ButtonAudio.CANCEL.getAudio()); space.getStyleClass().clear(); deselectActiveSelection(gameData.gameBoard.getBord()[space.x][space.y]); selected = null; } private void showPossibleAttacks(SpaceBox space) { if (selected != null) deselectActiveSelection(selected); SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); space.getStyleClass().add(ButtonType.SELECT.getType()); selected = gameData.gameBoard.getBord()[space.x][space.y]; AttackVectors attackVectors = gameData.gameBoard.getPossibleAttackSquare(new Space(space.x, space.y), gameData.currentPlayer.getRange(), gameData.currentPlayer.getAttackDropOff()); showShortRangeAttack(attackVectors.possibleOneRangeAttackVectors(), space); showLongRangeAttack(attackVectors.possibleTwoRangeAttackVectors(), space); } private void showShortRangeAttack(Stapel<Space> attackVectors, SpaceBox origin) { while (!attackVectors.isEmpty()) { try { showPossibleBlock(attackVectors.pop(), ButtonType.SHORTRANGE.getType(), moveEvent(gameData.gameBoard.getBord()[origin.x][origin.y])); } catch (UnderflowException e) { e.printStackTrace(); } } } private void showLongRangeAttack(Stapel<Space> attackVectors, SpaceBox origin) { while (!attackVectors.isEmpty()) { try { showPossibleBlock(attackVectors.pop(), ButtonType.LONGRANGE.getType(), moveEvent(gameData.gameBoard.getBord()[origin.x][origin.y])); } catch (UnderflowException e) { e.printStackTrace(); } } } private void showPossibleBlock(Space space, String classStyle, EventHandler<? super MouseEvent> mouseEvent) { bordRows[space.y].getChildren().get(space.x).setOnMouseClicked(mouseEvent); bordRows[space.y].getChildren().get(space.x).setOnMouseEntered(move()); bordRows[space.y].getChildren().get(space.x).getStyleClass().clear(); bordRows[space.y].getChildren().get(space.x).getStyleClass().add(classStyle); } private void deselectActiveSelection(Space selectedSpace) { bordRows[selectedSpace.y].getChildren().get(selectedSpace.x).getStyleClass().clear(); bordRows[selectedSpace.y].getChildren().get(selectedSpace.x).getStyleClass().add(ButtonType.SELECT.getType()); Stapel<Space> deselectAbles = gameData.gameBoard.getDeselect(selectedSpace, 3); removeSelectAble(deselectAbles); } // ----- movement methods ----- public EventHandler<? super MouseEvent> moveEvent(Space origin) { return (EventHandler<MouseEvent>) event -> { SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); selected = null; SpaceBox selected = (SpaceBox) event.getSource(); bordRows[selected.y].getChildren().get(selected.x).setOnMouseEntered(null); move(origin, gameData.gameBoard.getBord()[selected.x][selected.y], gameData.currentPlayer, gameData.currentPlayer.getAttackDropOff(), gameData.currentPlayer.getRange()); }; } public void move(Space origin, Space selected, User currentUser, int attackDropOff, int range) { Stapel<Space> previousSelectables = gameData.gameBoard.getPlayerMoves(gameData.currentPlayer.getPlayerNumber()); int xDif = gameData.gameBoard.getDis(origin.x, selected.x); int yDif = gameData.gameBoard.getDis(origin.y, selected.y); deselectActiveSelection(gameData.gameBoard.getBord()[origin.x][origin.y]); if (xDif < attackDropOff && yDif < attackDropOff) { addPoint(1); shortRangeAttack(selected, currentUser); } else if (xDif < range && yDif < range) { longRangeAttack(origin, selected, currentUser); } removeSelectAble(previousSelectables); endPlayerMove(); } public void shortRangeAttack(Space select, User currentUser) { SpaceBox newSpace = (SpaceBox) bordRows[select.y].getChildren().get(select.x); newSpace.getStyleClass().clear(); setInfected(select, currentUser.getPlayerNumber()); gameData.gameBoard.getBord()[select.x][select.y].take(currentUser.getPlayerNumber()); setColour(newSpace, currentUser.getPlayerColour()); setSpaceLabel(currentUser.getPlayerNumber(), newSpace); } public void longRangeAttack(Space origin, Space select, User currentUser) { SpaceBox oldSpace = (SpaceBox) bordRows[origin.y].getChildren().get(origin.x); SpaceBox newSpace = (SpaceBox) bordRows[select.y].getChildren().get(select.x); removeColour((SpaceBox) bordRows[origin.y].getChildren().get(origin.x)); gameData.gameBoard.getBord()[origin.x][origin.y].deselect(); setInfected(select, currentUser.getPlayerNumber()); gameData.gameBoard.getBord()[select.x][select.y].take(currentUser.getPlayerNumber()); gameData.gameBoard.getBord()[oldSpace.x][oldSpace.y].deselect(); setColour(newSpace, currentUser.getPlayerColour()); setSpaceLabel(currentUser.getPlayerNumber(), newSpace); removeSpaceLabel(oldSpace); } private void setInfected(Space select, int playerNumber) { Stapel<Space> a = gameData.gameBoard.getInfected(select, playerNumber); while (!a.isEmpty()) { try { Space t = a.pop(); gameData.gameBoard.setInfected(t, playerNumber); addPoint(1); removePoint(1); setColour((SpaceBox) bordRows[t.y].getChildren().get(t.x), gameData.currentPlayer.getPlayerColour()); setSpaceLabel(gameData.currentPlayer.getPlayerNumber(), (SpaceBox) bordRows[t.y].getChildren().get(t.x)); } catch (UnderflowException e) { e.printStackTrace(); } } } private void addPoint(int points) { if (gameData.currentPlayer.getPlayerNumber() == 1) { gameData.increasePlayerOneScore(points); } else { gameData.increasePlayerTwoScore(points); } updatePointLabel(); } private void removePoint(int points) { if (gameData.currentPlayer.getPlayerNumber() == 1) { gameData.decreasePlayerTwoScore(points); } else { gameData.decreasePlayerOneScore(points); } updatePointLabel(); } private void updatePointLabel() { horizontalPlayerOneInfo.getScoreLabel().setText(String.valueOf(gameData.getPlayerOneScore())); horizontalPlayerTwoInfo.getScoreLabel().setText(String.valueOf(gameData.getPlayerTwoScore())); } // ----- configuring initial board ----- private void configBoard() { gameData.gameBoard.setInitialOccupied(2); drawBoard(gameData); } private void drawBoard(GameData data) { bordRows = new HBox[data.gameBoard.yGroote]; for (int y = 0; y < data.gameBoard.yGroote; y++) { HBox row = new HBox(); for (int x = 0; x < data.gameBoard.xGroote; x++) { SpaceBox spaceBox = new SpaceBox(x, y, spaceMinSize, spaceMaxSize); setBoxBorder(x, y, spaceBox); if (data.gameBoard.getBord()[x][y].isTaken()) { if (data.gameBoard.getBord()[x][y].getPlayerNumber() == 1) { setColour(spaceBox, data.getPlayer1().getPlayerColour()); setSpaceLabel(1, spaceBox); } else { setColour(spaceBox, data.getPlayer2().getPlayerColour()); setSpaceLabel(2, spaceBox); } } row.getChildren().add(spaceBox); } bordRows[y] = row; } if (!bordColumnBox.getChildren().isEmpty()) bordColumnBox.getChildren().clear(); bordColumnBox.getChildren().addAll(bordRows); } private void setBoxBorder(int x, int y, Node space) { if (gameData.gameBoard.xGroote - 1 != x && y != 0) { space.setStyle( "-fx-border-width: 2 2 0 0;\n" + "-fx-border-color: #242526;"); } else if (gameData.gameBoard.xGroote - 1 != x) { space.setStyle( "-fx-border-width: 0 2 0 0;\n" + "-fx-border-color: #242526;"); } else if (gameData.gameBoard.xGroote - 1 == x && y != 0) { space.setStyle( "-fx-border-width: 2 0 0 0;\n" + "-fx-border-color: #242526;"); } else { space.setStyle( "-fx-border-width: 0 0 0 0;\n" + "-fx-border-color: #242526;"); } } private void setSpaceLabel(int playerNumber, SpaceBox spaceBox) { if (playerNumber == 1) { spaceBox.setText("H"); } else { spaceBox.setText("B"); } } private void removeSpaceLabel(SpaceBox spaceBox) { spaceBox.setText(""); } private void setColour(SpaceBox spaceBox, String color) { String style = spaceBox.getStyle(); String newStyle = ""; if (!style.isEmpty()) { String[] t = style.split("((?=;))"); newStyle = t[0] + t[1] + ";"; } spaceBox.setStyle(newStyle + "\n-fx-background-color: #" + "B0" + color.substring(3) + ";"); } private void removeColour(SpaceBox spaceBox) { String style = spaceBox.getStyle(); String newStyle = ""; if (!style.isEmpty()) { String[] t = style.split("((?=;))"); newStyle = t[0] + t[1] + ";"; } spaceBox.setStyle(newStyle); } // ----- configuring initial turn ----- public void setInitialTurn() { Random random = new Random(); if (random.nextInt(2) == 0) { gameData.currentPlayer = gameData.getPlayer1(); setResetButtonActive(true); setNewPlayerMove(); } else { gameData.currentPlayer = gameData.getPlayer2(); setResetButtonActive(false); setNewPlayerMove(); } setTurnInfo(); } protected void setTurnInfo() { turnInfo.setText("Turn " + gameData.getTurnNumber() + " | "); } protected void setCurrentPlayer() { currentPlayerLabel.setText(gameData.currentPlayer.getPlayerName()); if (gameData.currentPlayer.getPlayerNumber() == 1) { setTurnGlow(1); setResetButtonActive(true); } else { setTurnGlow(2); setResetButtonActive(false); } } // ----- set or removes a glow when it's one player's turn or not ----- protected void setTurnGlow(int playerNumber) { if (playerNumber == 1) { addTurnGlow(horizontalPlayerOneInfo.getPlayerLabel(), horizontalPlayerOneInfo.getAvatarBox().getAvatarCircle()); removeTurnGlow(horizontalPlayerTwoInfo.getPlayerLabel(), horizontalPlayerTwoInfo.getAvatarBox().getAvatarCircle()); } else { addTurnGlow(horizontalPlayerTwoInfo.getPlayerLabel(), horizontalPlayerTwoInfo.getAvatarBox().getAvatarCircle()); removeTurnGlow(horizontalPlayerOneInfo.getPlayerLabel(), horizontalPlayerOneInfo.getAvatarBox().getAvatarCircle()); } } private void addTurnGlow(Label playerLabel, Circle avatarCircle) { Bloom bloom = new Bloom(); bloom.setThreshold(0.01); playerLabel.setEffect(bloom); avatarCircle.setEffect(bloom); } private void removeTurnGlow(Label playerLabel, Circle avatarCircle) { playerLabel.setEffect(null); avatarCircle.setEffect(null); } // ----- event that runs when the game turn goes back ----- // pops the new turn data and peeks for the previous turn data @FXML private void resetTurn() throws UnderflowException { if (!gameGeschiedenis.isEmpty()) { SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); resetButtonBox.getChildren().clear(); removeSelectAble(gameData.gameBoard.getPlayerMoves(gameData.currentPlayer.getPlayerNumber())); resetTwistedGame(gameGeschiedenis.pop()); } } private void resetTwistedGame(GameData data) { gameData = data; drawBoard(data); setOldGameData(); setTurnInfo(); updatePointLabel(); gameData.currentPlayer = gameData.getPlayer1(); setNewPlayerMove(); } protected void setResetButtonActive(boolean active) { if (!gameGeschiedenis.isEmpty()) { if(active && resetButtonBox.getChildren().isEmpty()){ resetButtonBox.getChildren().add(controllerResetTurnButton); } else { resetButtonBox.getChildren().clear(); } } else { resetButtonBox.getChildren().clear(); } } // ----- event that runs when the game has ended ----- @FXML private void endGameEvent() { SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); if(gameData.currentPlayer.getPlayerNumber() == 1){ endGame(1,2); } else { endGame(2,1); } } protected void endGame(int oldP, int newP) { if (gameData.getPlayerOneScore() > gameData.getPlayerTwoScore()) { user1Win(); } else if (gameData.getPlayerTwoScore() > gameData.getPlayerOneScore()) { user2Win(); } else { if (gameData.gameBoard.checkBoard(newP)) { if(oldP == 1){ user1Win(); } else if(oldP == 2) { user2Win(); } } else { draw(); } } } private void user1Win(){ GameOverData gameOverData = new GameOverData(GameOverType.P1, gameData.getPlayer1(), gameData.getPlayer2(), gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber()); this.gameMenuController.setGameOverScreen(gameOverData); } private void user2Win(){ GameOverData gameOverData = new GameOverData(GameOverType.P2, gameData.getPlayer1(), gameData.getPlayer2(), gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber()); this.gameMenuController.setGameOverScreen(gameOverData); } private void draw(){ GameOverData gameOverData = new GameOverData(GameOverType.DRAW, gameData.getPlayer1(), gameData.getPlayer2(), gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber()); this.gameMenuController.setGameOverScreen(gameOverData); } // ----- for adding sounds? ----- private EventHandler<? super MouseEvent> select() { return (EventHandler<MouseEvent>) event -> SoundPlayer.playAudioFile(ButtonAudio.SELECT.getAudio()); } private EventHandler<? super MouseEvent> move() { return (EventHandler<MouseEvent>) event -> SoundPlayer.playAudioFile(ButtonAudio.MOVE.getAudio()); } }
xamediego/DEDS_W4-The-Great-Outdoors-Wins
src/main/java/mai/scenes/game/normalgame/GameController.java
6,397
// ----- movement methods -----
line_comment
nl
package mai.scenes.game.normalgame; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.effect.Bloom; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.shape.Circle; import mai.audio.ButtonAudio; import mai.audio.Sound; import mai.data.User; import mai.datastructs.Stapel; import mai.enums.ButtonType; import mai.enums.GameOverType; import mai.exceptions.UnderflowException; import mai.scenes.game.Parts.UserInfoBox; import mai.scenes.game.logic.*; import mai.scenes.gamemenu.GameMenuController; import mai.scenes.gameover.GameOverData; import mai.scenes.abstractscene.AbstractController; import mai.audio.SoundPlayer; import java.net.URL; import java.util.Random; import java.util.ResourceBundle; public class GameController extends AbstractController implements Initializable { // ----- Game Data ----- private final int spaceMinSize, spaceMaxSize; private final Stapel<GameData> gameGeschiedenis; public HBox[] bordRows; //move gameData to stack? public GameData gameData; public GameData oldGameData; // ----- Board Interface ----- @FXML private HBox GameBoardContainer; @FXML private VBox bordColumnBox; @FXML private Label turnInfo; @FXML private Label currentPlayerLabel; @FXML private Button gameOverButton; @FXML private Button resetTurnButton; private Button controllerResetTurnButton; @FXML private HBox resetButtonBox; // ----- UserDetails ----- UserInfoBox horizontalPlayerOneInfo; UserInfoBox horizontalPlayerTwoInfo; @FXML private VBox HorizontalPlayerOneInfoContainer; @FXML private VBox HorizontalPlayerTwoInfoContainer; private final GameMenuController gameMenuController; public GameController(GameData gameData, int spaceMinSize, int spaceMaxSize, GameMenuController gameMenuController) { this.gameData = gameData; this.spaceMaxSize = spaceMaxSize; this.gameMenuController = gameMenuController; this.gameGeschiedenis = new Stapel<>(); this.spaceMinSize = spaceMinSize; } @Override public void initialize(URL url, ResourceBundle resourceBundle) { controllerResetTurnButton = resetTurnButton; SoundPlayer.playAudioFile(Sound.SUMMON.getAudio()); configButtons(); horizontalPlayerOneInfo = new UserInfoBox(gameData.getPlayer1(), gameData.getPlayerOneScore(), "Hoodie",60); horizontalPlayerTwoInfo = new UserInfoBox(gameData.getPlayer2(), gameData.getPlayerTwoScore(), "Baggy Sweater",60); HorizontalPlayerOneInfoContainer.getChildren().add(horizontalPlayerOneInfo); HorizontalPlayerTwoInfoContainer.getChildren().add(horizontalPlayerTwoInfo); configBoard(); setInitialTurn(); setOldGameData(); } private void configButtons() { gameOverButton.setOnMouseEntered(select()); resetTurnButton.setOnMouseEntered(select()); } // ----- methods when player ends his move ----- protected void endTurn() { gameData.increaseTurnNumber(); gameData.player1Finished = false; gameData.player2Finished = false; setTurnInfo(); setOldGameData(); } private void setOldGameData() { Space[][] bord = gameData.gameBoard.copyBord(); GameBoard oldGameBoard = new GameBoard(gameData.gameBoard.xGroote, gameData.gameBoard.yGroote, bord); oldGameData = new GameData(gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber(), gameData.getPlayer1(), gameData.getPlayer2(), oldGameBoard); } public void endPlayerMove() { int oldP, newP; if (gameData.currentPlayer.getPlayerNumber() == 1) { gameData.player1Finished = true; gameData.currentPlayer = gameData.getPlayer2(); newP = 2; oldP = 1; } else { oldP = 2; newP = 1; gameData.player2Finished = true; gameData.currentPlayer = gameData.getPlayer1(); } if (checkGameConditions(newP)) { endGame(oldP, newP); } else { if (gameData.player1Finished && gameData.player2Finished) endTurn(); setNewPlayerMove(); } } protected void setNewPlayerMove() { setTurnGlow(gameData.currentPlayer.getPlayerNumber()); setCurrentPlayer(); setSelectAble(gameData.gameBoard.getPlayerMoves(gameData.currentPlayer.getPlayerNumber())); } protected boolean checkGameConditions(int newP) { return gameData.gameBoard.checkBoard(newP); } protected void addGameHistory(GameData data) { data.currentPlayer = gameData.currentPlayer; gameGeschiedenis.push(data); } // ----- make the tiles for the current player selectable ----- private void setSelectAble(Stapel<Space> selectAbles) { while (!selectAbles.isEmpty()){ try { makeSelectAble(selectAbles.pop()); } catch (UnderflowException e) { e.printStackTrace(); } } } private void makeSelectAble(Space space) { bordRows[space.y].getChildren().get(space.x).getStyleClass().add(ButtonType.SELECT.getType()); bordRows[space.y].getChildren().get(space.x).setOnMouseClicked(showPossible()); } protected void removeSelectAble(Stapel<Space> removeAbles) { while (!removeAbles.isEmpty()){ try { deselectBlock(removeAbles.pop()); } catch (UnderflowException e) { e.printStackTrace(); } } } private void deselectBlock(Space space) { bordRows[space.y].getChildren().get(space.x).getStyleClass().clear(); bordRows[space.y].getChildren().get(space.x).setOnMouseClicked(null); bordRows[space.y].getChildren().get(space.x).setOnMouseEntered(null); } // ----- setting selectable tiles ----- private Space selected; private EventHandler<? super MouseEvent> showPossible() { return (EventHandler<MouseEvent>) event -> { SpaceBox space = (SpaceBox) event.getSource(); if (selected != null && (selected.y == space.y && selected.x == space.x)) { cancelAttack(space); } else { showPossibleAttacks(space); } }; } private void cancelAttack(SpaceBox space){ SoundPlayer.playAudioFile(ButtonAudio.CANCEL.getAudio()); space.getStyleClass().clear(); deselectActiveSelection(gameData.gameBoard.getBord()[space.x][space.y]); selected = null; } private void showPossibleAttacks(SpaceBox space) { if (selected != null) deselectActiveSelection(selected); SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); space.getStyleClass().add(ButtonType.SELECT.getType()); selected = gameData.gameBoard.getBord()[space.x][space.y]; AttackVectors attackVectors = gameData.gameBoard.getPossibleAttackSquare(new Space(space.x, space.y), gameData.currentPlayer.getRange(), gameData.currentPlayer.getAttackDropOff()); showShortRangeAttack(attackVectors.possibleOneRangeAttackVectors(), space); showLongRangeAttack(attackVectors.possibleTwoRangeAttackVectors(), space); } private void showShortRangeAttack(Stapel<Space> attackVectors, SpaceBox origin) { while (!attackVectors.isEmpty()) { try { showPossibleBlock(attackVectors.pop(), ButtonType.SHORTRANGE.getType(), moveEvent(gameData.gameBoard.getBord()[origin.x][origin.y])); } catch (UnderflowException e) { e.printStackTrace(); } } } private void showLongRangeAttack(Stapel<Space> attackVectors, SpaceBox origin) { while (!attackVectors.isEmpty()) { try { showPossibleBlock(attackVectors.pop(), ButtonType.LONGRANGE.getType(), moveEvent(gameData.gameBoard.getBord()[origin.x][origin.y])); } catch (UnderflowException e) { e.printStackTrace(); } } } private void showPossibleBlock(Space space, String classStyle, EventHandler<? super MouseEvent> mouseEvent) { bordRows[space.y].getChildren().get(space.x).setOnMouseClicked(mouseEvent); bordRows[space.y].getChildren().get(space.x).setOnMouseEntered(move()); bordRows[space.y].getChildren().get(space.x).getStyleClass().clear(); bordRows[space.y].getChildren().get(space.x).getStyleClass().add(classStyle); } private void deselectActiveSelection(Space selectedSpace) { bordRows[selectedSpace.y].getChildren().get(selectedSpace.x).getStyleClass().clear(); bordRows[selectedSpace.y].getChildren().get(selectedSpace.x).getStyleClass().add(ButtonType.SELECT.getType()); Stapel<Space> deselectAbles = gameData.gameBoard.getDeselect(selectedSpace, 3); removeSelectAble(deselectAbles); } // ----- movement<SUF> public EventHandler<? super MouseEvent> moveEvent(Space origin) { return (EventHandler<MouseEvent>) event -> { SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); selected = null; SpaceBox selected = (SpaceBox) event.getSource(); bordRows[selected.y].getChildren().get(selected.x).setOnMouseEntered(null); move(origin, gameData.gameBoard.getBord()[selected.x][selected.y], gameData.currentPlayer, gameData.currentPlayer.getAttackDropOff(), gameData.currentPlayer.getRange()); }; } public void move(Space origin, Space selected, User currentUser, int attackDropOff, int range) { Stapel<Space> previousSelectables = gameData.gameBoard.getPlayerMoves(gameData.currentPlayer.getPlayerNumber()); int xDif = gameData.gameBoard.getDis(origin.x, selected.x); int yDif = gameData.gameBoard.getDis(origin.y, selected.y); deselectActiveSelection(gameData.gameBoard.getBord()[origin.x][origin.y]); if (xDif < attackDropOff && yDif < attackDropOff) { addPoint(1); shortRangeAttack(selected, currentUser); } else if (xDif < range && yDif < range) { longRangeAttack(origin, selected, currentUser); } removeSelectAble(previousSelectables); endPlayerMove(); } public void shortRangeAttack(Space select, User currentUser) { SpaceBox newSpace = (SpaceBox) bordRows[select.y].getChildren().get(select.x); newSpace.getStyleClass().clear(); setInfected(select, currentUser.getPlayerNumber()); gameData.gameBoard.getBord()[select.x][select.y].take(currentUser.getPlayerNumber()); setColour(newSpace, currentUser.getPlayerColour()); setSpaceLabel(currentUser.getPlayerNumber(), newSpace); } public void longRangeAttack(Space origin, Space select, User currentUser) { SpaceBox oldSpace = (SpaceBox) bordRows[origin.y].getChildren().get(origin.x); SpaceBox newSpace = (SpaceBox) bordRows[select.y].getChildren().get(select.x); removeColour((SpaceBox) bordRows[origin.y].getChildren().get(origin.x)); gameData.gameBoard.getBord()[origin.x][origin.y].deselect(); setInfected(select, currentUser.getPlayerNumber()); gameData.gameBoard.getBord()[select.x][select.y].take(currentUser.getPlayerNumber()); gameData.gameBoard.getBord()[oldSpace.x][oldSpace.y].deselect(); setColour(newSpace, currentUser.getPlayerColour()); setSpaceLabel(currentUser.getPlayerNumber(), newSpace); removeSpaceLabel(oldSpace); } private void setInfected(Space select, int playerNumber) { Stapel<Space> a = gameData.gameBoard.getInfected(select, playerNumber); while (!a.isEmpty()) { try { Space t = a.pop(); gameData.gameBoard.setInfected(t, playerNumber); addPoint(1); removePoint(1); setColour((SpaceBox) bordRows[t.y].getChildren().get(t.x), gameData.currentPlayer.getPlayerColour()); setSpaceLabel(gameData.currentPlayer.getPlayerNumber(), (SpaceBox) bordRows[t.y].getChildren().get(t.x)); } catch (UnderflowException e) { e.printStackTrace(); } } } private void addPoint(int points) { if (gameData.currentPlayer.getPlayerNumber() == 1) { gameData.increasePlayerOneScore(points); } else { gameData.increasePlayerTwoScore(points); } updatePointLabel(); } private void removePoint(int points) { if (gameData.currentPlayer.getPlayerNumber() == 1) { gameData.decreasePlayerTwoScore(points); } else { gameData.decreasePlayerOneScore(points); } updatePointLabel(); } private void updatePointLabel() { horizontalPlayerOneInfo.getScoreLabel().setText(String.valueOf(gameData.getPlayerOneScore())); horizontalPlayerTwoInfo.getScoreLabel().setText(String.valueOf(gameData.getPlayerTwoScore())); } // ----- configuring initial board ----- private void configBoard() { gameData.gameBoard.setInitialOccupied(2); drawBoard(gameData); } private void drawBoard(GameData data) { bordRows = new HBox[data.gameBoard.yGroote]; for (int y = 0; y < data.gameBoard.yGroote; y++) { HBox row = new HBox(); for (int x = 0; x < data.gameBoard.xGroote; x++) { SpaceBox spaceBox = new SpaceBox(x, y, spaceMinSize, spaceMaxSize); setBoxBorder(x, y, spaceBox); if (data.gameBoard.getBord()[x][y].isTaken()) { if (data.gameBoard.getBord()[x][y].getPlayerNumber() == 1) { setColour(spaceBox, data.getPlayer1().getPlayerColour()); setSpaceLabel(1, spaceBox); } else { setColour(spaceBox, data.getPlayer2().getPlayerColour()); setSpaceLabel(2, spaceBox); } } row.getChildren().add(spaceBox); } bordRows[y] = row; } if (!bordColumnBox.getChildren().isEmpty()) bordColumnBox.getChildren().clear(); bordColumnBox.getChildren().addAll(bordRows); } private void setBoxBorder(int x, int y, Node space) { if (gameData.gameBoard.xGroote - 1 != x && y != 0) { space.setStyle( "-fx-border-width: 2 2 0 0;\n" + "-fx-border-color: #242526;"); } else if (gameData.gameBoard.xGroote - 1 != x) { space.setStyle( "-fx-border-width: 0 2 0 0;\n" + "-fx-border-color: #242526;"); } else if (gameData.gameBoard.xGroote - 1 == x && y != 0) { space.setStyle( "-fx-border-width: 2 0 0 0;\n" + "-fx-border-color: #242526;"); } else { space.setStyle( "-fx-border-width: 0 0 0 0;\n" + "-fx-border-color: #242526;"); } } private void setSpaceLabel(int playerNumber, SpaceBox spaceBox) { if (playerNumber == 1) { spaceBox.setText("H"); } else { spaceBox.setText("B"); } } private void removeSpaceLabel(SpaceBox spaceBox) { spaceBox.setText(""); } private void setColour(SpaceBox spaceBox, String color) { String style = spaceBox.getStyle(); String newStyle = ""; if (!style.isEmpty()) { String[] t = style.split("((?=;))"); newStyle = t[0] + t[1] + ";"; } spaceBox.setStyle(newStyle + "\n-fx-background-color: #" + "B0" + color.substring(3) + ";"); } private void removeColour(SpaceBox spaceBox) { String style = spaceBox.getStyle(); String newStyle = ""; if (!style.isEmpty()) { String[] t = style.split("((?=;))"); newStyle = t[0] + t[1] + ";"; } spaceBox.setStyle(newStyle); } // ----- configuring initial turn ----- public void setInitialTurn() { Random random = new Random(); if (random.nextInt(2) == 0) { gameData.currentPlayer = gameData.getPlayer1(); setResetButtonActive(true); setNewPlayerMove(); } else { gameData.currentPlayer = gameData.getPlayer2(); setResetButtonActive(false); setNewPlayerMove(); } setTurnInfo(); } protected void setTurnInfo() { turnInfo.setText("Turn " + gameData.getTurnNumber() + " | "); } protected void setCurrentPlayer() { currentPlayerLabel.setText(gameData.currentPlayer.getPlayerName()); if (gameData.currentPlayer.getPlayerNumber() == 1) { setTurnGlow(1); setResetButtonActive(true); } else { setTurnGlow(2); setResetButtonActive(false); } } // ----- set or removes a glow when it's one player's turn or not ----- protected void setTurnGlow(int playerNumber) { if (playerNumber == 1) { addTurnGlow(horizontalPlayerOneInfo.getPlayerLabel(), horizontalPlayerOneInfo.getAvatarBox().getAvatarCircle()); removeTurnGlow(horizontalPlayerTwoInfo.getPlayerLabel(), horizontalPlayerTwoInfo.getAvatarBox().getAvatarCircle()); } else { addTurnGlow(horizontalPlayerTwoInfo.getPlayerLabel(), horizontalPlayerTwoInfo.getAvatarBox().getAvatarCircle()); removeTurnGlow(horizontalPlayerOneInfo.getPlayerLabel(), horizontalPlayerOneInfo.getAvatarBox().getAvatarCircle()); } } private void addTurnGlow(Label playerLabel, Circle avatarCircle) { Bloom bloom = new Bloom(); bloom.setThreshold(0.01); playerLabel.setEffect(bloom); avatarCircle.setEffect(bloom); } private void removeTurnGlow(Label playerLabel, Circle avatarCircle) { playerLabel.setEffect(null); avatarCircle.setEffect(null); } // ----- event that runs when the game turn goes back ----- // pops the new turn data and peeks for the previous turn data @FXML private void resetTurn() throws UnderflowException { if (!gameGeschiedenis.isEmpty()) { SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); resetButtonBox.getChildren().clear(); removeSelectAble(gameData.gameBoard.getPlayerMoves(gameData.currentPlayer.getPlayerNumber())); resetTwistedGame(gameGeschiedenis.pop()); } } private void resetTwistedGame(GameData data) { gameData = data; drawBoard(data); setOldGameData(); setTurnInfo(); updatePointLabel(); gameData.currentPlayer = gameData.getPlayer1(); setNewPlayerMove(); } protected void setResetButtonActive(boolean active) { if (!gameGeschiedenis.isEmpty()) { if(active && resetButtonBox.getChildren().isEmpty()){ resetButtonBox.getChildren().add(controllerResetTurnButton); } else { resetButtonBox.getChildren().clear(); } } else { resetButtonBox.getChildren().clear(); } } // ----- event that runs when the game has ended ----- @FXML private void endGameEvent() { SoundPlayer.playAudioFile(ButtonAudio.OK.getAudio()); if(gameData.currentPlayer.getPlayerNumber() == 1){ endGame(1,2); } else { endGame(2,1); } } protected void endGame(int oldP, int newP) { if (gameData.getPlayerOneScore() > gameData.getPlayerTwoScore()) { user1Win(); } else if (gameData.getPlayerTwoScore() > gameData.getPlayerOneScore()) { user2Win(); } else { if (gameData.gameBoard.checkBoard(newP)) { if(oldP == 1){ user1Win(); } else if(oldP == 2) { user2Win(); } } else { draw(); } } } private void user1Win(){ GameOverData gameOverData = new GameOverData(GameOverType.P1, gameData.getPlayer1(), gameData.getPlayer2(), gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber()); this.gameMenuController.setGameOverScreen(gameOverData); } private void user2Win(){ GameOverData gameOverData = new GameOverData(GameOverType.P2, gameData.getPlayer1(), gameData.getPlayer2(), gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber()); this.gameMenuController.setGameOverScreen(gameOverData); } private void draw(){ GameOverData gameOverData = new GameOverData(GameOverType.DRAW, gameData.getPlayer1(), gameData.getPlayer2(), gameData.getPlayerOneScore(), gameData.getPlayerTwoScore(), gameData.getTurnNumber()); this.gameMenuController.setGameOverScreen(gameOverData); } // ----- for adding sounds? ----- private EventHandler<? super MouseEvent> select() { return (EventHandler<MouseEvent>) event -> SoundPlayer.playAudioFile(ButtonAudio.SELECT.getAudio()); } private EventHandler<? super MouseEvent> move() { return (EventHandler<MouseEvent>) event -> SoundPlayer.playAudioFile(ButtonAudio.MOVE.getAudio()); } }
193194_1
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class UserDAO { //klasse om te interageren met de database user table public static ResultSet getAll(int demandedAge, Connection connection){ // voorbeeld van een getAll DAO, moeten deze voor elke mogelijke query String query = "SELECT user FROM user WHERE age = demandedAge"; // en elke mogelijke combinatie gemaakt worden? try { Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(query); return rs; } catch (SQLException exception) { System.err.println(exception.getMessage()); } return null; } public static ResultSet get(long usernumber, Connection connection) { // query om een user uit de lijst te halen String query = "SELECT FROM user WHERE userNumber = " + usernumber; try { Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(query); return rs; } catch (SQLException exception) { System.err.println(exception.getMessage()); } return null; } public static void update(User user, Connection connection) { // query om user up te daten String query = "INSERT INTO user " + "VALUES (user.getUserNumber,user.getAge(),user.getEmails(), user.getPhoneNumber(),user.getFirstName(), user.getLastName())"; try{ Statement statement = connection.createStatement(); statement.executeUpdate(query); } catch (SQLException exception){ System.out.println(exception.getMessage()); } } public static void delete(User user, Connection connection){ // query om user te deleten String query ="DELETE FROM users WHERE userNumber = user.getUserNumber"; try { Statement st = connection.createStatement(); st.executeUpdate(query); } catch (SQLException exception){ System.out.println(exception.getMessage()); } } public static void save(User user){ // Ik weet niet wat hier zou moeten gebeuren? } }
xanderdecat/Project27
src/UserDAO.java
575
// voorbeeld van een getAll DAO, moeten deze voor elke mogelijke query
line_comment
nl
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class UserDAO { //klasse om te interageren met de database user table public static ResultSet getAll(int demandedAge, Connection connection){ // voorbeeld van<SUF> String query = "SELECT user FROM user WHERE age = demandedAge"; // en elke mogelijke combinatie gemaakt worden? try { Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(query); return rs; } catch (SQLException exception) { System.err.println(exception.getMessage()); } return null; } public static ResultSet get(long usernumber, Connection connection) { // query om een user uit de lijst te halen String query = "SELECT FROM user WHERE userNumber = " + usernumber; try { Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(query); return rs; } catch (SQLException exception) { System.err.println(exception.getMessage()); } return null; } public static void update(User user, Connection connection) { // query om user up te daten String query = "INSERT INTO user " + "VALUES (user.getUserNumber,user.getAge(),user.getEmails(), user.getPhoneNumber(),user.getFirstName(), user.getLastName())"; try{ Statement statement = connection.createStatement(); statement.executeUpdate(query); } catch (SQLException exception){ System.out.println(exception.getMessage()); } } public static void delete(User user, Connection connection){ // query om user te deleten String query ="DELETE FROM users WHERE userNumber = user.getUserNumber"; try { Statement st = connection.createStatement(); st.executeUpdate(query); } catch (SQLException exception){ System.out.println(exception.getMessage()); } } public static void save(User user){ // Ik weet niet wat hier zou moeten gebeuren? } }
100942_8
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tengu.io; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author sander * * Sends Images to AMICA-Vision */ public class ImageSpout extends BaseRichSpout { SpoutOutputCollector _collector; //String imagePath; Integer counter; public void open(Map map, TopologyContext tc, SpoutOutputCollector soc) { _collector = soc; //magePath = map.get("path").toString(); counter = 1; } public void declareOutputFields(OutputFieldsDeclarer ofd) { ofd.declare(new Fields("id", "text")); //ofd.declare(new Fields("message")); } public void nextTuple() { Utils.sleep(3000); //Add artificial delay //try { //System.out.println("Reading image"); //File fi = new File(imagePath + counter + ".jpg"); //if (fi.exists() && !fi.isDirectory()) { //byte[] fileContent = Files.readAllBytes(fi.toPath()); //counter++; //System.out.println("Emitting byte array(" + counter + ")"); // _collector.emit(new Values("{\"id\":795579924908273665,\"text\":\"#Calpe Guardia Civil verijdelt 2 zelfmoordpogingen https://t.co/32tn93XAiG\",\"createdAt\":1478516009000,\"language\":\"nl\",\"media\":[\"http://i.imgur.com/vGUbrPo.jpg\"],\"user\":\"Herwig Waterschoot\"}")); System.out.println("EMMITING TUPLE FROM SPOUT"); _collector.emit(new Values("0001", "Dit is een voorbeeldzin")); //} // } catch (IOException ex) { // Logger.getLogger(ImageSpout.class.getName()).log(Level.SEVERE, null, ex); //} } }
xannz/amica
src/main/java/com/tengu/io/ImageSpout.java
705
// _collector.emit(new Values("{\"id\":795579924908273665,\"text\":\"#Calpe Guardia Civil verijdelt 2 zelfmoordpogingen https://t.co/32tn93XAiG\",\"createdAt\":1478516009000,\"language\":\"nl\",\"media\":[\"http://i.imgur.com/vGUbrPo.jpg\"],\"user\":\"Herwig Waterschoot\"}"));
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tengu.io; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author sander * * Sends Images to AMICA-Vision */ public class ImageSpout extends BaseRichSpout { SpoutOutputCollector _collector; //String imagePath; Integer counter; public void open(Map map, TopologyContext tc, SpoutOutputCollector soc) { _collector = soc; //magePath = map.get("path").toString(); counter = 1; } public void declareOutputFields(OutputFieldsDeclarer ofd) { ofd.declare(new Fields("id", "text")); //ofd.declare(new Fields("message")); } public void nextTuple() { Utils.sleep(3000); //Add artificial delay //try { //System.out.println("Reading image"); //File fi = new File(imagePath + counter + ".jpg"); //if (fi.exists() && !fi.isDirectory()) { //byte[] fileContent = Files.readAllBytes(fi.toPath()); //counter++; //System.out.println("Emitting byte array(" + counter + ")"); // _collector.emit(new Values("{\"id\":795579924908273665,\"text\":\"#Calpe<SUF> System.out.println("EMMITING TUPLE FROM SPOUT"); _collector.emit(new Values("0001", "Dit is een voorbeeldzin")); //} // } catch (IOException ex) { // Logger.getLogger(ImageSpout.class.getName()).log(Level.SEVERE, null, ex); //} } }
80499_2
/* * P2Tools Copyright (C) 2023 W. Xaver W.Xaver[at]googlemail.com * https://www.p2tools.de/ * * This program 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 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 General Public License along with this program. If * not, see <http://www.gnu.org/licenses/>. */ package de.p2tools.p2lib.tools.log; import de.p2tools.p2lib.P2LibConst; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.ArrayList; /** * diese Meldungen können in einem Tab "Meldungen" angesehen werden * und sind für die User gedacht (werden aber auch im PLog eingetragen) */ public class P2UserMessage { public static ObservableList<String> msgList = FXCollections.observableArrayList(); private static final int MAX_SIZE_1 = 50000; private static final int MAX_SIZE_2 = 30000; private static int lineNo = 0; static synchronized void userMsg(ArrayList<String> text) { message(text.toArray(new String[]{})); } static synchronized void userMsg(String[] text) { message(text); } static synchronized void userMsg(String text) { message(new String[]{text}); } private static void message(String[] text) { if (text.length <= 1) { notify(text[0]); } else { String line = "---------------------------------------- "; notify(line); for (int i = 0; i < text.length; ++i) { if (i == 0) { notify(text[i]); } else { notify(" " + text[i]); } } notify(" "); } } public static void clearText() { lineNo = 0; msgList.clear(); } private static void notify(String line) { addText(msgList, "[" + getNr(lineNo++) + "] " + line); } private static String getNr(int no) { final int MAX_STELLEN = 5; final String FUELL_ZEICHEN = "0"; String str = String.valueOf(no); while (str.length() < MAX_STELLEN) { str = FUELL_ZEICHEN + str; } return str; } private synchronized static void addText(ObservableList<String> text, String texte) { if (text.size() > MAX_SIZE_1) { text.remove(0, MAX_SIZE_2); } text.add(texte + P2LibConst.LINE_SEPARATOR); } public synchronized static String getText() { // wegen synchronized hier return String.join("", msgList); } }
xaverW/P2Lib
src/main/java/de/p2tools/p2lib/tools/log/P2UserMessage.java
881
// wegen synchronized hier
line_comment
nl
/* * P2Tools Copyright (C) 2023 W. Xaver W.Xaver[at]googlemail.com * https://www.p2tools.de/ * * This program 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 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 General Public License along with this program. If * not, see <http://www.gnu.org/licenses/>. */ package de.p2tools.p2lib.tools.log; import de.p2tools.p2lib.P2LibConst; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.ArrayList; /** * diese Meldungen können in einem Tab "Meldungen" angesehen werden * und sind für die User gedacht (werden aber auch im PLog eingetragen) */ public class P2UserMessage { public static ObservableList<String> msgList = FXCollections.observableArrayList(); private static final int MAX_SIZE_1 = 50000; private static final int MAX_SIZE_2 = 30000; private static int lineNo = 0; static synchronized void userMsg(ArrayList<String> text) { message(text.toArray(new String[]{})); } static synchronized void userMsg(String[] text) { message(text); } static synchronized void userMsg(String text) { message(new String[]{text}); } private static void message(String[] text) { if (text.length <= 1) { notify(text[0]); } else { String line = "---------------------------------------- "; notify(line); for (int i = 0; i < text.length; ++i) { if (i == 0) { notify(text[i]); } else { notify(" " + text[i]); } } notify(" "); } } public static void clearText() { lineNo = 0; msgList.clear(); } private static void notify(String line) { addText(msgList, "[" + getNr(lineNo++) + "] " + line); } private static String getNr(int no) { final int MAX_STELLEN = 5; final String FUELL_ZEICHEN = "0"; String str = String.valueOf(no); while (str.length() < MAX_STELLEN) { str = FUELL_ZEICHEN + str; } return str; } private synchronized static void addText(ObservableList<String> text, String texte) { if (text.size() > MAX_SIZE_1) { text.remove(0, MAX_SIZE_2); } text.add(texte + P2LibConst.LINE_SEPARATOR); } public synchronized static String getText() { // wegen synchronized<SUF> return String.join("", msgList); } }
29850_15
/* * This file is part of the constraint solver ACE (AbsCon Essence). * * Copyright (c) 2021. All rights reserved. * Christophe Lecoutre, CRIL, Univ. Artois and CNRS. * * Licensed under the MIT License. * See LICENSE file in the project root for full license information. */ package constraints.extension; import static utility.Kit.control; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; import java.util.stream.Stream; import constraints.ConstraintExtension; import constraints.ConstraintExtension.ExtensionSpecific; import constraints.extension.structures.ExtensionStructure; import constraints.extension.structures.Table; import interfaces.Observers.ObserverOnSolving; import interfaces.Tags.TagPositive; import problem.Problem; import sets.SetDense; import sets.SetSparse; import sets.SetSparseReversible; import utility.Kit; import variables.Domain; import variables.Variable; /** * This is STR3 (Simple Tabular Reduction, v3), for filtering extension (table) constraints, as described in: <br /> * "STR3: A path-optimal filtering algorithm for table constraints", Artificial Intelligence 220: 1-27 (2015) by C. * Lecoutre, C. Likitvivatanavong, and R. H. C. Yap. * * @author Christophe Lecoutre */ public final class STR3 extends ExtensionSpecific implements TagPositive, ObserverOnSolving { /********************************************************************************************** * Implementing Interfaces *********************************************************************************************/ @Override public void afterProblemConstruction(int n) { super.afterProblemConstruction(n); this.table = (TableAugmented) extStructure(); this.set = new SetSparseReversible(table.tuples.length, n + 1); int nValues = Variable.nInitValuesFor(scp); this.separatorsMaps = IntStream.rangeClosed(0, n).mapToObj(i -> new SetSparseMapSTR3(nValues)).toArray(SetSparseMapSTR3[]::new); // above do we need rangeClosed ? this.deps = IntStream.range(0, set.dense.length).mapToObj(i -> new LocalSetSparseByte(scp.length, false)).toArray(LocalSetSparseByte[]::new); if (set.capacity() >= Short.MAX_VALUE) this.separators = Variable.litterals(scp).intArray(); else this.separatorsShort = Variable.litterals(scp).shortArray(); } @Override public void restoreBefore(int depth) { set.restoreLimitAtLevel(depth); SetSparseMapSTR3 map = separatorsMaps[depth]; int[] dense = map.dense; if (separators != null) { for (int i = map.limit; i >= 0; i--) { int mapIndex = dense[i]; int x = map.positions[mapIndex]; int a = mapIndex - offsetsForMaps[x]; separators[x][a] = map.sseparators[mapIndex]; } } else { for (int i = map.limit; i >= 0; i--) { int mapIndex = dense[i]; int x = map.positions[mapIndex]; int a = mapIndex - offsetsForMaps[x]; separatorsShort[x][a] = (short) map.sseparators[mapIndex]; } } map.clear(); for (int i = futvars.limit; i >= 0; i--) { int x = futvars.dense[i]; frontiers[x] = doms[x].lastRemoved(); } } /********************************************************************************************** * Inner classes *********************************************************************************************/ private static final class TableAugmented extends Table { /** * subtables[x][a][k] is the tid (position in tuples) of the kth tuple where x = a */ public int[][][] subtables; public short[][][] subtablesShort; // short version private void buildSubtables() { Variable[] scp = firstRegisteredCtr().scp; if (tuples.length >= Short.MAX_VALUE) { List<Integer>[][] tmp = Variable.litterals(scp).listArray(); for (int tid = 0; tid < tuples.length; tid++) for (int x = 0; x < scp.length; x++) tmp[x][tuples[tid][x]].add(tid); subtables = Stream.of(tmp).map(m -> Kit.intArray2D(m)).toArray(int[][][]::new); } else { List<Short>[][] tmp = Variable.litterals(scp).listArray(); for (int tid = 0; tid < tuples.length; tid++) for (int x = 0; x < scp.length; x++) tmp[x][tuples[tid][x]].add((short) tid); subtablesShort = Stream.of(tmp).map(m -> Kit.shortArray2D(m)).toArray(short[][][]::new); } } @Override public void storeTuples(int[][] tuples, boolean positive) { super.storeTuples(tuples, positive); buildSubtables(); } public TableAugmented(ConstraintExtension c) { super(c); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (subtables != null) for (int i = 0; i < subtables.length; i++) { sb.append("Variable " + firstRegisteredCtr().scp[i] + "\n"); for (int j = 0; j < subtables[i].length; j++) sb.append(" " + j + " : " + Kit.join(subtables[i][j]) + "\n"); } if (subtablesShort != null) for (int i = 0; i < subtablesShort.length; i++) { sb.append("Variable " + firstRegisteredCtr().scp[i] + "\n"); for (int j = 0; j < subtablesShort[i].length; j++) sb.append(" " + j + " : " + Kit.join(subtablesShort[i][j]) + "\n"); } return sb.toString(); } } private final class SetSparseMapSTR3 extends SetSparse { public short[] positions; public int[] sseparators; public SetSparseMapSTR3(int capacity) { super(capacity, false); control(0 < capacity && capacity <= Short.MAX_VALUE); this.positions = new short[capacity]; for (short i = 0; i < positions.length; i++) positions[i] = i; this.sseparators = new int[capacity]; } @Override public final boolean add(int a) { throw new RuntimeException("Must not be called without a second argument"); } public boolean add(int a, int position, int separator) { assert position < Byte.MAX_VALUE; boolean added = super.add(a); if (added) { positions[a] = (short) position; sseparators[a] = separator; } return added; } } private final class LocalSetSparseByte { private byte[] dense; private byte[] sparse; private byte limit; public LocalSetSparseByte(int capacity, boolean initiallyFull) { control(0 < capacity && capacity <= Byte.MAX_VALUE); this.dense = new byte[capacity]; for (byte i = 0; i < dense.length; i++) dense[i] = i; this.sparse = new byte[capacity]; for (byte i = 0; i < sparse.length; i++) sparse[i] = i; this.limit = (byte) (initiallyFull ? dense.length - 1 : -1); } public boolean add(byte e) { byte i = sparse[e]; if (i <= limit) return false; // not added because already present limit++; if (i > limit) { byte f = dense[limit]; dense[i] = f; dense[limit] = e; sparse[e] = limit; sparse[f] = i; } return true; // added } public boolean remove(byte e) { byte i = sparse[e]; if (i > limit) return false; // not removed because not present if (i != limit) { byte f = dense[limit]; dense[i] = f; dense[limit] = e; sparse[e] = limit; sparse[f] = i; } limit--; return true; // removed } } /********************************************************************************************** * Fields, constructor and preprocessing *********************************************************************************************/ /** * The (augmented) table used with STR3 */ private TableAugmented table; /** * The reversible sparse set storing the indexes (of tuples) of the current table */ private SetSparseReversible set; /** * Only used at preprocessing, ac[x][a] indicates if a support has been found for (x,a) */ private boolean[][] ac; /** * Only used at preprocessing, cnts[x] is the number of values in the current domain of x with no found support * (yet) */ private int[] cnts; /** * separators[x][a] is the separator for (x,a) in the associated subtable */ private int[][] separators; private short[][] separatorsShort; // short version private final int[] offsetsForMaps; // 1D = variable (position) private SetSparseMapSTR3[] separatorsMaps; // 1D = depth /** * deps[p] is the variable position of the tuple at position p in set (so we can obtain the value in the tuple) */ private LocalSetSparseByte[] deps; /** * frontiers[x] is the frontier for variable x */ private final int[] frontiers; public STR3(Problem pb, Variable[] scp) { super(pb, scp); this.offsetsForMaps = new int[scp.length]; for (int i = 1; i < offsetsForMaps.length; i++) offsetsForMaps[i] = offsetsForMaps[i - 1] + scp[i - 1].dom.initSize(); this.ac = Variable.litterals(scp).booleanArray(); this.cnts = new int[scp.length]; this.frontiers = new int[scp.length]; } @Override protected ExtensionStructure buildExtensionStructure() { return new TableAugmented(this); } /********************************************************************************************** * Methods related to propagation at preprocessing *********************************************************************************************/ private boolean updateDomainsAtPreprocessing(int cnt) { for (int x = scp.length - 1; x >= 0 && cnt > 0; x--) { int nRemovals = cnts[x]; if (nRemovals == 0) continue; if (scp[x].dom.remove(ac[x], nRemovals) == false) return false; cnt -= nRemovals; } return true; } private boolean filterAtPreprocessing() { int cnt = 0; for (int i = 0; i < scp.length; i++) { cnt += (cnts[i] = doms[i].size()); Arrays.fill(ac[i], false); } for (int i = set.limit; i >= 0; i--) { int[] tuple = table.tuples[set.dense[i]]; if (isValid(tuple)) { for (int x = scp.length - 1; x >= 0; x--) { int a = tuple[x]; if (!ac[x][a]) { cnt--; cnts[x]--; ac[x][a] = true; } } } else set.removeAtPosition(i, 0); } return updateDomainsAtPreprocessing(cnt); } /********************************************************************************************** * Methods called between preprocessing and search *********************************************************************************************/ @Override public void beforeSearch() { ac = null; cnts = null; for (int i = 0; i < frontiers.length; i++) frontiers[i] = doms[i].lastRemoved(); // initialization of separators and deps if (table.subtables != null) { for (int x = scp.length - 1; x >= 0; x--) { for (int a = scp[x].dom.first(); a != -1; a = scp[x].dom.next(a)) { int[] subtable = table.subtables[x][a]; int p = subtable.length - 1; while (!set.contains(subtable[p])) p--; separators[x][a] = p; p = 0; while (!set.contains(subtable[p])) p++; deps[subtable[p]].add((byte) x); } } } else { for (int x = scp.length - 1; x >= 0; x--) { for (int a = scp[x].dom.first(); a != -1; a = scp[x].dom.next(a)) { control(table.subtablesShort[x][a].length < Short.MAX_VALUE); short[] subtableShort = table.subtablesShort[x][a]; int p = subtableShort.length - 1; while (!set.contains(subtableShort[p])) p--; separatorsShort[x][a] = (short) (p); // (subtablesShort[i][index].length - 1); p = 0; while (!set.contains(subtableShort[p])) p++; deps[subtableShort[p]].add((byte) x); } } } } /********************************************************************************************** * Methods related to propagation during search *********************************************************************************************/ // bug to fix for java ace BinPacking-tab-Schwerin1_BPP10.xml.lzma -r_c=10 -lc=4 -positive=str3 -r_n=20 // -varh=DDegOnDom -ev private void suppressInvalidTuplesFromRemovalsOf(int x) { Domain dom = doms[x]; if (table.subtables != null) { for (int a = dom.lastRemoved(); a != frontiers[x]; a = dom.prevRemoved(a)) { int[] t = table.subtables[x][a]; for (int p = separators[x][a]; p >= 0; p--) set.remove(t[p]); } } else { for (int a = dom.lastRemoved(); a != frontiers[x]; a = dom.prevRemoved(a)) { short[] t = table.subtablesShort[x][a]; for (int p = separatorsShort[x][a]; p >= 0; p--) set.remove(t[p]); } } } private void supressInvalidTuples() { int limitBefore = set.limit; Variable lastPast = problem.solver.futVars.lastPast(); if (lastPast != null && positionOf(lastPast) != -1) suppressInvalidTuplesFromRemovalsOf(positionOf(lastPast)); for (int i = futvars.limit; i >= 0; i--) suppressInvalidTuplesFromRemovalsOf(futvars.dense[i]); if (set.limit < limitBefore) // tuples have been removed if this condition holds if (set.limits[problem.solver.depth()] == SetDense.UNINITIALIZED) set.limits[problem.solver.depth()] = limitBefore; } @Override public boolean runPropagator(Variable dummy) { if (ac != null) return filterAtPreprocessing(); SetSparseMapSTR3 map = separatorsMaps[problem.solver.depth()]; int limitBefore = set.limit; supressInvalidTuples(); if (table.subtables != null) { for (int i = set.limit + 1; i <= limitBefore; i++) { int[] tuple = table.tuples[set.dense[i]]; // suppressed tuple LocalSetSparseByte dependencies = deps[set.dense[i]]; for (int j = dependencies.limit; j >= 0; j--) { byte x = dependencies.dense[j]; if (!scp[x].assigned()) { int a = tuple[x]; if (scp[x].dom.contains(a)) { int[] subtable = table.subtables[x][a]; int separator = separators[x][a], p = separator; while (p >= 0 && !set.contains(subtable[p])) p--; if (p < 0) { if (scp[x].dom.remove(a) == false) return false; } else { if (p != separator) { map.add(offsetsForMaps[x] + a, x, separator); separators[x][a] = p; } dependencies.remove(x); deps[subtable[p]].add(x); } } } // else dependencies.removePresentIndex(pos); } } } else { for (int i = set.limit + 1; i <= limitBefore; i++) { int[] supressedTuple = table.tuples[set.dense[i]]; LocalSetSparseByte dependencies = deps[set.dense[i]]; for (int j = dependencies.limit; j >= 0; j--) { byte x = dependencies.dense[j]; if (!scp[x].assigned()) { int a = supressedTuple[x]; if (scp[x].dom.contains(a)) { short[] subtable = table.subtablesShort[x][a]; short separator = separatorsShort[x][a], p = separator; while (p >= 0 && !set.contains(subtable[p])) p--; if (p < 0) { if (!scp[x].dom.remove(a)) return false; } else { if (p != separator) { map.add(offsetsForMaps[x] + a, x, separator); separatorsShort[x][a] = p; } dependencies.remove(x); deps[subtable[p]].add(x); } } } // else dependencies.removePresentIndex(pos); } } } for (int i = futvars.limit; i >= 0; i--) { int x = futvars.dense[i]; frontiers[x] = doms[x].lastRemoved(); } return true; } }
xcsp3team/ACE
src/main/java/constraints/extension/STR3.java
5,294
// 1D = depth
line_comment
nl
/* * This file is part of the constraint solver ACE (AbsCon Essence). * * Copyright (c) 2021. All rights reserved. * Christophe Lecoutre, CRIL, Univ. Artois and CNRS. * * Licensed under the MIT License. * See LICENSE file in the project root for full license information. */ package constraints.extension; import static utility.Kit.control; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; import java.util.stream.Stream; import constraints.ConstraintExtension; import constraints.ConstraintExtension.ExtensionSpecific; import constraints.extension.structures.ExtensionStructure; import constraints.extension.structures.Table; import interfaces.Observers.ObserverOnSolving; import interfaces.Tags.TagPositive; import problem.Problem; import sets.SetDense; import sets.SetSparse; import sets.SetSparseReversible; import utility.Kit; import variables.Domain; import variables.Variable; /** * This is STR3 (Simple Tabular Reduction, v3), for filtering extension (table) constraints, as described in: <br /> * "STR3: A path-optimal filtering algorithm for table constraints", Artificial Intelligence 220: 1-27 (2015) by C. * Lecoutre, C. Likitvivatanavong, and R. H. C. Yap. * * @author Christophe Lecoutre */ public final class STR3 extends ExtensionSpecific implements TagPositive, ObserverOnSolving { /********************************************************************************************** * Implementing Interfaces *********************************************************************************************/ @Override public void afterProblemConstruction(int n) { super.afterProblemConstruction(n); this.table = (TableAugmented) extStructure(); this.set = new SetSparseReversible(table.tuples.length, n + 1); int nValues = Variable.nInitValuesFor(scp); this.separatorsMaps = IntStream.rangeClosed(0, n).mapToObj(i -> new SetSparseMapSTR3(nValues)).toArray(SetSparseMapSTR3[]::new); // above do we need rangeClosed ? this.deps = IntStream.range(0, set.dense.length).mapToObj(i -> new LocalSetSparseByte(scp.length, false)).toArray(LocalSetSparseByte[]::new); if (set.capacity() >= Short.MAX_VALUE) this.separators = Variable.litterals(scp).intArray(); else this.separatorsShort = Variable.litterals(scp).shortArray(); } @Override public void restoreBefore(int depth) { set.restoreLimitAtLevel(depth); SetSparseMapSTR3 map = separatorsMaps[depth]; int[] dense = map.dense; if (separators != null) { for (int i = map.limit; i >= 0; i--) { int mapIndex = dense[i]; int x = map.positions[mapIndex]; int a = mapIndex - offsetsForMaps[x]; separators[x][a] = map.sseparators[mapIndex]; } } else { for (int i = map.limit; i >= 0; i--) { int mapIndex = dense[i]; int x = map.positions[mapIndex]; int a = mapIndex - offsetsForMaps[x]; separatorsShort[x][a] = (short) map.sseparators[mapIndex]; } } map.clear(); for (int i = futvars.limit; i >= 0; i--) { int x = futvars.dense[i]; frontiers[x] = doms[x].lastRemoved(); } } /********************************************************************************************** * Inner classes *********************************************************************************************/ private static final class TableAugmented extends Table { /** * subtables[x][a][k] is the tid (position in tuples) of the kth tuple where x = a */ public int[][][] subtables; public short[][][] subtablesShort; // short version private void buildSubtables() { Variable[] scp = firstRegisteredCtr().scp; if (tuples.length >= Short.MAX_VALUE) { List<Integer>[][] tmp = Variable.litterals(scp).listArray(); for (int tid = 0; tid < tuples.length; tid++) for (int x = 0; x < scp.length; x++) tmp[x][tuples[tid][x]].add(tid); subtables = Stream.of(tmp).map(m -> Kit.intArray2D(m)).toArray(int[][][]::new); } else { List<Short>[][] tmp = Variable.litterals(scp).listArray(); for (int tid = 0; tid < tuples.length; tid++) for (int x = 0; x < scp.length; x++) tmp[x][tuples[tid][x]].add((short) tid); subtablesShort = Stream.of(tmp).map(m -> Kit.shortArray2D(m)).toArray(short[][][]::new); } } @Override public void storeTuples(int[][] tuples, boolean positive) { super.storeTuples(tuples, positive); buildSubtables(); } public TableAugmented(ConstraintExtension c) { super(c); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (subtables != null) for (int i = 0; i < subtables.length; i++) { sb.append("Variable " + firstRegisteredCtr().scp[i] + "\n"); for (int j = 0; j < subtables[i].length; j++) sb.append(" " + j + " : " + Kit.join(subtables[i][j]) + "\n"); } if (subtablesShort != null) for (int i = 0; i < subtablesShort.length; i++) { sb.append("Variable " + firstRegisteredCtr().scp[i] + "\n"); for (int j = 0; j < subtablesShort[i].length; j++) sb.append(" " + j + " : " + Kit.join(subtablesShort[i][j]) + "\n"); } return sb.toString(); } } private final class SetSparseMapSTR3 extends SetSparse { public short[] positions; public int[] sseparators; public SetSparseMapSTR3(int capacity) { super(capacity, false); control(0 < capacity && capacity <= Short.MAX_VALUE); this.positions = new short[capacity]; for (short i = 0; i < positions.length; i++) positions[i] = i; this.sseparators = new int[capacity]; } @Override public final boolean add(int a) { throw new RuntimeException("Must not be called without a second argument"); } public boolean add(int a, int position, int separator) { assert position < Byte.MAX_VALUE; boolean added = super.add(a); if (added) { positions[a] = (short) position; sseparators[a] = separator; } return added; } } private final class LocalSetSparseByte { private byte[] dense; private byte[] sparse; private byte limit; public LocalSetSparseByte(int capacity, boolean initiallyFull) { control(0 < capacity && capacity <= Byte.MAX_VALUE); this.dense = new byte[capacity]; for (byte i = 0; i < dense.length; i++) dense[i] = i; this.sparse = new byte[capacity]; for (byte i = 0; i < sparse.length; i++) sparse[i] = i; this.limit = (byte) (initiallyFull ? dense.length - 1 : -1); } public boolean add(byte e) { byte i = sparse[e]; if (i <= limit) return false; // not added because already present limit++; if (i > limit) { byte f = dense[limit]; dense[i] = f; dense[limit] = e; sparse[e] = limit; sparse[f] = i; } return true; // added } public boolean remove(byte e) { byte i = sparse[e]; if (i > limit) return false; // not removed because not present if (i != limit) { byte f = dense[limit]; dense[i] = f; dense[limit] = e; sparse[e] = limit; sparse[f] = i; } limit--; return true; // removed } } /********************************************************************************************** * Fields, constructor and preprocessing *********************************************************************************************/ /** * The (augmented) table used with STR3 */ private TableAugmented table; /** * The reversible sparse set storing the indexes (of tuples) of the current table */ private SetSparseReversible set; /** * Only used at preprocessing, ac[x][a] indicates if a support has been found for (x,a) */ private boolean[][] ac; /** * Only used at preprocessing, cnts[x] is the number of values in the current domain of x with no found support * (yet) */ private int[] cnts; /** * separators[x][a] is the separator for (x,a) in the associated subtable */ private int[][] separators; private short[][] separatorsShort; // short version private final int[] offsetsForMaps; // 1D = variable (position) private SetSparseMapSTR3[] separatorsMaps; // 1D =<SUF> /** * deps[p] is the variable position of the tuple at position p in set (so we can obtain the value in the tuple) */ private LocalSetSparseByte[] deps; /** * frontiers[x] is the frontier for variable x */ private final int[] frontiers; public STR3(Problem pb, Variable[] scp) { super(pb, scp); this.offsetsForMaps = new int[scp.length]; for (int i = 1; i < offsetsForMaps.length; i++) offsetsForMaps[i] = offsetsForMaps[i - 1] + scp[i - 1].dom.initSize(); this.ac = Variable.litterals(scp).booleanArray(); this.cnts = new int[scp.length]; this.frontiers = new int[scp.length]; } @Override protected ExtensionStructure buildExtensionStructure() { return new TableAugmented(this); } /********************************************************************************************** * Methods related to propagation at preprocessing *********************************************************************************************/ private boolean updateDomainsAtPreprocessing(int cnt) { for (int x = scp.length - 1; x >= 0 && cnt > 0; x--) { int nRemovals = cnts[x]; if (nRemovals == 0) continue; if (scp[x].dom.remove(ac[x], nRemovals) == false) return false; cnt -= nRemovals; } return true; } private boolean filterAtPreprocessing() { int cnt = 0; for (int i = 0; i < scp.length; i++) { cnt += (cnts[i] = doms[i].size()); Arrays.fill(ac[i], false); } for (int i = set.limit; i >= 0; i--) { int[] tuple = table.tuples[set.dense[i]]; if (isValid(tuple)) { for (int x = scp.length - 1; x >= 0; x--) { int a = tuple[x]; if (!ac[x][a]) { cnt--; cnts[x]--; ac[x][a] = true; } } } else set.removeAtPosition(i, 0); } return updateDomainsAtPreprocessing(cnt); } /********************************************************************************************** * Methods called between preprocessing and search *********************************************************************************************/ @Override public void beforeSearch() { ac = null; cnts = null; for (int i = 0; i < frontiers.length; i++) frontiers[i] = doms[i].lastRemoved(); // initialization of separators and deps if (table.subtables != null) { for (int x = scp.length - 1; x >= 0; x--) { for (int a = scp[x].dom.first(); a != -1; a = scp[x].dom.next(a)) { int[] subtable = table.subtables[x][a]; int p = subtable.length - 1; while (!set.contains(subtable[p])) p--; separators[x][a] = p; p = 0; while (!set.contains(subtable[p])) p++; deps[subtable[p]].add((byte) x); } } } else { for (int x = scp.length - 1; x >= 0; x--) { for (int a = scp[x].dom.first(); a != -1; a = scp[x].dom.next(a)) { control(table.subtablesShort[x][a].length < Short.MAX_VALUE); short[] subtableShort = table.subtablesShort[x][a]; int p = subtableShort.length - 1; while (!set.contains(subtableShort[p])) p--; separatorsShort[x][a] = (short) (p); // (subtablesShort[i][index].length - 1); p = 0; while (!set.contains(subtableShort[p])) p++; deps[subtableShort[p]].add((byte) x); } } } } /********************************************************************************************** * Methods related to propagation during search *********************************************************************************************/ // bug to fix for java ace BinPacking-tab-Schwerin1_BPP10.xml.lzma -r_c=10 -lc=4 -positive=str3 -r_n=20 // -varh=DDegOnDom -ev private void suppressInvalidTuplesFromRemovalsOf(int x) { Domain dom = doms[x]; if (table.subtables != null) { for (int a = dom.lastRemoved(); a != frontiers[x]; a = dom.prevRemoved(a)) { int[] t = table.subtables[x][a]; for (int p = separators[x][a]; p >= 0; p--) set.remove(t[p]); } } else { for (int a = dom.lastRemoved(); a != frontiers[x]; a = dom.prevRemoved(a)) { short[] t = table.subtablesShort[x][a]; for (int p = separatorsShort[x][a]; p >= 0; p--) set.remove(t[p]); } } } private void supressInvalidTuples() { int limitBefore = set.limit; Variable lastPast = problem.solver.futVars.lastPast(); if (lastPast != null && positionOf(lastPast) != -1) suppressInvalidTuplesFromRemovalsOf(positionOf(lastPast)); for (int i = futvars.limit; i >= 0; i--) suppressInvalidTuplesFromRemovalsOf(futvars.dense[i]); if (set.limit < limitBefore) // tuples have been removed if this condition holds if (set.limits[problem.solver.depth()] == SetDense.UNINITIALIZED) set.limits[problem.solver.depth()] = limitBefore; } @Override public boolean runPropagator(Variable dummy) { if (ac != null) return filterAtPreprocessing(); SetSparseMapSTR3 map = separatorsMaps[problem.solver.depth()]; int limitBefore = set.limit; supressInvalidTuples(); if (table.subtables != null) { for (int i = set.limit + 1; i <= limitBefore; i++) { int[] tuple = table.tuples[set.dense[i]]; // suppressed tuple LocalSetSparseByte dependencies = deps[set.dense[i]]; for (int j = dependencies.limit; j >= 0; j--) { byte x = dependencies.dense[j]; if (!scp[x].assigned()) { int a = tuple[x]; if (scp[x].dom.contains(a)) { int[] subtable = table.subtables[x][a]; int separator = separators[x][a], p = separator; while (p >= 0 && !set.contains(subtable[p])) p--; if (p < 0) { if (scp[x].dom.remove(a) == false) return false; } else { if (p != separator) { map.add(offsetsForMaps[x] + a, x, separator); separators[x][a] = p; } dependencies.remove(x); deps[subtable[p]].add(x); } } } // else dependencies.removePresentIndex(pos); } } } else { for (int i = set.limit + 1; i <= limitBefore; i++) { int[] supressedTuple = table.tuples[set.dense[i]]; LocalSetSparseByte dependencies = deps[set.dense[i]]; for (int j = dependencies.limit; j >= 0; j--) { byte x = dependencies.dense[j]; if (!scp[x].assigned()) { int a = supressedTuple[x]; if (scp[x].dom.contains(a)) { short[] subtable = table.subtablesShort[x][a]; short separator = separatorsShort[x][a], p = separator; while (p >= 0 && !set.contains(subtable[p])) p--; if (p < 0) { if (!scp[x].dom.remove(a)) return false; } else { if (p != separator) { map.add(offsetsForMaps[x] + a, x, separator); separatorsShort[x][a] = p; } dependencies.remove(x); deps[subtable[p]].add(x); } } } // else dependencies.removePresentIndex(pos); } } } for (int i = futvars.limit; i >= 0; i--) { int x = futvars.dense[i]; frontiers[x] = doms[x].lastRemoved(); } return true; } }
143234_27
/* * 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.coyote; import java.io.IOException; import java.io.StringReader; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.WriteListener; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [[email protected]] * @author Jason Hunter [[email protected]] * @author James Todd [[email protected]] * @author Harish Prabandham * @author Hans Bergsten [[email protected]] * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Response.class); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ int status = 200; /** * Status message. */ String message = null; /** * Response headers. */ final MimeHeaders headers = new MimeHeaders(); /** * Associated output buffer. */ OutputBuffer outputBuffer; /** * Notes. */ final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ volatile boolean commited = false; /** * Action hook. */ volatile ActionHook hook; /** * HTTP specific fields. */ String contentType = null; String contentLanguage = null; String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General informations private long contentWritten = 0; private long commitTime = -1; /** * Holds request error exception. */ Exception errorException = null; /** * Has the charset been explicitly set. */ boolean charsetSet = false; Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } protected void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if (param == null) { hook.action(actionCode, this); } else { hook.action(actionCode, param); } } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status. * * @param status The status value to set */ public void setStatus(int status) { this.status = status; } /** * Get the status message. * * @return The message associated with the current status */ public String getMessage() { return message; } /** * Set the status message. * * @param message The status message to set */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return commited; } public void setCommitted(boolean v) { if (v && !this.commited) { this.commitTime = System.currentTimeMillis(); } this.commited = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return commitTime; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during request processing. * * @param ex The exception that occurred */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during request processing. * * @return The exception that occurred */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return ( errorException != null ); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { if (commited) { throw new IllegalStateException(); } recycle(); // Reset the stream action(ActionCode.RESET, this); } // -------------------- Headers -------------------- /** * Does the response contain the given header. * <br> * Warning: This method always returns <code>false</code> for Content-Type * and Content-Length. * * @param name The name of the header of interest * * @return {@code true} if the response contains the header. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { addHeader(name, value, null); } public void addHeader(String name, String value, Charset charset) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } MessageBytes mb = headers.addValue(name); if (charset != null) { mb.setCharset(charset); } mb.setString(value); } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and the default * encoding. * * @param locale The locale to use for this response */ public void setLocale(Locale locale) { if (locale == null) { return; // throw an exception? } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.toLanguageTag(); } /** * Return the content language. * * @return The language code for the language currently associated with this * response */ public String getContentLanguage() { return contentLanguage; } /* * Overrides the name of the character encoding used in the body * of the response. This method must be called prior to writing output * using getWriter(). * * @param charset String containing the name of the character encoding. */ public void setCharacterEncoding(String charset) { if (isCommitted()) return; if (charset == null) return; characterEncoding = charset; charsetSet=true; } public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = MediaType.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue != null) { charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { charsetSet = true; this.characterEncoding = charsetValue; } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && characterEncoding != null && charsetSet) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. * * @param chunk The bytes to write * * @throws IOException If an I/O error occurs during the write */ public void doWrite(ByteChunk chunk) throws IOException { outputBuffer.doWrite(chunk); contentWritten+=chunk.getLength(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; charsetSet = false; contentLength = -1; status = 200; message = null; commited = false; commitTime = -1; errorException = null; headers.clear(); // Servlet 3.1 non-blocking write listener listener = null; fireListener = false; registeredForWrite = false; // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. * * @return The total number of bytes written to the response by the * application. This will not be the number of bytes written to the * network which may be more or less than this value. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. * * @param flush Should any remaining bytes be flushed before returning the * total? If {@code false} bytes remaining in the buffer will * not be included in the returned value * * @return The total number of bytes written to the socket for this response */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ volatile WriteListener listener; private boolean fireListener = false; private boolean registeredForWrite = false; private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { synchronized (nonBlockingStateLock) { // Ensure we don't get multiple write registrations if // ServletOutputStream.isReady() returns false during a call to // onDataAvailable() registeredForWrite = true; // Need to set the fireListener flag otherwise when the // container tries to trigger onWritePossible, nothing will // happen fireListener = true; } action(ActionCode.DISPATCH_WRITE, null); if (!ContainerThreadMarker.isContainerThread()) { // Not on a container thread so need to execute the dispatch action(ActionCode.DISPATCH_EXECUTE, null); } } } public boolean isReady() { if (listener == null) { throw new IllegalStateException(sm.getString("response.notNonBlocking")); } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite() { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
xcxzzx-1/tomcat8.5
java/org/apache/coyote/Response.java
4,619
// -------------------- Headers --------------------
line_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.coyote; import java.io.IOException; import java.io.StringReader; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.WriteListener; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [[email protected]] * @author Jason Hunter [[email protected]] * @author James Todd [[email protected]] * @author Harish Prabandham * @author Hans Bergsten [[email protected]] * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Response.class); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ int status = 200; /** * Status message. */ String message = null; /** * Response headers. */ final MimeHeaders headers = new MimeHeaders(); /** * Associated output buffer. */ OutputBuffer outputBuffer; /** * Notes. */ final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ volatile boolean commited = false; /** * Action hook. */ volatile ActionHook hook; /** * HTTP specific fields. */ String contentType = null; String contentLanguage = null; String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General informations private long contentWritten = 0; private long commitTime = -1; /** * Holds request error exception. */ Exception errorException = null; /** * Has the charset been explicitly set. */ boolean charsetSet = false; Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } protected void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if (param == null) { hook.action(actionCode, this); } else { hook.action(actionCode, param); } } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status. * * @param status The status value to set */ public void setStatus(int status) { this.status = status; } /** * Get the status message. * * @return The message associated with the current status */ public String getMessage() { return message; } /** * Set the status message. * * @param message The status message to set */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return commited; } public void setCommitted(boolean v) { if (v && !this.commited) { this.commitTime = System.currentTimeMillis(); } this.commited = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return commitTime; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during request processing. * * @param ex The exception that occurred */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during request processing. * * @return The exception that occurred */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return ( errorException != null ); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { if (commited) { throw new IllegalStateException(); } recycle(); // Reset the stream action(ActionCode.RESET, this); } // -------------------- Headers<SUF> /** * Does the response contain the given header. * <br> * Warning: This method always returns <code>false</code> for Content-Type * and Content-Length. * * @param name The name of the header of interest * * @return {@code true} if the response contains the header. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { addHeader(name, value, null); } public void addHeader(String name, String value, Charset charset) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } MessageBytes mb = headers.addValue(name); if (charset != null) { mb.setCharset(charset); } mb.setString(value); } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and the default * encoding. * * @param locale The locale to use for this response */ public void setLocale(Locale locale) { if (locale == null) { return; // throw an exception? } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.toLanguageTag(); } /** * Return the content language. * * @return The language code for the language currently associated with this * response */ public String getContentLanguage() { return contentLanguage; } /* * Overrides the name of the character encoding used in the body * of the response. This method must be called prior to writing output * using getWriter(). * * @param charset String containing the name of the character encoding. */ public void setCharacterEncoding(String charset) { if (isCommitted()) return; if (charset == null) return; characterEncoding = charset; charsetSet=true; } public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = MediaType.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue != null) { charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { charsetSet = true; this.characterEncoding = charsetValue; } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && characterEncoding != null && charsetSet) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. * * @param chunk The bytes to write * * @throws IOException If an I/O error occurs during the write */ public void doWrite(ByteChunk chunk) throws IOException { outputBuffer.doWrite(chunk); contentWritten+=chunk.getLength(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; charsetSet = false; contentLength = -1; status = 200; message = null; commited = false; commitTime = -1; errorException = null; headers.clear(); // Servlet 3.1 non-blocking write listener listener = null; fireListener = false; registeredForWrite = false; // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. * * @return The total number of bytes written to the response by the * application. This will not be the number of bytes written to the * network which may be more or less than this value. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. * * @param flush Should any remaining bytes be flushed before returning the * total? If {@code false} bytes remaining in the buffer will * not be included in the returned value * * @return The total number of bytes written to the socket for this response */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ volatile WriteListener listener; private boolean fireListener = false; private boolean registeredForWrite = false; private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { synchronized (nonBlockingStateLock) { // Ensure we don't get multiple write registrations if // ServletOutputStream.isReady() returns false during a call to // onDataAvailable() registeredForWrite = true; // Need to set the fireListener flag otherwise when the // container tries to trigger onWritePossible, nothing will // happen fireListener = true; } action(ActionCode.DISPATCH_WRITE, null); if (!ContainerThreadMarker.isContainerThread()) { // Not on a container thread so need to execute the dispatch action(ActionCode.DISPATCH_EXECUTE, null); } } } public boolean isReady() { if (listener == null) { throw new IllegalStateException(sm.getString("response.notNonBlocking")); } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite() { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
189238_37
/* * Copyright 2008 JRimum Project * * 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. * * Created at: 15/02/2010 - 17:42:20 * * ================================================================================ * * Direitos autorais 2008 JRimum Project * * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que * haja exigência legal ou acordo por escrito, a distribuição de software sob * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a * reger permissões e limitações sob esta LICENÇA. * * Criado em: 15/02/2010 - 17:42:20 * */ package org.jrimum.bopepo.campolivre; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.lang.reflect.ParameterizedType; import java.math.BigDecimal; import java.math.RoundingMode; import org.jrimum.bopepo.campolivre.CampoLivre; import org.jrimum.bopepo.campolivre.CampoLivreException; import org.jrimum.bopepo.campolivre.CampoLivreFactory; import org.jrimum.domkee.financeiro.banco.ParametroBancario; import org.jrimum.domkee.financeiro.banco.ParametrosBancariosMap; import org.jrimum.domkee.financeiro.banco.febraban.Agencia; import org.jrimum.domkee.financeiro.banco.febraban.Carteira; import org.jrimum.domkee.financeiro.banco.febraban.Cedente; import org.jrimum.domkee.financeiro.banco.febraban.ContaBancaria; import org.jrimum.domkee.financeiro.banco.febraban.NumeroDaConta; import org.jrimum.domkee.financeiro.banco.febraban.Sacado; import org.jrimum.domkee.financeiro.banco.febraban.Titulo; import org.junit.Test; /** * <p> * Classe base para os testes de campos livres. Contém os métodos * básicos de testes de qualquer campo livre. * </p> * <p> * Todos os testes de campo livre devem herdar desta classe. * </p> * * @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a> * @author <a href="mailto:[email protected]">Rômulo Augusto</a> * * @since 0.2 * * @version 0.2 */ public abstract class AbstractCampoLivreBaseTest <CL extends CampoLivre>{ protected final Titulo titulo; private CampoLivre campoLivreToTest; private String campoLivreValidoAsString; public AbstractCampoLivreBaseTest() { super(); this.titulo = new Titulo(new ContaBancaria(), new Sacado("S"), new Cedente("C")); } /* * Testes para obrigatórios de todos os campos livres. */ @Test public final void seCriacaoDoCampoLivreOcorreSemFalha() { assertNotNull(campoLivreToTest); } @Test public final void seTamanhoDoCampoLivreEscritoIgualA25() { campoLivreToTest.write().length(); assertEquals(25, campoLivreToTest.write().length()); } @Test public final void seClasseDaInstaciaDoCampoLivreEstaCorreta() { @SuppressWarnings("unchecked") Class<CL> classeGeradoraDoCampoLivre = (Class<CL>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; assertEquals(classeGeradoraDoCampoLivre, campoLivreToTest.getClass()); } @Test public final void seCampoLivreEscritoEstaCorreto() { campoLivreToTest.write(); assertEquals(campoLivreValidoAsString, campoLivreToTest.write()); } /* * Testes para uso específico */ protected final void testeSeNaoPermiteAgenciaNula() throws CampoLivreException{ titulo.getContaBancaria().setAgencia(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteAgenciaComCodigoZero() throws CampoLivreException{ titulo.getContaBancaria().setAgencia(new Agencia(-0)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteAgenciaComCodigoNegativo() throws IllegalArgumentException{ //uma exceção deve ser lançada aqui titulo.getContaBancaria().setAgencia(new Agencia(-1)); } protected final void testeSeNaoPermiteNumeroDaAgenciaComDigitosAcimaDoLimite(int limiteAcima) throws CampoLivreException { titulo.getContaBancaria().setAgencia(new Agencia(limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaAgenciaNulo() throws CampoLivreException { titulo.getContaBancaria().setAgencia(new Agencia(1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaAgenciaNaoNumerico() throws CampoLivreException { titulo.getContaBancaria().setAgencia(new Agencia(1,"X")); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraNula() throws CampoLivreException { titulo.getContaBancaria().setCarteira(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraSemTipoDeCobranca() throws CampoLivreException{ titulo.getContaBancaria().setCarteira(new Carteira()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraComCodigoNegativo() throws CampoLivreException{ titulo.getContaBancaria().setCarteira(new Carteira(-1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraComCodigoAcimaDoLimite(int limiteAcima) throws CampoLivreException{ titulo.getContaBancaria().setCarteira(new Carteira(limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroNulo() throws CampoLivreException{ titulo.setNossoNumero(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroComBrancos(int nnLength) throws CampoLivreException{ StringBuilder nnBlank = new StringBuilder(nnLength); for(int i = 1; i <= nnLength; i++){ nnBlank.append(" "); } titulo.setNossoNumero(nnBlank.toString()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroComEspacos(int nnLength) throws CampoLivreException{ //Nosso número randômico String nnRadom = nossoNumeroRadom(nnLength); char[] nn = nnRadom.toCharArray(); //Com espaço (+ ou -) no meio nn[nnRadom.length()/2] = ' '; titulo.setNossoNumero(nn.toString()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroComTamanhoDiferenteDoEspecificado(int nnOutLength) throws CampoLivreException{ titulo.setNossoNumero(nossoNumeroRadom(nnOutLength)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaNulo() throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaComCodigoZero() throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(0)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaComCodigoNegativo() throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(-1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaComCodigoAcimaDoLimite(int limiteAcima) throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaNulo() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaVazio() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1,EMPTY)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaNegativo() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1,"-1")); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaNaoNumerico() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1,"X")); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteParametroBancarioNulo() throws CampoLivreException{ titulo.setParametrosBancarios(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteParametroBancarioAusente() throws CampoLivreException{ titulo.setParametrosBancarios(new ParametrosBancariosMap()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteParametroBancarioSemValor(ParametroBancario<?> parametro) throws IllegalArgumentException{ //uma exceção deve ser lançada aqui titulo.setParametrosBancarios(new ParametrosBancariosMap(parametro, null)); } protected final void testeSeNaoPermiteParametroBancarioComValorAcimaDoLimite(ParametroBancario<?> parametro, Integer limiteAcima) throws IllegalArgumentException{ titulo.setParametrosBancarios(new ParametrosBancariosMap(parametro, limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteValorDoTituloNulo() throws NullPointerException{ //uma exceção deve ser lançada aqui titulo.setValor(null); } protected final void testeSeNaoPermiteValorDoTituloNegativo() throws CampoLivreException{ titulo.setValor(BigDecimal.valueOf(-23.4150)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } /* * Obtenção de novas instâncias. */ public final void createCampoLivreToTest() { this.campoLivreToTest = CampoLivreFactory.create(titulo); } /* * Acessores */ /** * Simplesmente escreve o campo livre executando o método {@code write()}. * * @return campo livre */ public final String writeCampoLivre(){ return campoLivreToTest.write(); } protected final void setCampoLivreEsperadoComoString(String campoLivreValidoAsString) { this.campoLivreValidoAsString = campoLivreValidoAsString; } /* * Helpers */ /** * Gera um nosso numero randomicamente com o tamanho determinado. * * @param nnLength * @return geraNossoNumero */ private final String nossoNumeroRadom(int nnLength){ //Nosso número randômico return new BigDecimal(Math.random()).movePointRight(nnLength).setScale(0,RoundingMode.DOWN).toString(); } }
xdevelsistemas/xDevPlayApp
modules/bopepo/test/org/jrimum/bopepo/campolivre/AbstractCampoLivreBaseTest.java
4,462
/* * Helpers */
block_comment
nl
/* * Copyright 2008 JRimum Project * * 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. * * Created at: 15/02/2010 - 17:42:20 * * ================================================================================ * * Direitos autorais 2008 JRimum Project * * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que * haja exigência legal ou acordo por escrito, a distribuição de software sob * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a * reger permissões e limitações sob esta LICENÇA. * * Criado em: 15/02/2010 - 17:42:20 * */ package org.jrimum.bopepo.campolivre; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.lang.reflect.ParameterizedType; import java.math.BigDecimal; import java.math.RoundingMode; import org.jrimum.bopepo.campolivre.CampoLivre; import org.jrimum.bopepo.campolivre.CampoLivreException; import org.jrimum.bopepo.campolivre.CampoLivreFactory; import org.jrimum.domkee.financeiro.banco.ParametroBancario; import org.jrimum.domkee.financeiro.banco.ParametrosBancariosMap; import org.jrimum.domkee.financeiro.banco.febraban.Agencia; import org.jrimum.domkee.financeiro.banco.febraban.Carteira; import org.jrimum.domkee.financeiro.banco.febraban.Cedente; import org.jrimum.domkee.financeiro.banco.febraban.ContaBancaria; import org.jrimum.domkee.financeiro.banco.febraban.NumeroDaConta; import org.jrimum.domkee.financeiro.banco.febraban.Sacado; import org.jrimum.domkee.financeiro.banco.febraban.Titulo; import org.junit.Test; /** * <p> * Classe base para os testes de campos livres. Contém os métodos * básicos de testes de qualquer campo livre. * </p> * <p> * Todos os testes de campo livre devem herdar desta classe. * </p> * * @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a> * @author <a href="mailto:[email protected]">Rômulo Augusto</a> * * @since 0.2 * * @version 0.2 */ public abstract class AbstractCampoLivreBaseTest <CL extends CampoLivre>{ protected final Titulo titulo; private CampoLivre campoLivreToTest; private String campoLivreValidoAsString; public AbstractCampoLivreBaseTest() { super(); this.titulo = new Titulo(new ContaBancaria(), new Sacado("S"), new Cedente("C")); } /* * Testes para obrigatórios de todos os campos livres. */ @Test public final void seCriacaoDoCampoLivreOcorreSemFalha() { assertNotNull(campoLivreToTest); } @Test public final void seTamanhoDoCampoLivreEscritoIgualA25() { campoLivreToTest.write().length(); assertEquals(25, campoLivreToTest.write().length()); } @Test public final void seClasseDaInstaciaDoCampoLivreEstaCorreta() { @SuppressWarnings("unchecked") Class<CL> classeGeradoraDoCampoLivre = (Class<CL>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; assertEquals(classeGeradoraDoCampoLivre, campoLivreToTest.getClass()); } @Test public final void seCampoLivreEscritoEstaCorreto() { campoLivreToTest.write(); assertEquals(campoLivreValidoAsString, campoLivreToTest.write()); } /* * Testes para uso específico */ protected final void testeSeNaoPermiteAgenciaNula() throws CampoLivreException{ titulo.getContaBancaria().setAgencia(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteAgenciaComCodigoZero() throws CampoLivreException{ titulo.getContaBancaria().setAgencia(new Agencia(-0)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteAgenciaComCodigoNegativo() throws IllegalArgumentException{ //uma exceção deve ser lançada aqui titulo.getContaBancaria().setAgencia(new Agencia(-1)); } protected final void testeSeNaoPermiteNumeroDaAgenciaComDigitosAcimaDoLimite(int limiteAcima) throws CampoLivreException { titulo.getContaBancaria().setAgencia(new Agencia(limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaAgenciaNulo() throws CampoLivreException { titulo.getContaBancaria().setAgencia(new Agencia(1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaAgenciaNaoNumerico() throws CampoLivreException { titulo.getContaBancaria().setAgencia(new Agencia(1,"X")); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraNula() throws CampoLivreException { titulo.getContaBancaria().setCarteira(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraSemTipoDeCobranca() throws CampoLivreException{ titulo.getContaBancaria().setCarteira(new Carteira()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraComCodigoNegativo() throws CampoLivreException{ titulo.getContaBancaria().setCarteira(new Carteira(-1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteCarteiraComCodigoAcimaDoLimite(int limiteAcima) throws CampoLivreException{ titulo.getContaBancaria().setCarteira(new Carteira(limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroNulo() throws CampoLivreException{ titulo.setNossoNumero(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroComBrancos(int nnLength) throws CampoLivreException{ StringBuilder nnBlank = new StringBuilder(nnLength); for(int i = 1; i <= nnLength; i++){ nnBlank.append(" "); } titulo.setNossoNumero(nnBlank.toString()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroComEspacos(int nnLength) throws CampoLivreException{ //Nosso número randômico String nnRadom = nossoNumeroRadom(nnLength); char[] nn = nnRadom.toCharArray(); //Com espaço (+ ou -) no meio nn[nnRadom.length()/2] = ' '; titulo.setNossoNumero(nn.toString()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNossoNumeroComTamanhoDiferenteDoEspecificado(int nnOutLength) throws CampoLivreException{ titulo.setNossoNumero(nossoNumeroRadom(nnOutLength)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaNulo() throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaComCodigoZero() throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(0)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaComCodigoNegativo() throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(-1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteNumeroDaContaComCodigoAcimaDoLimite(int limiteAcima) throws CampoLivreException{ titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaNulo() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaVazio() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1,EMPTY)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaNegativo() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1,"-1")); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteDigitoDaContaNaoNumerico() throws CampoLivreException { titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1,"X")); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteParametroBancarioNulo() throws CampoLivreException{ titulo.setParametrosBancarios(null); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteParametroBancarioAusente() throws CampoLivreException{ titulo.setParametrosBancarios(new ParametrosBancariosMap()); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteParametroBancarioSemValor(ParametroBancario<?> parametro) throws IllegalArgumentException{ //uma exceção deve ser lançada aqui titulo.setParametrosBancarios(new ParametrosBancariosMap(parametro, null)); } protected final void testeSeNaoPermiteParametroBancarioComValorAcimaDoLimite(ParametroBancario<?> parametro, Integer limiteAcima) throws IllegalArgumentException{ titulo.setParametrosBancarios(new ParametrosBancariosMap(parametro, limiteAcima)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } protected final void testeSeNaoPermiteValorDoTituloNulo() throws NullPointerException{ //uma exceção deve ser lançada aqui titulo.setValor(null); } protected final void testeSeNaoPermiteValorDoTituloNegativo() throws CampoLivreException{ titulo.setValor(BigDecimal.valueOf(-23.4150)); createCampoLivreToTest(); //uma exceção deve ser lançada aqui writeCampoLivre(); } /* * Obtenção de novas instâncias. */ public final void createCampoLivreToTest() { this.campoLivreToTest = CampoLivreFactory.create(titulo); } /* * Acessores */ /** * Simplesmente escreve o campo livre executando o método {@code write()}. * * @return campo livre */ public final String writeCampoLivre(){ return campoLivreToTest.write(); } protected final void setCampoLivreEsperadoComoString(String campoLivreValidoAsString) { this.campoLivreValidoAsString = campoLivreValidoAsString; } /* * Helpers <SUF>*/ /** * Gera um nosso numero randomicamente com o tamanho determinado. * * @param nnLength * @return geraNossoNumero */ private final String nossoNumeroRadom(int nnLength){ //Nosso número randômico return new BigDecimal(Math.random()).movePointRight(nnLength).setScale(0,RoundingMode.DOWN).toString(); } }
16526_3
/*-------------------------------------------------------------------------- * Copyright 2008 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // snappy-java Project // // OSInfo.java // Since: May 20, 2008 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.snappy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { private static HashMap<String, String> archMapping = new HashMap<String, String>(); public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; public static final String IBMZ = "s390"; public static final String IBMZ_64 = "s390x"; public static final String AARCH_64 = "aarch64"; public static final String RISCV_64 = "riscv64"; public static final String LOONGARCH_64 = "loongarch64"; static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac // Itenium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itenium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); // IBM z mappings archMapping.put(IBMZ, IBMZ); // IBM z 64-bit mappings archMapping.put(IBMZ_64, IBMZ_64); // Aarch64 mappings archMapping.put(AARCH_64, AARCH_64); // RISC-V mappings archMapping.put(RISCV_64, RISCV_64); // LoongArch64 mappings archMapping.put(LOONGARCH_64, LOONGARCH_64); } public static void main(String[] args) { if(args.length >= 1) { if("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } static String getHardwareName() { try { Process p = Runtime.getRuntime().exec("uname -m"); p.waitFor(); InputStream in = p.getInputStream(); try { int readLen = 0; ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[32]; while((readLen = in.read(buf, 0, buf.length)) >= 0) { b.write(buf, 0, readLen); } return b.toString(); } finally { if(in != null) { in.close(); } } } catch(Throwable e) { System.err.println("Error while running uname -m: " + e.getMessage()); return "unknown"; } } static String resolveArmArchType() { if(System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, i686 if(armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if(armType.startsWith("armv7")) { // Generic return "armv7"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if(abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } // For java7, we stil need to if run some shell commands to determine ABI of JVM try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String javaHome = System.getProperty("java.home"); String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if(exitCode == 0) { return "armv7"; } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String osArch = System.getProperty("os.arch"); // For Android if(isAndroid()) { return "android-arm"; } if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if(osName.contains("Windows")) { return "Windows"; } else if(osName.contains("Mac")) { return "Mac"; } else if(osName.contains("Linux")) { return "Linux"; } else if(osName.contains("AIX")) { return "AIX"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } }
xerial/snappy-java
src/main/java/org/xerial/snappy/OSInfo.java
2,444
// Needed for openjdk7 in Mac
line_comment
nl
/*-------------------------------------------------------------------------- * Copyright 2008 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // snappy-java Project // // OSInfo.java // Since: May 20, 2008 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.snappy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { private static HashMap<String, String> archMapping = new HashMap<String, String>(); public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; public static final String IBMZ = "s390"; public static final String IBMZ_64 = "s390x"; public static final String AARCH_64 = "aarch64"; public static final String RISCV_64 = "riscv64"; public static final String LOONGARCH_64 = "loongarch64"; static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for<SUF> // Itenium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itenium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); // IBM z mappings archMapping.put(IBMZ, IBMZ); // IBM z 64-bit mappings archMapping.put(IBMZ_64, IBMZ_64); // Aarch64 mappings archMapping.put(AARCH_64, AARCH_64); // RISC-V mappings archMapping.put(RISCV_64, RISCV_64); // LoongArch64 mappings archMapping.put(LOONGARCH_64, LOONGARCH_64); } public static void main(String[] args) { if(args.length >= 1) { if("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } static String getHardwareName() { try { Process p = Runtime.getRuntime().exec("uname -m"); p.waitFor(); InputStream in = p.getInputStream(); try { int readLen = 0; ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[32]; while((readLen = in.read(buf, 0, buf.length)) >= 0) { b.write(buf, 0, readLen); } return b.toString(); } finally { if(in != null) { in.close(); } } } catch(Throwable e) { System.err.println("Error while running uname -m: " + e.getMessage()); return "unknown"; } } static String resolveArmArchType() { if(System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, i686 if(armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if(armType.startsWith("armv7")) { // Generic return "armv7"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if(abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } // For java7, we stil need to if run some shell commands to determine ABI of JVM try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String javaHome = System.getProperty("java.home"); String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if(exitCode == 0) { return "armv7"; } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String osArch = System.getProperty("os.arch"); // For Android if(isAndroid()) { return "android-arm"; } if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if(osName.contains("Windows")) { return "Windows"; } else if(osName.contains("Mac")) { return "Mac"; } else if(osName.contains("Linux")) { return "Linux"; } else if(osName.contains("AIX")) { return "AIX"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } }
16548_3
/*-------------------------------------------------------------------------- * Copyright 2008 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ // -------------------------------------- // sqlite-jdbc Project // // OSInfo.java // Since: May 20, 2008 // // $URL$ // $Author$ // -------------------------------------- package org.sqlite.util; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Locale; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { protected static ProcessRunner processRunner = new ProcessRunner(); private static final HashMap<String, String> archMapping = new HashMap<>(); public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac // Itanium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itanium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); archMapping.put("ppc64el", PPC64); archMapping.put("ppc64le", PPC64); } public static void main(String[] args) { if (args.length >= 1) { if ("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if ("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return isAndroidRuntime() || isAndroidTermux(); } public static boolean isAndroidRuntime() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } public static boolean isAndroidTermux() { try { return processRunner.runAndWaitFor("uname -o").toLowerCase().contains("android"); } catch (Exception ignored) { return false; } } public static boolean isMusl() { Path mapFilesDir = Paths.get("/proc/self/map_files"); try (Stream<Path> dirStream = Files.list(mapFilesDir)) { return dirStream .map( path -> { try { return path.toRealPath().toString(); } catch (IOException e) { return ""; } }) .anyMatch(s -> s.toLowerCase().contains("musl")); } catch (Exception ignored) { // fall back to checking for alpine linux in the event we're using an older kernel which // may not fail the above check return isAlpineLinux(); } } private static boolean isAlpineLinux() { try (Stream<String> osLines = Files.lines(Paths.get("/etc/os-release"))) { return osLines.anyMatch(l -> l.startsWith("ID") && l.contains("alpine")); } catch (Exception ignored2) { } return false; } static String getHardwareName() { try { return processRunner.runAndWaitFor("uname -m"); } catch (Throwable e) { LogHolder.logger.error("Error while running uname -m", e); return "unknown"; } } static String resolveArmArchType() { if (System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, // aarch64, i686 // for Android, we fold everything that is not aarch64 into arm if (isAndroid()) { if (armType.startsWith("aarch64")) { // Use arm64 return "aarch64"; } else { return "arm"; } } if (armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if (armType.startsWith("armv7")) { // Generic return "armv7"; } else if (armType.startsWith("armv5")) { // Use armv5, soft-float ABI return "arm"; } else if (armType.startsWith("aarch64")) { // Use arm64 return "aarch64"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if (abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } // For java7, we still need to run some shell commands to determine ABI of JVM String javaHome = System.getProperty("java.home"); try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if (exitCode == 0) { String[] cmdarray = { "/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'" }; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if (exitCode == 0) { return "armv7"; } } else { LogHolder.logger.warn( "readelf not found. Cannot check if running on an armhf system, armel architecture will be presumed"); } } catch (IOException | InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String override = System.getProperty("org.sqlite.osinfo.architecture"); if (override != null) { return override; } String osArch = System.getProperty("os.arch"); if (osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if (archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if (osName.contains("Windows")) { return "Windows"; } else if (osName.contains("Mac") || osName.contains("Darwin")) { return "Mac"; } else if (osName.contains("AIX")) { return "AIX"; } else if (isMusl()) { return "Linux-Musl"; } else if (isAndroid()) { return "Linux-Android"; } else if (osName.contains("Linux")) { return "Linux"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } /** * Class-wrapper around the logger object to avoid build-time initialization of the logging * framework in native-image */ private static class LogHolder { private static final Logger logger = LoggerFactory.getLogger(OSInfo.class); } }
xerial/sqlite-jdbc
src/main/java/org/sqlite/util/OSInfo.java
2,785
// Needed for openjdk7 in Mac
line_comment
nl
/*-------------------------------------------------------------------------- * Copyright 2008 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ // -------------------------------------- // sqlite-jdbc Project // // OSInfo.java // Since: May 20, 2008 // // $URL$ // $Author$ // -------------------------------------- package org.sqlite.util; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Locale; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { protected static ProcessRunner processRunner = new ProcessRunner(); private static final HashMap<String, String> archMapping = new HashMap<>(); public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for<SUF> // Itanium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itanium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); archMapping.put("ppc64el", PPC64); archMapping.put("ppc64le", PPC64); } public static void main(String[] args) { if (args.length >= 1) { if ("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if ("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return isAndroidRuntime() || isAndroidTermux(); } public static boolean isAndroidRuntime() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } public static boolean isAndroidTermux() { try { return processRunner.runAndWaitFor("uname -o").toLowerCase().contains("android"); } catch (Exception ignored) { return false; } } public static boolean isMusl() { Path mapFilesDir = Paths.get("/proc/self/map_files"); try (Stream<Path> dirStream = Files.list(mapFilesDir)) { return dirStream .map( path -> { try { return path.toRealPath().toString(); } catch (IOException e) { return ""; } }) .anyMatch(s -> s.toLowerCase().contains("musl")); } catch (Exception ignored) { // fall back to checking for alpine linux in the event we're using an older kernel which // may not fail the above check return isAlpineLinux(); } } private static boolean isAlpineLinux() { try (Stream<String> osLines = Files.lines(Paths.get("/etc/os-release"))) { return osLines.anyMatch(l -> l.startsWith("ID") && l.contains("alpine")); } catch (Exception ignored2) { } return false; } static String getHardwareName() { try { return processRunner.runAndWaitFor("uname -m"); } catch (Throwable e) { LogHolder.logger.error("Error while running uname -m", e); return "unknown"; } } static String resolveArmArchType() { if (System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, // aarch64, i686 // for Android, we fold everything that is not aarch64 into arm if (isAndroid()) { if (armType.startsWith("aarch64")) { // Use arm64 return "aarch64"; } else { return "arm"; } } if (armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if (armType.startsWith("armv7")) { // Generic return "armv7"; } else if (armType.startsWith("armv5")) { // Use armv5, soft-float ABI return "arm"; } else if (armType.startsWith("aarch64")) { // Use arm64 return "aarch64"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if (abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } // For java7, we still need to run some shell commands to determine ABI of JVM String javaHome = System.getProperty("java.home"); try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if (exitCode == 0) { String[] cmdarray = { "/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'" }; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if (exitCode == 0) { return "armv7"; } } else { LogHolder.logger.warn( "readelf not found. Cannot check if running on an armhf system, armel architecture will be presumed"); } } catch (IOException | InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String override = System.getProperty("org.sqlite.osinfo.architecture"); if (override != null) { return override; } String osArch = System.getProperty("os.arch"); if (osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if (archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if (osName.contains("Windows")) { return "Windows"; } else if (osName.contains("Mac") || osName.contains("Darwin")) { return "Mac"; } else if (osName.contains("AIX")) { return "AIX"; } else if (isMusl()) { return "Linux-Musl"; } else if (isAndroid()) { return "Linux-Android"; } else if (osName.contains("Linux")) { return "Linux"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } /** * Class-wrapper around the logger object to avoid build-time initialization of the logging * framework in native-image */ private static class LogHolder { private static final Logger logger = LoggerFactory.getLogger(OSInfo.class); } }
33701_3
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* This program 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 2 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 General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import cc.arduino.packages.BoardPort; import processing.app.helpers.CircularBuffer; import processing.app.helpers.Ticks; import processing.app.legacy.PApplet; import java.util.ArrayList; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.text.DefaultEditorKit; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import static processing.app.I18n.tr; public class SerialPlotter extends AbstractMonitor { private final StringBuffer messageBuffer; private JComboBox<String> serialRates; private Serial serial; private int serialRate, xCount; private JLabel noLineEndingAlert; private JTextField textField; private JButton sendButton; private JComboBox<String> lineEndings; private ArrayList<Graph> graphs; private final static int BUFFER_CAPACITY = 500; private static class Graph { public CircularBuffer buffer; private Color color; public String label; public Graph(int id) { buffer = new CircularBuffer(BUFFER_CAPACITY); color = Theme.getColorCycleColor("plotting.graphcolor", id); } public void paint(Graphics2D g, float xstep, double minY, double maxY, double rangeY, double height) { g.setColor(color); g.setStroke(new BasicStroke(1.0f)); for (int i = 0; i < buffer.size() - 1; ++i) { g.drawLine( (int) (i * xstep), (int) transformY(buffer.get(i), minY, rangeY, height), (int) ((i + 1) * xstep), (int) transformY(buffer.get(i + 1), minY, rangeY, height) ); } } private float transformY(double rawY, double minY, double rangeY, double height) { return (float) (5 + (height - 10) * (1.0 - (rawY - minY) / rangeY)); } } private class GraphPanel extends JPanel { private double minY, maxY, rangeY; private Rectangle bounds; private int xOffset, xPadding; private final Font font; private final Color bgColor, gridColor, boundsColor; public GraphPanel() { font = Theme.getFont("console.font"); bgColor = Theme.getColor("plotting.bgcolor"); gridColor = Theme.getColor("plotting.gridcolor"); boundsColor = Theme.getColor("plotting.boundscolor"); xOffset = 20; xPadding = 20; } private Ticks computeBounds() { minY = Double.POSITIVE_INFINITY; maxY = Double.NEGATIVE_INFINITY; for(Graph g : graphs) { if (!g.buffer.isEmpty()) { minY = Math.min(g.buffer.min(), minY); maxY = Math.max(g.buffer.max(), maxY); } } final double MIN_DELTA = 10.0; if (maxY - minY < MIN_DELTA) { double mid = (maxY + minY) / 2; maxY = mid + MIN_DELTA / 2; minY = mid - MIN_DELTA / 2; } Ticks ticks = new Ticks(minY, maxY, 5); minY = Math.min(minY, ticks.getTick(0)); maxY = Math.max(maxY, ticks.getTick(ticks.getTickCount() - 1)); rangeY = maxY - minY; minY -= 0.05 * rangeY; maxY += 0.05 * rangeY; rangeY = maxY - minY; return ticks; } @Override public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(font); super.paintComponent(g); bounds = g.getClipBounds(); setBackground(bgColor); if (graphs.isEmpty()) { return; } Ticks ticks = computeBounds(); g.setStroke(new BasicStroke(1.0f)); FontMetrics fm = g.getFontMetrics(); for (int i = 0; i < ticks.getTickCount(); ++i) { double tick = ticks.getTick(i); Rectangle2D fRect = fm.getStringBounds(String.valueOf(tick), g); xOffset = Math.max(xOffset, (int) fRect.getWidth() + 15); g.setColor(boundsColor); // draw tick g.drawLine(xOffset - 5, (int) transformY(tick), xOffset + 2, (int) transformY(tick)); // draw tick label g.drawString(String.valueOf(tick), xOffset - (int) fRect.getWidth() - 10, transformY(tick) - (float) fRect.getHeight() * 0.5f + fm.getAscent()); // draw horizontal grid lines g.setColor(gridColor); g.drawLine(xOffset + 3, (int) transformY(tick), bounds.width - xPadding, (int) transformY(tick)); } // handle data count int cnt = xCount - BUFFER_CAPACITY; if (xCount < BUFFER_CAPACITY) cnt = 0; double zeroTick = ticks.getTick(0); double lastTick = ticks.getTick(ticks.getTickCount() - 1); double xTickRange = BUFFER_CAPACITY / ticks.getTickCount(); for (int i = 0; i < ticks.getTickCount() + 1; i++) { String s; int xValue; int sWidth; Rectangle2D fBounds; if (i == 0) { s = String.valueOf(cnt); fBounds = fm.getStringBounds(s, g); sWidth = (int)fBounds.getWidth()/2; xValue = xOffset; } else { s = String.valueOf((int)(xTickRange * i)+cnt); fBounds = fm.getStringBounds(s, g); sWidth = (int)fBounds.getWidth()/2; xValue = (int)((bounds.width - xOffset - xPadding) * ((xTickRange * i) / BUFFER_CAPACITY) + xOffset); } // draw graph x axis, ticks and labels g.setColor(boundsColor); g.drawString(s, xValue - sWidth, (int) bounds.y + (int) transformY(zeroTick) + 15); g.drawLine(xValue, (int)transformY(zeroTick) - 2, xValue, bounds.y + (int)transformY(zeroTick) + 5); // draw vertical grid lines g.setColor(gridColor); g.drawLine(xValue, (int)transformY(zeroTick) - 3, xValue, bounds.y + (int)transformY(lastTick)); } g.setColor(boundsColor); // draw major y axis g.drawLine(bounds.x + xOffset, (int) transformY(lastTick) - 5, bounds.x + xOffset, bounds.y + (int) transformY(zeroTick) + 5); // draw major x axis g.drawLine(xOffset, (int) transformY(zeroTick), bounds.width - xPadding, (int)transformY(zeroTick)); g.setTransform(AffineTransform.getTranslateInstance(xOffset, 0)); float xstep = (float) (bounds.width - xOffset - xPadding) / (float) BUFFER_CAPACITY; // draw legend int legendXOffset = 0; for(int i = 0; i < graphs.size(); ++i) { graphs.get(i).paint(g, xstep, minY, maxY, rangeY, bounds.height); if(graphs.size() > 1) { //draw legend rectangle g.fillRect(10 + legendXOffset, 10, 10, 10); legendXOffset += 13; //draw label g.setColor(boundsColor); String s = graphs.get(i).label; if(s != null && s.length() > 0) { Rectangle2D fBounds = fm.getStringBounds(s, g); int sWidth = (int)fBounds.getWidth(); g.drawString(s, 10 + legendXOffset, 10 + (int)fBounds.getHeight() /2); legendXOffset += sWidth + 3; } } } } private float transformY(double rawY) { return (float) (5 + (bounds.height - 10) * (1.0 - (rawY - minY) / rangeY)); } @Override public Dimension getMinimumSize() { return new Dimension(200, 100); } @Override public Dimension getPreferredSize() { return new Dimension(500, 250); } } public SerialPlotter(BoardPort port) { super(port); serialRate = PreferencesData.getInteger("serial.debug_rate"); serialRates.setSelectedItem(serialRate + " " + tr("baud")); onSerialRateChange(event -> { String wholeString = (String) serialRates.getSelectedItem(); String rateString = wholeString.substring(0, wholeString.indexOf(' ')); serialRate = Integer.parseInt(rateString); PreferencesData.set("serial.debug_rate", rateString); if (serial != null) { try { close(); Thread.sleep(100); // Wait for serial port to properly close open(); } catch (Exception e) { // ignore } } }); messageBuffer = new StringBuffer(); graphs = new ArrayList<>(); } protected void onCreateWindow(Container mainPane) { mainPane.setLayout(new BorderLayout()); GraphPanel graphPanel = new GraphPanel(); mainPane.add(graphPanel, BorderLayout.CENTER); JPanel pane = new JPanel(); pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); pane.setBorder(new EmptyBorder(4, 4, 4, 4)); serialRates = new JComboBox<>(); for (String serialRateString : serialRateStrings) serialRates.addItem(serialRateString + " " + tr("baud")); serialRates.setMaximumSize(serialRates.getMinimumSize()); pane.add(Box.createHorizontalGlue()); pane.add(Box.createRigidArea(new Dimension(8, 0))); pane.add(serialRates); mainPane.add(pane, BorderLayout.SOUTH); textField = new JTextField(40); // textField is selected every time the window is focused addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent e) { textField.requestFocusInWindow(); } }); // Add cut/copy/paste contextual menu to the text input field. JPopupMenu menu = new JPopupMenu(); Action cut = new DefaultEditorKit.CutAction(); cut.putValue(Action.NAME, tr("Cut")); menu.add(cut); Action copy = new DefaultEditorKit.CopyAction(); copy.putValue(Action.NAME, tr("Copy")); menu.add(copy); Action paste = new DefaultEditorKit.PasteAction(); paste.putValue(Action.NAME, tr("Paste")); menu.add(paste); textField.setComponentPopupMenu(menu); sendButton = new JButton(tr("Send")); JPanel lowerPane = new JPanel(); lowerPane.setLayout(new BoxLayout(lowerPane, BoxLayout.X_AXIS)); lowerPane.setBorder(new EmptyBorder(4, 4, 4, 4)); noLineEndingAlert = new JLabel(I18n.format(tr("You've pressed {0} but nothing was sent. Should you select a line ending?"), tr("Send"))); noLineEndingAlert.setToolTipText(noLineEndingAlert.getText()); noLineEndingAlert.setForeground(pane.getBackground()); Dimension minimumSize = new Dimension(noLineEndingAlert.getMinimumSize()); minimumSize.setSize(minimumSize.getWidth() / 3, minimumSize.getHeight()); noLineEndingAlert.setMinimumSize(minimumSize); lineEndings = new JComboBox<String>(new String[]{tr("No line ending"), tr("Newline"), tr("Carriage return"), tr("Both NL & CR")}); lineEndings.addActionListener((ActionEvent event) -> { PreferencesData.setInteger("serial.line_ending", lineEndings.getSelectedIndex()); noLineEndingAlert.setForeground(pane.getBackground()); }); lineEndings.setMaximumSize(lineEndings.getMinimumSize()); lowerPane.add(textField); lowerPane.add(Box.createRigidArea(new Dimension(4, 0))); lowerPane.add(sendButton); pane.add(lowerPane); pane.add(noLineEndingAlert); pane.add(Box.createRigidArea(new Dimension(8, 0))); pane.add(lineEndings); applyPreferences(); onSendCommand((ActionEvent event) -> { send(textField.getText()); textField.setText(""); }); } private void send(String string) { String s = string; if (serial != null) { switch (lineEndings.getSelectedIndex()) { case 1: s += "\n"; break; case 2: s += "\r"; break; case 3: s += "\r\n"; break; default: break; } if ("".equals(s) && lineEndings.getSelectedIndex() == 0 && !PreferencesData.has("runtime.line.ending.alert.notified")) { noLineEndingAlert.setForeground(Color.RED); PreferencesData.set("runtime.line.ending.alert.notified", "true"); } serial.write(s); } } public void onSendCommand(ActionListener listener) { textField.addActionListener(listener); sendButton.addActionListener(listener); } public void applyPreferences() { // Apply line endings. if (PreferencesData.get("serial.line_ending") != null) { lineEndings.setSelectedIndex(PreferencesData.getInteger("serial.line_ending")); } } protected void onEnableWindow(boolean enable) { textField.setEnabled(enable); sendButton.setEnabled(enable); } private void onSerialRateChange(ActionListener listener) { serialRates.addActionListener(listener); } public void message(final String s) { messageBuffer.append(s); while (true) { int linebreak = messageBuffer.indexOf("\n"); if (linebreak == -1) { break; } xCount++; String line = messageBuffer.substring(0, linebreak); messageBuffer.delete(0, linebreak + 1); line = line.trim(); if (line.length() == 0) { // the line only contained trimmable characters continue; } String[] parts = line.split("[, \t]+"); if(parts.length == 0) { continue; } int validParts = 0; int validLabels = 0; for(int i = 0; i < parts.length; ++i) { Double value = null; String label = null; // column formated name value pair if(parts[i].contains(":")) { // get label String[] subString = parts[i].split("[:]+"); if(subString.length > 0) { int labelLength = subString[0].length(); if(labelLength > 32) { labelLength = 32; } label = subString[0].substring(0, labelLength); } else { label = ""; } if(subString.length > 1) { parts[i] = subString[1]; } else { parts[i] = ""; } } try { value = Double.valueOf(parts[i]); } catch (NumberFormatException e) { // ignored } //CSV header if(label == null && value == null) { label = parts[i]; } if(value != null) { if(validParts >= graphs.size()) { graphs.add(new Graph(validParts)); } graphs.get(validParts).buffer.add(value); validParts++; } if(label != null) { if(validLabels >= graphs.size()) { graphs.add(new Graph(validLabels)); } graphs.get(validLabels).label = label; validLabels++; } if(validParts > validLabels) validLabels = validParts; else if(validLabels > validParts) validParts = validLabels; } } SwingUtilities.invokeLater(SerialPlotter.this::repaint); } public void open() throws Exception { super.open(); if (serial != null) return; serial = new Serial(getBoardPort().getAddress(), serialRate) { @Override protected void message(char buff[], int n) { addToUpdateBuffer(buff, n); } }; } public void close() throws Exception { if (serial != null) { super.close(); int[] location = getPlacement(); String locationStr = PApplet.join(PApplet.str(location), ","); PreferencesData.set("last.serial.location", locationStr); serial.dispose(); serial = null; } } }
xeronith/Arduino
app/src/processing/app/SerialPlotter.java
5,353
// draw horizontal grid lines
line_comment
nl
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* This program 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 2 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 General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import cc.arduino.packages.BoardPort; import processing.app.helpers.CircularBuffer; import processing.app.helpers.Ticks; import processing.app.legacy.PApplet; import java.util.ArrayList; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.text.DefaultEditorKit; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import static processing.app.I18n.tr; public class SerialPlotter extends AbstractMonitor { private final StringBuffer messageBuffer; private JComboBox<String> serialRates; private Serial serial; private int serialRate, xCount; private JLabel noLineEndingAlert; private JTextField textField; private JButton sendButton; private JComboBox<String> lineEndings; private ArrayList<Graph> graphs; private final static int BUFFER_CAPACITY = 500; private static class Graph { public CircularBuffer buffer; private Color color; public String label; public Graph(int id) { buffer = new CircularBuffer(BUFFER_CAPACITY); color = Theme.getColorCycleColor("plotting.graphcolor", id); } public void paint(Graphics2D g, float xstep, double minY, double maxY, double rangeY, double height) { g.setColor(color); g.setStroke(new BasicStroke(1.0f)); for (int i = 0; i < buffer.size() - 1; ++i) { g.drawLine( (int) (i * xstep), (int) transformY(buffer.get(i), minY, rangeY, height), (int) ((i + 1) * xstep), (int) transformY(buffer.get(i + 1), minY, rangeY, height) ); } } private float transformY(double rawY, double minY, double rangeY, double height) { return (float) (5 + (height - 10) * (1.0 - (rawY - minY) / rangeY)); } } private class GraphPanel extends JPanel { private double minY, maxY, rangeY; private Rectangle bounds; private int xOffset, xPadding; private final Font font; private final Color bgColor, gridColor, boundsColor; public GraphPanel() { font = Theme.getFont("console.font"); bgColor = Theme.getColor("plotting.bgcolor"); gridColor = Theme.getColor("plotting.gridcolor"); boundsColor = Theme.getColor("plotting.boundscolor"); xOffset = 20; xPadding = 20; } private Ticks computeBounds() { minY = Double.POSITIVE_INFINITY; maxY = Double.NEGATIVE_INFINITY; for(Graph g : graphs) { if (!g.buffer.isEmpty()) { minY = Math.min(g.buffer.min(), minY); maxY = Math.max(g.buffer.max(), maxY); } } final double MIN_DELTA = 10.0; if (maxY - minY < MIN_DELTA) { double mid = (maxY + minY) / 2; maxY = mid + MIN_DELTA / 2; minY = mid - MIN_DELTA / 2; } Ticks ticks = new Ticks(minY, maxY, 5); minY = Math.min(minY, ticks.getTick(0)); maxY = Math.max(maxY, ticks.getTick(ticks.getTickCount() - 1)); rangeY = maxY - minY; minY -= 0.05 * rangeY; maxY += 0.05 * rangeY; rangeY = maxY - minY; return ticks; } @Override public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(font); super.paintComponent(g); bounds = g.getClipBounds(); setBackground(bgColor); if (graphs.isEmpty()) { return; } Ticks ticks = computeBounds(); g.setStroke(new BasicStroke(1.0f)); FontMetrics fm = g.getFontMetrics(); for (int i = 0; i < ticks.getTickCount(); ++i) { double tick = ticks.getTick(i); Rectangle2D fRect = fm.getStringBounds(String.valueOf(tick), g); xOffset = Math.max(xOffset, (int) fRect.getWidth() + 15); g.setColor(boundsColor); // draw tick g.drawLine(xOffset - 5, (int) transformY(tick), xOffset + 2, (int) transformY(tick)); // draw tick label g.drawString(String.valueOf(tick), xOffset - (int) fRect.getWidth() - 10, transformY(tick) - (float) fRect.getHeight() * 0.5f + fm.getAscent()); // draw horizontal<SUF> g.setColor(gridColor); g.drawLine(xOffset + 3, (int) transformY(tick), bounds.width - xPadding, (int) transformY(tick)); } // handle data count int cnt = xCount - BUFFER_CAPACITY; if (xCount < BUFFER_CAPACITY) cnt = 0; double zeroTick = ticks.getTick(0); double lastTick = ticks.getTick(ticks.getTickCount() - 1); double xTickRange = BUFFER_CAPACITY / ticks.getTickCount(); for (int i = 0; i < ticks.getTickCount() + 1; i++) { String s; int xValue; int sWidth; Rectangle2D fBounds; if (i == 0) { s = String.valueOf(cnt); fBounds = fm.getStringBounds(s, g); sWidth = (int)fBounds.getWidth()/2; xValue = xOffset; } else { s = String.valueOf((int)(xTickRange * i)+cnt); fBounds = fm.getStringBounds(s, g); sWidth = (int)fBounds.getWidth()/2; xValue = (int)((bounds.width - xOffset - xPadding) * ((xTickRange * i) / BUFFER_CAPACITY) + xOffset); } // draw graph x axis, ticks and labels g.setColor(boundsColor); g.drawString(s, xValue - sWidth, (int) bounds.y + (int) transformY(zeroTick) + 15); g.drawLine(xValue, (int)transformY(zeroTick) - 2, xValue, bounds.y + (int)transformY(zeroTick) + 5); // draw vertical grid lines g.setColor(gridColor); g.drawLine(xValue, (int)transformY(zeroTick) - 3, xValue, bounds.y + (int)transformY(lastTick)); } g.setColor(boundsColor); // draw major y axis g.drawLine(bounds.x + xOffset, (int) transformY(lastTick) - 5, bounds.x + xOffset, bounds.y + (int) transformY(zeroTick) + 5); // draw major x axis g.drawLine(xOffset, (int) transformY(zeroTick), bounds.width - xPadding, (int)transformY(zeroTick)); g.setTransform(AffineTransform.getTranslateInstance(xOffset, 0)); float xstep = (float) (bounds.width - xOffset - xPadding) / (float) BUFFER_CAPACITY; // draw legend int legendXOffset = 0; for(int i = 0; i < graphs.size(); ++i) { graphs.get(i).paint(g, xstep, minY, maxY, rangeY, bounds.height); if(graphs.size() > 1) { //draw legend rectangle g.fillRect(10 + legendXOffset, 10, 10, 10); legendXOffset += 13; //draw label g.setColor(boundsColor); String s = graphs.get(i).label; if(s != null && s.length() > 0) { Rectangle2D fBounds = fm.getStringBounds(s, g); int sWidth = (int)fBounds.getWidth(); g.drawString(s, 10 + legendXOffset, 10 + (int)fBounds.getHeight() /2); legendXOffset += sWidth + 3; } } } } private float transformY(double rawY) { return (float) (5 + (bounds.height - 10) * (1.0 - (rawY - minY) / rangeY)); } @Override public Dimension getMinimumSize() { return new Dimension(200, 100); } @Override public Dimension getPreferredSize() { return new Dimension(500, 250); } } public SerialPlotter(BoardPort port) { super(port); serialRate = PreferencesData.getInteger("serial.debug_rate"); serialRates.setSelectedItem(serialRate + " " + tr("baud")); onSerialRateChange(event -> { String wholeString = (String) serialRates.getSelectedItem(); String rateString = wholeString.substring(0, wholeString.indexOf(' ')); serialRate = Integer.parseInt(rateString); PreferencesData.set("serial.debug_rate", rateString); if (serial != null) { try { close(); Thread.sleep(100); // Wait for serial port to properly close open(); } catch (Exception e) { // ignore } } }); messageBuffer = new StringBuffer(); graphs = new ArrayList<>(); } protected void onCreateWindow(Container mainPane) { mainPane.setLayout(new BorderLayout()); GraphPanel graphPanel = new GraphPanel(); mainPane.add(graphPanel, BorderLayout.CENTER); JPanel pane = new JPanel(); pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); pane.setBorder(new EmptyBorder(4, 4, 4, 4)); serialRates = new JComboBox<>(); for (String serialRateString : serialRateStrings) serialRates.addItem(serialRateString + " " + tr("baud")); serialRates.setMaximumSize(serialRates.getMinimumSize()); pane.add(Box.createHorizontalGlue()); pane.add(Box.createRigidArea(new Dimension(8, 0))); pane.add(serialRates); mainPane.add(pane, BorderLayout.SOUTH); textField = new JTextField(40); // textField is selected every time the window is focused addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent e) { textField.requestFocusInWindow(); } }); // Add cut/copy/paste contextual menu to the text input field. JPopupMenu menu = new JPopupMenu(); Action cut = new DefaultEditorKit.CutAction(); cut.putValue(Action.NAME, tr("Cut")); menu.add(cut); Action copy = new DefaultEditorKit.CopyAction(); copy.putValue(Action.NAME, tr("Copy")); menu.add(copy); Action paste = new DefaultEditorKit.PasteAction(); paste.putValue(Action.NAME, tr("Paste")); menu.add(paste); textField.setComponentPopupMenu(menu); sendButton = new JButton(tr("Send")); JPanel lowerPane = new JPanel(); lowerPane.setLayout(new BoxLayout(lowerPane, BoxLayout.X_AXIS)); lowerPane.setBorder(new EmptyBorder(4, 4, 4, 4)); noLineEndingAlert = new JLabel(I18n.format(tr("You've pressed {0} but nothing was sent. Should you select a line ending?"), tr("Send"))); noLineEndingAlert.setToolTipText(noLineEndingAlert.getText()); noLineEndingAlert.setForeground(pane.getBackground()); Dimension minimumSize = new Dimension(noLineEndingAlert.getMinimumSize()); minimumSize.setSize(minimumSize.getWidth() / 3, minimumSize.getHeight()); noLineEndingAlert.setMinimumSize(minimumSize); lineEndings = new JComboBox<String>(new String[]{tr("No line ending"), tr("Newline"), tr("Carriage return"), tr("Both NL & CR")}); lineEndings.addActionListener((ActionEvent event) -> { PreferencesData.setInteger("serial.line_ending", lineEndings.getSelectedIndex()); noLineEndingAlert.setForeground(pane.getBackground()); }); lineEndings.setMaximumSize(lineEndings.getMinimumSize()); lowerPane.add(textField); lowerPane.add(Box.createRigidArea(new Dimension(4, 0))); lowerPane.add(sendButton); pane.add(lowerPane); pane.add(noLineEndingAlert); pane.add(Box.createRigidArea(new Dimension(8, 0))); pane.add(lineEndings); applyPreferences(); onSendCommand((ActionEvent event) -> { send(textField.getText()); textField.setText(""); }); } private void send(String string) { String s = string; if (serial != null) { switch (lineEndings.getSelectedIndex()) { case 1: s += "\n"; break; case 2: s += "\r"; break; case 3: s += "\r\n"; break; default: break; } if ("".equals(s) && lineEndings.getSelectedIndex() == 0 && !PreferencesData.has("runtime.line.ending.alert.notified")) { noLineEndingAlert.setForeground(Color.RED); PreferencesData.set("runtime.line.ending.alert.notified", "true"); } serial.write(s); } } public void onSendCommand(ActionListener listener) { textField.addActionListener(listener); sendButton.addActionListener(listener); } public void applyPreferences() { // Apply line endings. if (PreferencesData.get("serial.line_ending") != null) { lineEndings.setSelectedIndex(PreferencesData.getInteger("serial.line_ending")); } } protected void onEnableWindow(boolean enable) { textField.setEnabled(enable); sendButton.setEnabled(enable); } private void onSerialRateChange(ActionListener listener) { serialRates.addActionListener(listener); } public void message(final String s) { messageBuffer.append(s); while (true) { int linebreak = messageBuffer.indexOf("\n"); if (linebreak == -1) { break; } xCount++; String line = messageBuffer.substring(0, linebreak); messageBuffer.delete(0, linebreak + 1); line = line.trim(); if (line.length() == 0) { // the line only contained trimmable characters continue; } String[] parts = line.split("[, \t]+"); if(parts.length == 0) { continue; } int validParts = 0; int validLabels = 0; for(int i = 0; i < parts.length; ++i) { Double value = null; String label = null; // column formated name value pair if(parts[i].contains(":")) { // get label String[] subString = parts[i].split("[:]+"); if(subString.length > 0) { int labelLength = subString[0].length(); if(labelLength > 32) { labelLength = 32; } label = subString[0].substring(0, labelLength); } else { label = ""; } if(subString.length > 1) { parts[i] = subString[1]; } else { parts[i] = ""; } } try { value = Double.valueOf(parts[i]); } catch (NumberFormatException e) { // ignored } //CSV header if(label == null && value == null) { label = parts[i]; } if(value != null) { if(validParts >= graphs.size()) { graphs.add(new Graph(validParts)); } graphs.get(validParts).buffer.add(value); validParts++; } if(label != null) { if(validLabels >= graphs.size()) { graphs.add(new Graph(validLabels)); } graphs.get(validLabels).label = label; validLabels++; } if(validParts > validLabels) validLabels = validParts; else if(validLabels > validParts) validParts = validLabels; } } SwingUtilities.invokeLater(SerialPlotter.this::repaint); } public void open() throws Exception { super.open(); if (serial != null) return; serial = new Serial(getBoardPort().getAddress(), serialRate) { @Override protected void message(char buff[], int n) { addToUpdateBuffer(buff, n); } }; } public void close() throws Exception { if (serial != null) { super.close(); int[] location = getPlacement(); String locationStr = PApplet.join(PApplet.str(location), ","); PreferencesData.set("last.serial.location", locationStr); serial.dispose(); serial = null; } } }
84336_3
package org.osmdroid.bonuspack.overlays; import android.graphics.Canvas; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Overlay; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; /** * A Folder overlay implementing Z-Index to all overlays that it contains. * Like Google Maps Android API: * "An overlay with a larger z-index is drawn over overlays with smaller z-indices. * The order of overlays with the same z-index value is arbitrary. * The default is 0." * Unlike Google Maps Android API, this applies to all overlays, including Markers. * * TODO - WORK IN PROGRESS. * * @author M.Kergall */ public class FolderZOverlay extends Overlay { protected TreeSet<ZOverlay> mList; protected String mName, mDescription; protected class ZOverlay implements Comparator<ZOverlay> { float mZIndex; Overlay mOverlay; ZOverlay(Overlay o, float zIndex){ mOverlay = o; mZIndex = zIndex; } @Override public int compare(ZOverlay o1, ZOverlay o2){ return (int)Math.signum(o1.mZIndex - o2.mZIndex); } } FolderZOverlay(){ super(); mList = new TreeSet<>(); mName = ""; mDescription = ""; } public void setName(String name){ mName = name; } public String getName(){ return mName; } public void setDescription(String description){ mDescription = description; } public String getDescription(){ return mDescription; } public boolean add(Overlay item, float zIndex){ return mList.add(new ZOverlay(item, zIndex)); } public boolean add(Overlay item){ return add(item, 0); } protected ZOverlay get(Overlay overlay){ Iterator<ZOverlay> itr = mList.iterator(); while (itr.hasNext()) { ZOverlay item = itr.next(); if (item.mOverlay == overlay) { mList.remove(item); return item; } } return null; } public boolean remove(Overlay overlay) { ZOverlay item = get(overlay); if (item != null) { mList.remove(item); return true; } else return false; } /** * Change the Z-Index of an overlay. * @param overlay overlay to change * @param zIndex new Z-Index to set */ public void setZIndex(Overlay overlay, float zIndex){ ZOverlay item = get(overlay); if (item == null) return; mList.remove(item); item.mZIndex = zIndex; //TODO Check if removal/addition is really necessary. mList.add(item); } //TODO: //get highest z-index => getMaxZIndex @Override protected void draw(Canvas canvas, MapView mapView, boolean shadow) { if (shadow) return; Iterator<ZOverlay> itr=mList.iterator(); while(itr.hasNext()){ ZOverlay item = itr.next(); Overlay overlay = item.mOverlay; if (overlay!=null && overlay.isEnabled()) { //TODO overlay.draw(canvas, mapView, false); - IMPOSSIBLE, private method! } } } //TODO Implement events }
xeronith/osmbonuspack
OSMBonusPack/src/main/java/org/osmdroid/bonuspack/overlays/FolderZOverlay.java
970
//get highest z-index => getMaxZIndex
line_comment
nl
package org.osmdroid.bonuspack.overlays; import android.graphics.Canvas; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Overlay; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; /** * A Folder overlay implementing Z-Index to all overlays that it contains. * Like Google Maps Android API: * "An overlay with a larger z-index is drawn over overlays with smaller z-indices. * The order of overlays with the same z-index value is arbitrary. * The default is 0." * Unlike Google Maps Android API, this applies to all overlays, including Markers. * * TODO - WORK IN PROGRESS. * * @author M.Kergall */ public class FolderZOverlay extends Overlay { protected TreeSet<ZOverlay> mList; protected String mName, mDescription; protected class ZOverlay implements Comparator<ZOverlay> { float mZIndex; Overlay mOverlay; ZOverlay(Overlay o, float zIndex){ mOverlay = o; mZIndex = zIndex; } @Override public int compare(ZOverlay o1, ZOverlay o2){ return (int)Math.signum(o1.mZIndex - o2.mZIndex); } } FolderZOverlay(){ super(); mList = new TreeSet<>(); mName = ""; mDescription = ""; } public void setName(String name){ mName = name; } public String getName(){ return mName; } public void setDescription(String description){ mDescription = description; } public String getDescription(){ return mDescription; } public boolean add(Overlay item, float zIndex){ return mList.add(new ZOverlay(item, zIndex)); } public boolean add(Overlay item){ return add(item, 0); } protected ZOverlay get(Overlay overlay){ Iterator<ZOverlay> itr = mList.iterator(); while (itr.hasNext()) { ZOverlay item = itr.next(); if (item.mOverlay == overlay) { mList.remove(item); return item; } } return null; } public boolean remove(Overlay overlay) { ZOverlay item = get(overlay); if (item != null) { mList.remove(item); return true; } else return false; } /** * Change the Z-Index of an overlay. * @param overlay overlay to change * @param zIndex new Z-Index to set */ public void setZIndex(Overlay overlay, float zIndex){ ZOverlay item = get(overlay); if (item == null) return; mList.remove(item); item.mZIndex = zIndex; //TODO Check if removal/addition is really necessary. mList.add(item); } //TODO: //get highest<SUF> @Override protected void draw(Canvas canvas, MapView mapView, boolean shadow) { if (shadow) return; Iterator<ZOverlay> itr=mList.iterator(); while(itr.hasNext()){ ZOverlay item = itr.next(); Overlay overlay = item.mOverlay; if (overlay!=null && overlay.isEnabled()) { //TODO overlay.draw(canvas, mapView, false); - IMPOSSIBLE, private method! } } } //TODO Implement events }
167659_0
package be.xhibit.teletask.parser.handler; import be.xhibit.teletask.parser.Consumer; import java.util.ListIterator; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GeneralMoodLineHandler extends LineHandlerSupport { private static final GeneralMoodLineHandler INSTANCE = new GeneralMoodLineHandler(); private static final Pattern START_PATTERN = Pattern.compile("\\s*GENERAL MOODS"); private static final Pattern LOCAL_MOOD_PATTERN = Pattern.compile("^\\s*GMD\\s*(\\d*)\\s*([^�]*)�\\s*([^�]*)�\\s*(.*)"); private GeneralMoodLineHandler() { } public static GeneralMoodLineHandler getInstance() { return INSTANCE; } @Override public Pattern getStartPattern() { return START_PATTERN; } @Override protected void handle(String startLine, Consumer consumer, ListIterator<String> iterator, String line, int counter) { //GMD 01 � � Alles Uit gelijkvloers vooraan Matcher matcher = LOCAL_MOOD_PATTERN.matcher(line); if (matcher.find()) { consumer.generalMood(matcher.group(1), matcher.group(2).trim(), matcher.group(3).trim(), matcher.group(4).trim()); } } }
xhibit/Teletask-api
backend/config-nbt-export/src/main/java/be/xhibit/teletask/parser/handler/GeneralMoodLineHandler.java
384
//GMD 01 � � Alles Uit gelijkvloers vooraan
line_comment
nl
package be.xhibit.teletask.parser.handler; import be.xhibit.teletask.parser.Consumer; import java.util.ListIterator; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GeneralMoodLineHandler extends LineHandlerSupport { private static final GeneralMoodLineHandler INSTANCE = new GeneralMoodLineHandler(); private static final Pattern START_PATTERN = Pattern.compile("\\s*GENERAL MOODS"); private static final Pattern LOCAL_MOOD_PATTERN = Pattern.compile("^\\s*GMD\\s*(\\d*)\\s*([^�]*)�\\s*([^�]*)�\\s*(.*)"); private GeneralMoodLineHandler() { } public static GeneralMoodLineHandler getInstance() { return INSTANCE; } @Override public Pattern getStartPattern() { return START_PATTERN; } @Override protected void handle(String startLine, Consumer consumer, ListIterator<String> iterator, String line, int counter) { //GMD <SUF> Matcher matcher = LOCAL_MOOD_PATTERN.matcher(line); if (matcher.find()) { consumer.generalMood(matcher.group(1), matcher.group(2).trim(), matcher.group(3).trim(), matcher.group(4).trim()); } } }
19686_0
package me.yluo.ruisiapp.widget.htmlview; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.Stack; /** * html解析器 * html文本-> html node * startDocument-> * startElement->characters->endElement-> * endDocument */ public class HtmlParser { private static final char EOF = (char) -1; private static final int MAX_TAG_LEN = 16; private static final int MAX_ATTR_LEN = 256; //pre 标签的层数0-no >0 有 private int preLevel = 0; private Reader reader; private int srcPos, srcCount; private char[] srcBuf; private int bufPos; private char[] buf; private char readItem = EOF, lastRead = EOF; private ParserCallback handler; private final Stack<HtmlNode> stack; private int cuurEleType = HtmlTag.UNKNOWN; public HtmlParser() { stack = new Stack<>(); } public void setHandler(ParserCallback handler) { this.handler = handler; } public void parse(InputStream is) throws IOException { if (handler == null) { throw new NullPointerException("you must set ParserCallback"); } int len = is.available(); len = len < 1024 ? 1024 : (len < 4096 ? 4096 : 6114); srcBuf = new char[len]; buf = new char[(len >= 4096) ? 2048 : 1024]; this.reader = new InputStreamReader(is, StandardCharsets.UTF_8); srcPos = 0; srcCount = 0; stack.clear(); parse(); } public void parse(String s) throws IOException { if (s == null) { throw new NullPointerException("input cant be null"); } srcBuf = s.toCharArray(); srcPos = 0; srcCount = srcBuf.length; int len = srcBuf.length; stack.clear(); len = len < 2048 ? len : 2048; buf = new char[len]; parse(); } //<!doctype html> //<!--注释--> private void parse() { if (handler == null) { return; } else { handler.startDocument(srcBuf.length); } read(); while (readItem != EOF) { switch (readItem) { case EOF://end handleStop(); break; case '<'://tags read(); switch (readItem) { case '/': parseEndTag(); break; case '!': read(); if (readItem == '-') { if (read() == '-') { parseComment(); } else if (readItem != '>') { skip(); } } else { skip(); } break; case '?': skip(); break; default: parseStartTag(); break; } break; case '>': //end tag read(); parseText(); break; default: if (lastRead == EOF || lastRead == '>') { parseText(); } else { read(); } break; } } } //解析开始标签<a> <img /> <x a="b" c="d" e> //单标签只有开始 private void parseStartTag() { if ((readItem < 'a' || readItem > 'z') && (readItem < 'A' || readItem > 'Z')) { //不合法的开始标签 return; } //read name bufPos = 0; do { if (readItem >= 'A' && readItem <= 'Z') { readItem = (char) (readItem + 'a' - 'A'); } buf[bufPos++] = readItem; read(); } while (readItem != EOF && bufPos < MAX_TAG_LEN && ((readItem >= 'a' && readItem <= 'z') || (readItem >= 'A' && readItem <= 'Z') || (readItem >= '0' && readItem <= '9'))); String name = new String(buf, 0, bufPos); int type = getTagType(); bufPos = 0; if (readItem == '/') { read(); } if (readItem != '>') { if (readItem == ' ' || readItem == '\n') { readNoSpcBr(); } if (readItem == '/') { read(); } if (readItem != '>') { parseAttr(); } } if (handler != null) { if (type == HtmlTag.PRE) { preLevel++; } //说明attr长度大于等于5为有效attr HtmlNode.HtmlAttr attr = null; if (bufPos >= 5) { attr = AttrParser.parserAttr(type, buf, bufPos); } HtmlNode n = new HtmlNode(type, name, attr); pushNode(n); cuurEleType = type; handler.startElement(n); } } //解析属性值 private void parseAttr() { bufPos = 0; do { buf[bufPos++] = readItem; read(); } while (readItem != EOF && readItem != '>' && bufPos < MAX_ATTR_LEN); if (buf[(bufPos - 1)] == '/') { bufPos--; } if (readItem != '>') { skip(); } } //解析结束标签</xxx > </xxx> </xxx\n > private void parseEndTag() { bufPos = 0; while (readItem != EOF && (readItem = readNoSpcBr()) != '>') { if (bufPos >= MAX_TAG_LEN) { //不可能出现太长的tag break; } else { buf[bufPos++] = readItem; } } String s = new String(buf, 0, bufPos); int type = getTagType(); bufPos = 0; if (type == HtmlTag.PRE && preLevel > 0) { preLevel--; } popNode(type, s); handler.endElement(type, s); } //解析注释 private void parseComment() { while (readItem != EOF) { read(); read(); if (readItem == '-' && lastRead == '-') { read(); if (readItem == '>') { break; } } } } //解析文字 //处理转义 //&amp; "&" //&apos; "'" //&gt; ">" //&lt; "<" //&quot; "\" //&nbsp; ' ' private void parseText() { bufPos = 0; while (readItem != EOF && readItem != '<' && readItem != '>') { if (preLevel > 0 && bufPos > 0) {//pre 标签 原封不动push pushText(readItem); } else { //转义 if (readItem == '&') {//&nbsp; read(); if (readItem != EOF && readItem == 'n') { read(); if (readItem != EOF && readItem == 'b') { read(); if (readItem != EOF && readItem == 's') { read(); if (readItem != EOF && readItem == 'p') { read(); if (readItem != EOF && readItem == ';') { pushText(' '); //&nbsp; read(); continue;//强制空格 } else { pushText('&'); pushText('n'); pushText('b'); pushText('s'); pushText('p'); } } else { pushText('&'); pushText('n'); pushText('b'); pushText('s'); } } else { pushText('&'); pushText('n'); pushText('b'); } } else { pushText('&'); pushText('n'); } } else if (readItem != EOF && readItem == 'a') { //&amp; &apos; read(); if (readItem != EOF && readItem == 'm') {//&amp; read(); if (readItem != EOF && readItem == 'p') {//&amp; read(); if (readItem != EOF && readItem == ';') {//&amp; pushText('&'); //&nbsp; read(); continue; } else { pushText('&'); pushText('a'); pushText('m'); pushText('p'); } } else { pushText('&'); pushText('a'); pushText('m'); } } else if (readItem != EOF && readItem == 'p') {//&apos; read(); if (readItem != EOF && readItem == 'o') {//&apos; read(); if (readItem != EOF && readItem == 's') {//&apos; read(); if (readItem != EOF && readItem == ';') { pushText('\''); //&apos; read(); continue; } else { pushText('&'); pushText('a'); pushText('p'); pushText('o'); pushText('s'); } } else { pushText('&'); pushText('a'); pushText('p'); pushText('o'); } } else { pushText('&'); pushText('a'); pushText('p'); } } else { pushText('&'); pushText('a'); } } else if (readItem != EOF && readItem == 'g') {//&gt; read(); if (readItem != EOF && readItem == 't') { read(); if (readItem != EOF && readItem == ';') { pushText('>'); //&gt; read(); continue; } else { pushText('&'); pushText('g'); pushText('t'); } } else { pushText('&'); pushText('g'); } } else if (readItem != EOF && readItem == 'l') {//&lt; read(); if (readItem != EOF && readItem == 't') { read(); if (readItem != EOF && readItem == ';') { pushText('<'); //&lt; read(); continue; } else { pushText('&'); pushText('l'); pushText('t'); } } else { pushText('&'); pushText('l'); } } else if (readItem != EOF && readItem == 'q') {//&quot; read(); if (readItem != EOF && readItem == 'u') { read(); if (readItem != EOF && readItem == 'o') { read(); if (readItem != EOF && readItem == 't') { read(); if (readItem != EOF && readItem == ';') { pushText('\\'); //&nbsp; read(); continue; } else { pushText('&'); pushText('q'); pushText('u'); pushText('o'); pushText('t'); } } else { pushText('&'); pushText('q'); pushText('u'); pushText('o'); } } else { pushText('&'); pushText('q'); pushText('u'); } } else { pushText('&'); pushText('q'); } } else { pushText('&'); } } if (readItem == ' ' || readItem == '\n') { if (bufPos != 0 && buf[(bufPos - 1)] != ' ') { readItem = ' '; pushText(readItem); } } else { pushText(readItem); } } read(); } //不是空 if (bufPos > 0 && handler != null) { handler.characters(buf, 0, bufPos); } } //处理解析完成 private void handleStop() { while (!stack.isEmpty()) { HtmlNode n = stack.pop(); handler.endElement(n.type, n.name); } readItem = EOF; handler.endDocument(); } //读取一个字符 private char read() { lastRead = readItem; if (srcPos < srcCount) { readItem = srcBuf[srcPos++]; } else { if (reader == null) { readItem = EOF; } else { try { srcCount = reader.read(srcBuf, 0, srcBuf.length); } catch (IOException e) { e.printStackTrace(); readItem = EOF; } if (srcCount <= 0) { readItem = EOF; } else { readItem = srcBuf[0]; } srcPos = 1; } } switch (readItem) { case EOF: handleStop(); break; case '\r': read(); break; default: break; } return readItem; } //忽略读入的空格和回车 private char readNoSpcBr() { while (readItem != EOF) { read(); if (readItem != '\n' && readItem != ' ') { return readItem; } } return EOF; } //skip to next > or EOF private void skip() { while (readItem != EOF && readItem != '>') { read(); } } //加入一个新的文字 private void pushText(int c) { if (bufPos == buf.length) { char[] bigger = new char[bufPos * 4 / 3 + 4]; System.arraycopy(buf, 0, bigger, 0, bufPos); buf = bigger; } buf[bufPos++] = (char) c; } private boolean equalTag(int start, String b) { int len = b.length(); while (len-- != 0) { if (buf[start] != b.charAt(start)) { return false; } start++; } return true; } private int getTagType() { switch (bufPos) { case 1: switch (buf[0]) { case 'a': return HtmlTag.A; case 'b': return HtmlTag.B; case 'i': return HtmlTag.I; case 'p': return HtmlTag.P; case 'q': return HtmlTag.Q; case 's': return HtmlTag.S; case 'u': return HtmlTag.U; default: Log.w(getClass().getName(), "unknown tag type: " + buf); break; } break; case 2: switch (buf[0]) { case 'b': if (buf[1] == 'r') { return HtmlTag.BR; } break; case 'e': if (buf[1] == 'm') { return HtmlTag.EM; } break; case 'h': if ('1' <= buf[1] && buf[1] <= '6') { return (buf[1] - '1') + HtmlTag.H1; } else if (buf[1] == 'r') { return HtmlTag.HR; } break; case 'l': if (buf[1] == 'i') { return HtmlTag.LI; } break; case 'o': if (buf[1] == 'l') { return HtmlTag.OL; } break; case 't': if (buf[1] == 'd') { return HtmlTag.TD; } else if (buf[1] == 'h') { return HtmlTag.TH; } else if (buf[1] == 'r') { return HtmlTag.TR; } else if (buf[1] == 't') { return HtmlTag.TT; } break; case 'u': if (buf[1] == 'l') { return HtmlTag.UL; } break; default: return HtmlTag.UNKNOWN; } break; case 3: switch (buf[0]) { case 'b': if (buf[1] == 'i' && buf[2] == 'g') { return HtmlTag.BIG; } break; case 'd': if (buf[1] == 'e' && buf[2] == 'l') { return HtmlTag.DEL; } else if (buf[1] == 'f' && buf[2] == 'n') { return HtmlTag.DFN; } else if (buf[1] == 'i' && buf[2] == 'v') { return HtmlTag.DIV; } break; case 'i': if (buf[1] == 'm' && buf[2] == 'g') { return HtmlTag.IMG; } else if (buf[1] == 'n' && buf[2] == 's') { return HtmlTag.INS; } break; case 'k': if (buf[1] == 'b' && buf[2] == 'd') { return HtmlTag.KBD; } break; case 'p': if (buf[1] == 'r') { if (buf[2] == 'e') { return HtmlTag.PRE; } } break; case 's': if (buf[1] == 'u') { if (buf[2] == 'b') { return HtmlTag.SUB; } else if (buf[2] == 'p') { return HtmlTag.SUP; } } break; default: return HtmlTag.UNKNOWN; } break; case 4: switch (buf[0]) { case 'c': if (buf[1] == 'i' && buf[2] == 't' && buf[3] == 'e') { return HtmlTag.CITE; } else if (buf[1] == 'o' && buf[2] == 'd' && buf[3] == 'e') { return HtmlTag.CODE; } break; case 'f': if (buf[1] == 'o' && buf[2] == 'n' && buf[3] == 't') { return HtmlTag.FONT; } break; case 's': if (buf[1] == 'p' && buf[2] == 'a' && buf[3] == 'n') { return HtmlTag.SPAN; } break; case 'm': if (buf[1] == 'a' && buf[2] == 'r' && buf[3] == 'k') { return HtmlTag.MARK; } break; default: return HtmlTag.UNKNOWN; } break; case 5: switch (buf[0]) { case 's': if (equalTag(1, "mall")) { return HtmlTag.SMALL; } break; case 't': if (equalTag(1, "able")) { return HtmlTag.TABLE; } else if (equalTag(1, "body")) { return HtmlTag.TBODY; } else if (equalTag(1, "head")) { return HtmlTag.THEAD; } else if (equalTag(1, "foot")) { return HtmlTag.TFOOT; } break; case 'a': if (equalTag(1, "udio")) { return HtmlTag.AUDIO; } break; case 'v': if (equalTag(1, "edio")) { return HtmlTag.VEDIO; } break; default: return HtmlTag.UNKNOWN; } break; case 6: if (equalTag(0, "str")) { if (buf[3] == 'o' && buf[4] == 'n' && buf[5] == 'g') { return HtmlTag.STRONG; } else if (buf[3] == 'i' && buf[4] == 'k' && buf[5] == 'e') { return HtmlTag.STRIKE; } } else if (buf[4] == 'e' && buf[5] == 'f') { if (buf[0] == 'h' && buf[1] == 'e' && buf[2] == 'a' && buf[3] == 'd') { return HtmlTag.HEADER; } else if (buf[0] == 'f' && buf[1] == 'o' && buf[2] == 'o' && buf[3] == 't') { return HtmlTag.FOOTER; } } break; case 7: if (equalTag(0, "caption")) { return HtmlTag.CAPTION; } break; case 10: if (equalTag(0, "blockquote")) { return HtmlTag.BLOCKQUOTE; } break; default: return HtmlTag.UNKNOWN; } return HtmlTag.UNKNOWN; } //压栈node到stack 更新节点属性 private void pushNode(HtmlNode node) { //单标签不压栈,且属性也不继承 if (node.type == HtmlTag.IMG || node.type == HtmlTag.BR || node.type == HtmlTag.HR) { return; } HtmlNode.HtmlAttr parentAttr; if (!stack.isEmpty() && (parentAttr = stack.peek().attr) != null) { if (node.attr == null) { node.attr = parentAttr; } else { //字体颜色继承 if (node.attr.color == AttrParser.COLOR_NONE) { node.attr.color = parentAttr.color; } // textDecoration 是否需要集成? if (node.attr.textDecoration == HtmlNode.DEC_NONE) { node.attr.textDecoration = parentAttr.textDecoration; } } } //压栈 stack.push(node); } private void popNode(int type, String name) { //这些节点不在栈 if (type == HtmlTag.IMG || type == HtmlTag.BR || type == HtmlTag.HR) { return; } HtmlNode n; if (!stack.isEmpty() && (n = stack.peek()) != null) { //栈顶元素相同出栈 if (n.type == type && Objects.equals(n.name, name)) { stack.pop(); } else {//不相同 是出还是不出??? int i = stack.size() - 1; for (; i > 0; i--) { if (stack.get(i).type == type && Objects.equals(stack.get(i).name, name)) { break; } } //栈里有 一直出栈 if (i > 0) { int j = stack.size() - 1; while (j != i - 1) { stack.pop(); j--; } } } } } }
xidian-rs/Ruisi
app/src/main/java/me/yluo/ruisiapp/widget/htmlview/HtmlParser.java
7,078
/** * html解析器 * html文本-> html node * startDocument-> * startElement->characters->endElement-> * endDocument */
block_comment
nl
package me.yluo.ruisiapp.widget.htmlview; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.Stack; /** * html解析器 *<SUF>*/ public class HtmlParser { private static final char EOF = (char) -1; private static final int MAX_TAG_LEN = 16; private static final int MAX_ATTR_LEN = 256; //pre 标签的层数0-no >0 有 private int preLevel = 0; private Reader reader; private int srcPos, srcCount; private char[] srcBuf; private int bufPos; private char[] buf; private char readItem = EOF, lastRead = EOF; private ParserCallback handler; private final Stack<HtmlNode> stack; private int cuurEleType = HtmlTag.UNKNOWN; public HtmlParser() { stack = new Stack<>(); } public void setHandler(ParserCallback handler) { this.handler = handler; } public void parse(InputStream is) throws IOException { if (handler == null) { throw new NullPointerException("you must set ParserCallback"); } int len = is.available(); len = len < 1024 ? 1024 : (len < 4096 ? 4096 : 6114); srcBuf = new char[len]; buf = new char[(len >= 4096) ? 2048 : 1024]; this.reader = new InputStreamReader(is, StandardCharsets.UTF_8); srcPos = 0; srcCount = 0; stack.clear(); parse(); } public void parse(String s) throws IOException { if (s == null) { throw new NullPointerException("input cant be null"); } srcBuf = s.toCharArray(); srcPos = 0; srcCount = srcBuf.length; int len = srcBuf.length; stack.clear(); len = len < 2048 ? len : 2048; buf = new char[len]; parse(); } //<!doctype html> //<!--注释--> private void parse() { if (handler == null) { return; } else { handler.startDocument(srcBuf.length); } read(); while (readItem != EOF) { switch (readItem) { case EOF://end handleStop(); break; case '<'://tags read(); switch (readItem) { case '/': parseEndTag(); break; case '!': read(); if (readItem == '-') { if (read() == '-') { parseComment(); } else if (readItem != '>') { skip(); } } else { skip(); } break; case '?': skip(); break; default: parseStartTag(); break; } break; case '>': //end tag read(); parseText(); break; default: if (lastRead == EOF || lastRead == '>') { parseText(); } else { read(); } break; } } } //解析开始标签<a> <img /> <x a="b" c="d" e> //单标签只有开始 private void parseStartTag() { if ((readItem < 'a' || readItem > 'z') && (readItem < 'A' || readItem > 'Z')) { //不合法的开始标签 return; } //read name bufPos = 0; do { if (readItem >= 'A' && readItem <= 'Z') { readItem = (char) (readItem + 'a' - 'A'); } buf[bufPos++] = readItem; read(); } while (readItem != EOF && bufPos < MAX_TAG_LEN && ((readItem >= 'a' && readItem <= 'z') || (readItem >= 'A' && readItem <= 'Z') || (readItem >= '0' && readItem <= '9'))); String name = new String(buf, 0, bufPos); int type = getTagType(); bufPos = 0; if (readItem == '/') { read(); } if (readItem != '>') { if (readItem == ' ' || readItem == '\n') { readNoSpcBr(); } if (readItem == '/') { read(); } if (readItem != '>') { parseAttr(); } } if (handler != null) { if (type == HtmlTag.PRE) { preLevel++; } //说明attr长度大于等于5为有效attr HtmlNode.HtmlAttr attr = null; if (bufPos >= 5) { attr = AttrParser.parserAttr(type, buf, bufPos); } HtmlNode n = new HtmlNode(type, name, attr); pushNode(n); cuurEleType = type; handler.startElement(n); } } //解析属性值 private void parseAttr() { bufPos = 0; do { buf[bufPos++] = readItem; read(); } while (readItem != EOF && readItem != '>' && bufPos < MAX_ATTR_LEN); if (buf[(bufPos - 1)] == '/') { bufPos--; } if (readItem != '>') { skip(); } } //解析结束标签</xxx > </xxx> </xxx\n > private void parseEndTag() { bufPos = 0; while (readItem != EOF && (readItem = readNoSpcBr()) != '>') { if (bufPos >= MAX_TAG_LEN) { //不可能出现太长的tag break; } else { buf[bufPos++] = readItem; } } String s = new String(buf, 0, bufPos); int type = getTagType(); bufPos = 0; if (type == HtmlTag.PRE && preLevel > 0) { preLevel--; } popNode(type, s); handler.endElement(type, s); } //解析注释 private void parseComment() { while (readItem != EOF) { read(); read(); if (readItem == '-' && lastRead == '-') { read(); if (readItem == '>') { break; } } } } //解析文字 //处理转义 //&amp; "&" //&apos; "'" //&gt; ">" //&lt; "<" //&quot; "\" //&nbsp; ' ' private void parseText() { bufPos = 0; while (readItem != EOF && readItem != '<' && readItem != '>') { if (preLevel > 0 && bufPos > 0) {//pre 标签 原封不动push pushText(readItem); } else { //转义 if (readItem == '&') {//&nbsp; read(); if (readItem != EOF && readItem == 'n') { read(); if (readItem != EOF && readItem == 'b') { read(); if (readItem != EOF && readItem == 's') { read(); if (readItem != EOF && readItem == 'p') { read(); if (readItem != EOF && readItem == ';') { pushText(' '); //&nbsp; read(); continue;//强制空格 } else { pushText('&'); pushText('n'); pushText('b'); pushText('s'); pushText('p'); } } else { pushText('&'); pushText('n'); pushText('b'); pushText('s'); } } else { pushText('&'); pushText('n'); pushText('b'); } } else { pushText('&'); pushText('n'); } } else if (readItem != EOF && readItem == 'a') { //&amp; &apos; read(); if (readItem != EOF && readItem == 'm') {//&amp; read(); if (readItem != EOF && readItem == 'p') {//&amp; read(); if (readItem != EOF && readItem == ';') {//&amp; pushText('&'); //&nbsp; read(); continue; } else { pushText('&'); pushText('a'); pushText('m'); pushText('p'); } } else { pushText('&'); pushText('a'); pushText('m'); } } else if (readItem != EOF && readItem == 'p') {//&apos; read(); if (readItem != EOF && readItem == 'o') {//&apos; read(); if (readItem != EOF && readItem == 's') {//&apos; read(); if (readItem != EOF && readItem == ';') { pushText('\''); //&apos; read(); continue; } else { pushText('&'); pushText('a'); pushText('p'); pushText('o'); pushText('s'); } } else { pushText('&'); pushText('a'); pushText('p'); pushText('o'); } } else { pushText('&'); pushText('a'); pushText('p'); } } else { pushText('&'); pushText('a'); } } else if (readItem != EOF && readItem == 'g') {//&gt; read(); if (readItem != EOF && readItem == 't') { read(); if (readItem != EOF && readItem == ';') { pushText('>'); //&gt; read(); continue; } else { pushText('&'); pushText('g'); pushText('t'); } } else { pushText('&'); pushText('g'); } } else if (readItem != EOF && readItem == 'l') {//&lt; read(); if (readItem != EOF && readItem == 't') { read(); if (readItem != EOF && readItem == ';') { pushText('<'); //&lt; read(); continue; } else { pushText('&'); pushText('l'); pushText('t'); } } else { pushText('&'); pushText('l'); } } else if (readItem != EOF && readItem == 'q') {//&quot; read(); if (readItem != EOF && readItem == 'u') { read(); if (readItem != EOF && readItem == 'o') { read(); if (readItem != EOF && readItem == 't') { read(); if (readItem != EOF && readItem == ';') { pushText('\\'); //&nbsp; read(); continue; } else { pushText('&'); pushText('q'); pushText('u'); pushText('o'); pushText('t'); } } else { pushText('&'); pushText('q'); pushText('u'); pushText('o'); } } else { pushText('&'); pushText('q'); pushText('u'); } } else { pushText('&'); pushText('q'); } } else { pushText('&'); } } if (readItem == ' ' || readItem == '\n') { if (bufPos != 0 && buf[(bufPos - 1)] != ' ') { readItem = ' '; pushText(readItem); } } else { pushText(readItem); } } read(); } //不是空 if (bufPos > 0 && handler != null) { handler.characters(buf, 0, bufPos); } } //处理解析完成 private void handleStop() { while (!stack.isEmpty()) { HtmlNode n = stack.pop(); handler.endElement(n.type, n.name); } readItem = EOF; handler.endDocument(); } //读取一个字符 private char read() { lastRead = readItem; if (srcPos < srcCount) { readItem = srcBuf[srcPos++]; } else { if (reader == null) { readItem = EOF; } else { try { srcCount = reader.read(srcBuf, 0, srcBuf.length); } catch (IOException e) { e.printStackTrace(); readItem = EOF; } if (srcCount <= 0) { readItem = EOF; } else { readItem = srcBuf[0]; } srcPos = 1; } } switch (readItem) { case EOF: handleStop(); break; case '\r': read(); break; default: break; } return readItem; } //忽略读入的空格和回车 private char readNoSpcBr() { while (readItem != EOF) { read(); if (readItem != '\n' && readItem != ' ') { return readItem; } } return EOF; } //skip to next > or EOF private void skip() { while (readItem != EOF && readItem != '>') { read(); } } //加入一个新的文字 private void pushText(int c) { if (bufPos == buf.length) { char[] bigger = new char[bufPos * 4 / 3 + 4]; System.arraycopy(buf, 0, bigger, 0, bufPos); buf = bigger; } buf[bufPos++] = (char) c; } private boolean equalTag(int start, String b) { int len = b.length(); while (len-- != 0) { if (buf[start] != b.charAt(start)) { return false; } start++; } return true; } private int getTagType() { switch (bufPos) { case 1: switch (buf[0]) { case 'a': return HtmlTag.A; case 'b': return HtmlTag.B; case 'i': return HtmlTag.I; case 'p': return HtmlTag.P; case 'q': return HtmlTag.Q; case 's': return HtmlTag.S; case 'u': return HtmlTag.U; default: Log.w(getClass().getName(), "unknown tag type: " + buf); break; } break; case 2: switch (buf[0]) { case 'b': if (buf[1] == 'r') { return HtmlTag.BR; } break; case 'e': if (buf[1] == 'm') { return HtmlTag.EM; } break; case 'h': if ('1' <= buf[1] && buf[1] <= '6') { return (buf[1] - '1') + HtmlTag.H1; } else if (buf[1] == 'r') { return HtmlTag.HR; } break; case 'l': if (buf[1] == 'i') { return HtmlTag.LI; } break; case 'o': if (buf[1] == 'l') { return HtmlTag.OL; } break; case 't': if (buf[1] == 'd') { return HtmlTag.TD; } else if (buf[1] == 'h') { return HtmlTag.TH; } else if (buf[1] == 'r') { return HtmlTag.TR; } else if (buf[1] == 't') { return HtmlTag.TT; } break; case 'u': if (buf[1] == 'l') { return HtmlTag.UL; } break; default: return HtmlTag.UNKNOWN; } break; case 3: switch (buf[0]) { case 'b': if (buf[1] == 'i' && buf[2] == 'g') { return HtmlTag.BIG; } break; case 'd': if (buf[1] == 'e' && buf[2] == 'l') { return HtmlTag.DEL; } else if (buf[1] == 'f' && buf[2] == 'n') { return HtmlTag.DFN; } else if (buf[1] == 'i' && buf[2] == 'v') { return HtmlTag.DIV; } break; case 'i': if (buf[1] == 'm' && buf[2] == 'g') { return HtmlTag.IMG; } else if (buf[1] == 'n' && buf[2] == 's') { return HtmlTag.INS; } break; case 'k': if (buf[1] == 'b' && buf[2] == 'd') { return HtmlTag.KBD; } break; case 'p': if (buf[1] == 'r') { if (buf[2] == 'e') { return HtmlTag.PRE; } } break; case 's': if (buf[1] == 'u') { if (buf[2] == 'b') { return HtmlTag.SUB; } else if (buf[2] == 'p') { return HtmlTag.SUP; } } break; default: return HtmlTag.UNKNOWN; } break; case 4: switch (buf[0]) { case 'c': if (buf[1] == 'i' && buf[2] == 't' && buf[3] == 'e') { return HtmlTag.CITE; } else if (buf[1] == 'o' && buf[2] == 'd' && buf[3] == 'e') { return HtmlTag.CODE; } break; case 'f': if (buf[1] == 'o' && buf[2] == 'n' && buf[3] == 't') { return HtmlTag.FONT; } break; case 's': if (buf[1] == 'p' && buf[2] == 'a' && buf[3] == 'n') { return HtmlTag.SPAN; } break; case 'm': if (buf[1] == 'a' && buf[2] == 'r' && buf[3] == 'k') { return HtmlTag.MARK; } break; default: return HtmlTag.UNKNOWN; } break; case 5: switch (buf[0]) { case 's': if (equalTag(1, "mall")) { return HtmlTag.SMALL; } break; case 't': if (equalTag(1, "able")) { return HtmlTag.TABLE; } else if (equalTag(1, "body")) { return HtmlTag.TBODY; } else if (equalTag(1, "head")) { return HtmlTag.THEAD; } else if (equalTag(1, "foot")) { return HtmlTag.TFOOT; } break; case 'a': if (equalTag(1, "udio")) { return HtmlTag.AUDIO; } break; case 'v': if (equalTag(1, "edio")) { return HtmlTag.VEDIO; } break; default: return HtmlTag.UNKNOWN; } break; case 6: if (equalTag(0, "str")) { if (buf[3] == 'o' && buf[4] == 'n' && buf[5] == 'g') { return HtmlTag.STRONG; } else if (buf[3] == 'i' && buf[4] == 'k' && buf[5] == 'e') { return HtmlTag.STRIKE; } } else if (buf[4] == 'e' && buf[5] == 'f') { if (buf[0] == 'h' && buf[1] == 'e' && buf[2] == 'a' && buf[3] == 'd') { return HtmlTag.HEADER; } else if (buf[0] == 'f' && buf[1] == 'o' && buf[2] == 'o' && buf[3] == 't') { return HtmlTag.FOOTER; } } break; case 7: if (equalTag(0, "caption")) { return HtmlTag.CAPTION; } break; case 10: if (equalTag(0, "blockquote")) { return HtmlTag.BLOCKQUOTE; } break; default: return HtmlTag.UNKNOWN; } return HtmlTag.UNKNOWN; } //压栈node到stack 更新节点属性 private void pushNode(HtmlNode node) { //单标签不压栈,且属性也不继承 if (node.type == HtmlTag.IMG || node.type == HtmlTag.BR || node.type == HtmlTag.HR) { return; } HtmlNode.HtmlAttr parentAttr; if (!stack.isEmpty() && (parentAttr = stack.peek().attr) != null) { if (node.attr == null) { node.attr = parentAttr; } else { //字体颜色继承 if (node.attr.color == AttrParser.COLOR_NONE) { node.attr.color = parentAttr.color; } // textDecoration 是否需要集成? if (node.attr.textDecoration == HtmlNode.DEC_NONE) { node.attr.textDecoration = parentAttr.textDecoration; } } } //压栈 stack.push(node); } private void popNode(int type, String name) { //这些节点不在栈 if (type == HtmlTag.IMG || type == HtmlTag.BR || type == HtmlTag.HR) { return; } HtmlNode n; if (!stack.isEmpty() && (n = stack.peek()) != null) { //栈顶元素相同出栈 if (n.type == type && Objects.equals(n.name, name)) { stack.pop(); } else {//不相同 是出还是不出??? int i = stack.size() - 1; for (; i > 0; i--) { if (stack.get(i).type == type && Objects.equals(stack.get(i).name, name)) { break; } } //栈里有 一直出栈 if (i > 0) { int j = stack.size() - 1; while (j != i - 1) { stack.pop(); j--; } } } } } }
35374_5
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.core; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.gui.GUIPositionInterface; import org.pentaho.di.core.gui.GUISizeInterface; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.core.xml.XMLInterface; import org.pentaho.di.repository.ObjectId; import org.w3c.dom.Node; /** * Describes a note displayed on a Transformation, Job, Schema, or Report. * * @author Matt * @since 28-11-2003 * */ public class NotePadMeta implements Cloneable, XMLInterface, GUIPositionInterface, GUISizeInterface { public static final String XML_TAG = "notepad"; public static final int COLOR_RGB_BLACK_RED = 0; public static final int COLOR_RGB_BLACK_GREEN = 0; public static final int COLOR_RGB_BLACK_BLUE = 0; public static final int COLOR_RGB_DEFAULT_BG_RED = 255; public static final int COLOR_RGB_DEFAULT_BG_GREEN = 205; public static final int COLOR_RGB_DEFAULT_BG_BLUE = 112; public static final int COLOR_RGB_DEFAULT_BORDER_RED = 100; public static final int COLOR_RGB_DEFAULT_BORDER_GREEN = 100; public static final int COLOR_RGB_DEFAULT_BORDER_BLUE = 100; private String note; private String fontname; private int fontsize; private boolean fontbold; private boolean fontitalic; private int fontcolorred; private int fontcolorgreen; private int fontcolorblue; private int backgroundcolorred; private int backgroundcolorgreen; private int backgroundcolorblue; private int bordercolorred; private int bordercolorgreen; private int bordercolorblue; private boolean drawshadow; private Point location; public int width, height; private boolean selected; private boolean changed; private ObjectId id; public NotePadMeta() { note = null; location = new Point( -1, -1 ); width = -1; height = -1; selected = false; setDefaultFont(); backgroundcolorred = 0xFF; backgroundcolorgreen = 0xA5; backgroundcolorblue = 0x00; } public NotePadMeta( String n, int xl, int yl, int w, int h ) { note = n; location = new Point( xl, yl ); width = w; height = h; selected = false; setDefaultFont(); } public NotePadMeta( String n, int xl, int yl, int w, int h, String fontname, int fontsize, boolean fontbold, boolean fontitalic, int fontColorRed, int fontColorGreen, int fontColorBlue, int backGrounColorRed, int backGrounColorGreen, int backGrounColorBlue, int borderColorRed, int borderColorGreen, int borderColorBlue, boolean drawshadow ) { this.note = n; this.location = new Point( xl, yl ); this.width = w; this.height = h; this.selected = false; this.fontname = fontname; this.fontsize = fontsize; this.fontbold = fontbold; this.fontitalic = fontitalic; // font color this.fontcolorred = fontColorRed; this.fontcolorgreen = fontColorGreen; this.fontcolorblue = fontColorBlue; // background color this.backgroundcolorred = backGrounColorRed; this.backgroundcolorgreen = backGrounColorGreen; this.backgroundcolorblue = backGrounColorBlue; // border color this.bordercolorred = borderColorRed; this.bordercolorgreen = borderColorGreen; this.bordercolorblue = borderColorBlue; this.drawshadow = drawshadow; } public NotePadMeta( Node notepadnode ) throws KettleXMLException { try { note = XMLHandler.getTagValue( notepadnode, "note" ); String sxloc = XMLHandler.getTagValue( notepadnode, "xloc" ); String syloc = XMLHandler.getTagValue( notepadnode, "yloc" ); String swidth = XMLHandler.getTagValue( notepadnode, "width" ); String sheight = XMLHandler.getTagValue( notepadnode, "heigth" ); int x = Const.toInt( sxloc, 0 ); int y = Const.toInt( syloc, 0 ); this.location = new Point( x, y ); this.width = Const.toInt( swidth, 0 ); this.height = Const.toInt( sheight, 0 ); this.selected = false; this.fontname = XMLHandler.getTagValue( notepadnode, "fontname" ); this.fontsize = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontsize" ), -1 ); this.fontbold = "Y".equalsIgnoreCase( XMLHandler.getTagValue( notepadnode, "fontbold" ) ); this.fontitalic = "Y".equalsIgnoreCase( XMLHandler.getTagValue( notepadnode, "fontitalic" ) ); // font color this.fontcolorred = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontcolorred" ), COLOR_RGB_BLACK_RED ); this.fontcolorgreen = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontcolorgreen" ), COLOR_RGB_BLACK_GREEN ); this.fontcolorblue = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontcolorblue" ), COLOR_RGB_BLACK_BLUE ); // background color this.backgroundcolorred = Const.toInt( XMLHandler.getTagValue( notepadnode, "backgroundcolorred" ), COLOR_RGB_DEFAULT_BG_RED ); this.backgroundcolorgreen = Const.toInt( XMLHandler.getTagValue( notepadnode, "backgroundcolorgreen" ), COLOR_RGB_DEFAULT_BG_GREEN ); this.backgroundcolorblue = Const.toInt( XMLHandler.getTagValue( notepadnode, "backgroundcolorblue" ), COLOR_RGB_DEFAULT_BG_BLUE ); // border color this.bordercolorred = Const.toInt( XMLHandler.getTagValue( notepadnode, "bordercolorred" ), COLOR_RGB_DEFAULT_BORDER_RED ); this.bordercolorgreen = Const.toInt( XMLHandler.getTagValue( notepadnode, "bordercolorgreen" ), COLOR_RGB_DEFAULT_BORDER_GREEN ); this.bordercolorblue = Const.toInt( XMLHandler.getTagValue( notepadnode, "bordercolorblue" ), COLOR_RGB_DEFAULT_BORDER_BLUE ); this.drawshadow = "Y".equalsIgnoreCase( XMLHandler.getTagValue( notepadnode, "drawshadow" ) ); } catch ( Exception e ) { throw new KettleXMLException( "Unable to read Notepad info from XML", e ); } } public ObjectId getObjectId() { return id; } public void setObjectId( ObjectId id ) { this.id = id; } public void setLocation( int x, int y ) { if ( x != location.x || y != location.y ) { setChanged(); } location.x = x; location.y = y; } public void setLocation( Point p ) { setLocation( p.x, p.y ); } public Point getLocation() { return location; } /** * @return Returns the note. */ public String getNote() { return this.note; } /** * @param note * The note to set. */ public void setNote( String note ) { this.note = note; } /** * @param green * the border red color. */ public void setBorderColorRed( int red ) { this.bordercolorred = red; } /** * @param green * the border color green. */ public void setBorderColorGreen( int green ) { this.bordercolorgreen = green; } /** * @param green * the border blue color. */ public void setBorderColorBlue( int blue ) { this.bordercolorblue = blue; } /** * @parm red the backGround red color. */ public void setBackGroundColorRed( int red ) { this.backgroundcolorred = red; } /** * @parm green the backGround green color. */ public void setBackGroundColorGreen( int green ) { this.backgroundcolorgreen = green; } /** * @parm green the backGround blue color. */ public void setBackGroundColorBlue( int blue ) { this.backgroundcolorblue = blue; } /** * @param Returns * the font color red. */ public void setFontColorRed( int red ) { this.fontcolorred = red; } /** * @param Returns * the font color green. */ public void setFontColorGreen( int green ) { this.fontcolorgreen = green; } /** * @param Returns * the font color blue. */ public void setFontColorBlue( int blue ) { this.fontcolorblue = blue; } /** * @return Returns the selected. */ public boolean isSelected() { return selected; } /** * @param selected * The selected to set. */ public void setSelected( boolean selected ) { this.selected = selected; } /** * Change a selected state to not-selected and vice-versa. */ public void flipSelected() { this.selected = !this.selected; } /** * @param drawshadow * The drawshadow to set. */ public void setDrawShadow( boolean drawshadow ) { this.drawshadow = drawshadow; } /** * Change a drawshadow state */ public boolean isDrawShadow() { return this.drawshadow; } public Object clone() { try { Object retval = super.clone(); return retval; } catch ( CloneNotSupportedException e ) { return null; } } public void setChanged() { setChanged( true ); } public void setChanged( boolean ch ) { changed = ch; } public boolean hasChanged() { return changed; } public String toString() { return note; } public String getXML() { StringBuilder retval = new StringBuilder( 100 ); retval.append( " <notepad>" ).append( Const.CR ); retval.append( " " ).append( XMLHandler.addTagValue( "note", note ) ); retval.append( " " ).append( XMLHandler.addTagValue( "xloc", location.x ) ); retval.append( " " ).append( XMLHandler.addTagValue( "yloc", location.y ) ); retval.append( " " ).append( XMLHandler.addTagValue( "width", width ) ); retval.append( " " ).append( XMLHandler.addTagValue( "heigth", height ) ); // Font retval.append( " " ).append( XMLHandler.addTagValue( "fontname", fontname ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontsize", fontsize ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontbold", fontbold ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontitalic", fontitalic ) ); // Font color retval.append( " " ).append( XMLHandler.addTagValue( "fontcolorred", fontcolorred ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontcolorgreen", fontcolorgreen ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontcolorblue", fontcolorblue ) ); // Background color retval.append( " " ).append( XMLHandler.addTagValue( "backgroundcolorred", backgroundcolorred ) ); retval.append( " " ).append( XMLHandler.addTagValue( "backgroundcolorgreen", backgroundcolorgreen ) ); retval.append( " " ).append( XMLHandler.addTagValue( "backgroundcolorblue", backgroundcolorblue ) ); // border color retval.append( " " ).append( XMLHandler.addTagValue( "bordercolorred", bordercolorred ) ); retval.append( " " ).append( XMLHandler.addTagValue( "bordercolorgreen", bordercolorgreen ) ); retval.append( " " ).append( XMLHandler.addTagValue( "bordercolorblue", bordercolorblue ) ); // draw shadow retval.append( " " ).append( XMLHandler.addTagValue( "drawshadow", drawshadow ) ); retval.append( " </notepad>" ).append( Const.CR ); return retval.toString(); } /** * @return the height */ public int getHeight() { return height; } /** * @param height * the height to set */ public void setHeight( int height ) { this.height = height; } /** * @return the width */ public int getWidth() { return width; } /** * @param width * the width to set */ public void setWidth( int width ) { this.width = width; } /** * @return Returns the font name. */ public String getFontName() { return this.fontname; } /** * @param note * The font name. */ public void setFontName( String fontname ) { this.fontname = fontname; } /** * @return Returns the font size. */ public int getFontSize() { return this.fontsize; } /** * @param note * The font bold. */ public void setFontBold( boolean fontbold ) { this.fontbold = fontbold; } /** * @return Returns the font bold. */ public boolean isFontBold() { return this.fontbold; } /** * @param note * The font italic. */ public void setFontItalic( boolean fontitalic ) { this.fontitalic = fontitalic; } /** * @return Returns the font italic. */ public boolean isFontItalic() { return this.fontitalic; } /** * @return Returns the backGround color red. */ public int getBorderColorRed() { return this.bordercolorred; } /** * @return Returns the backGround color green. */ public int getBorderColorGreen() { return this.bordercolorgreen; } /** * @return Returns the backGround color blue. */ public int getBorderColorBlue() { return this.bordercolorblue; } /** * @return Returns the backGround color red. */ public int getBackGroundColorRed() { return this.backgroundcolorred; } /** * @return Returns the backGround color green. */ public int getBackGroundColorGreen() { return this.backgroundcolorgreen; } /** * @return Returns the backGround color blue. */ public int getBackGroundColorBlue() { return this.backgroundcolorblue; } /** * @return Returns the font color red. */ public int getFontColorRed() { return this.fontcolorred; } /** * @return Returns the font color green. */ public int getFontColorGreen() { return this.fontcolorgreen; } /** * @return Returns the font color blue. */ public int getFontColorBlue() { return this.fontcolorblue; } /** * @param note * The font name. */ public void setFontSize( int fontsize ) { this.fontsize = fontsize; } private void setDefaultFont() { this.fontname = null; this.fontsize = -1; this.fontbold = false; this.fontitalic = false; // font color black this.fontcolorred = COLOR_RGB_BLACK_RED; this.fontcolorgreen = COLOR_RGB_BLACK_GREEN; this.fontcolorblue = COLOR_RGB_BLACK_BLUE; // background yellow this.backgroundcolorred = COLOR_RGB_DEFAULT_BG_RED; this.backgroundcolorgreen = COLOR_RGB_DEFAULT_BG_GREEN; this.backgroundcolorblue = COLOR_RGB_DEFAULT_BG_BLUE; // border gray this.bordercolorred = COLOR_RGB_DEFAULT_BORDER_RED; this.bordercolorgreen = COLOR_RGB_DEFAULT_BORDER_GREEN; this.bordercolorblue = COLOR_RGB_DEFAULT_BORDER_BLUE; this.drawshadow = true; } }
xiong305817127/CloudETL
cloudetl/idatrix-cloudetl-engine/src/main/java/org/pentaho/di/core/NotePadMeta.java
4,975
/** * @param green * the border color green. */
block_comment
nl
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.core; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.gui.GUIPositionInterface; import org.pentaho.di.core.gui.GUISizeInterface; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.core.xml.XMLInterface; import org.pentaho.di.repository.ObjectId; import org.w3c.dom.Node; /** * Describes a note displayed on a Transformation, Job, Schema, or Report. * * @author Matt * @since 28-11-2003 * */ public class NotePadMeta implements Cloneable, XMLInterface, GUIPositionInterface, GUISizeInterface { public static final String XML_TAG = "notepad"; public static final int COLOR_RGB_BLACK_RED = 0; public static final int COLOR_RGB_BLACK_GREEN = 0; public static final int COLOR_RGB_BLACK_BLUE = 0; public static final int COLOR_RGB_DEFAULT_BG_RED = 255; public static final int COLOR_RGB_DEFAULT_BG_GREEN = 205; public static final int COLOR_RGB_DEFAULT_BG_BLUE = 112; public static final int COLOR_RGB_DEFAULT_BORDER_RED = 100; public static final int COLOR_RGB_DEFAULT_BORDER_GREEN = 100; public static final int COLOR_RGB_DEFAULT_BORDER_BLUE = 100; private String note; private String fontname; private int fontsize; private boolean fontbold; private boolean fontitalic; private int fontcolorred; private int fontcolorgreen; private int fontcolorblue; private int backgroundcolorred; private int backgroundcolorgreen; private int backgroundcolorblue; private int bordercolorred; private int bordercolorgreen; private int bordercolorblue; private boolean drawshadow; private Point location; public int width, height; private boolean selected; private boolean changed; private ObjectId id; public NotePadMeta() { note = null; location = new Point( -1, -1 ); width = -1; height = -1; selected = false; setDefaultFont(); backgroundcolorred = 0xFF; backgroundcolorgreen = 0xA5; backgroundcolorblue = 0x00; } public NotePadMeta( String n, int xl, int yl, int w, int h ) { note = n; location = new Point( xl, yl ); width = w; height = h; selected = false; setDefaultFont(); } public NotePadMeta( String n, int xl, int yl, int w, int h, String fontname, int fontsize, boolean fontbold, boolean fontitalic, int fontColorRed, int fontColorGreen, int fontColorBlue, int backGrounColorRed, int backGrounColorGreen, int backGrounColorBlue, int borderColorRed, int borderColorGreen, int borderColorBlue, boolean drawshadow ) { this.note = n; this.location = new Point( xl, yl ); this.width = w; this.height = h; this.selected = false; this.fontname = fontname; this.fontsize = fontsize; this.fontbold = fontbold; this.fontitalic = fontitalic; // font color this.fontcolorred = fontColorRed; this.fontcolorgreen = fontColorGreen; this.fontcolorblue = fontColorBlue; // background color this.backgroundcolorred = backGrounColorRed; this.backgroundcolorgreen = backGrounColorGreen; this.backgroundcolorblue = backGrounColorBlue; // border color this.bordercolorred = borderColorRed; this.bordercolorgreen = borderColorGreen; this.bordercolorblue = borderColorBlue; this.drawshadow = drawshadow; } public NotePadMeta( Node notepadnode ) throws KettleXMLException { try { note = XMLHandler.getTagValue( notepadnode, "note" ); String sxloc = XMLHandler.getTagValue( notepadnode, "xloc" ); String syloc = XMLHandler.getTagValue( notepadnode, "yloc" ); String swidth = XMLHandler.getTagValue( notepadnode, "width" ); String sheight = XMLHandler.getTagValue( notepadnode, "heigth" ); int x = Const.toInt( sxloc, 0 ); int y = Const.toInt( syloc, 0 ); this.location = new Point( x, y ); this.width = Const.toInt( swidth, 0 ); this.height = Const.toInt( sheight, 0 ); this.selected = false; this.fontname = XMLHandler.getTagValue( notepadnode, "fontname" ); this.fontsize = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontsize" ), -1 ); this.fontbold = "Y".equalsIgnoreCase( XMLHandler.getTagValue( notepadnode, "fontbold" ) ); this.fontitalic = "Y".equalsIgnoreCase( XMLHandler.getTagValue( notepadnode, "fontitalic" ) ); // font color this.fontcolorred = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontcolorred" ), COLOR_RGB_BLACK_RED ); this.fontcolorgreen = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontcolorgreen" ), COLOR_RGB_BLACK_GREEN ); this.fontcolorblue = Const.toInt( XMLHandler.getTagValue( notepadnode, "fontcolorblue" ), COLOR_RGB_BLACK_BLUE ); // background color this.backgroundcolorred = Const.toInt( XMLHandler.getTagValue( notepadnode, "backgroundcolorred" ), COLOR_RGB_DEFAULT_BG_RED ); this.backgroundcolorgreen = Const.toInt( XMLHandler.getTagValue( notepadnode, "backgroundcolorgreen" ), COLOR_RGB_DEFAULT_BG_GREEN ); this.backgroundcolorblue = Const.toInt( XMLHandler.getTagValue( notepadnode, "backgroundcolorblue" ), COLOR_RGB_DEFAULT_BG_BLUE ); // border color this.bordercolorred = Const.toInt( XMLHandler.getTagValue( notepadnode, "bordercolorred" ), COLOR_RGB_DEFAULT_BORDER_RED ); this.bordercolorgreen = Const.toInt( XMLHandler.getTagValue( notepadnode, "bordercolorgreen" ), COLOR_RGB_DEFAULT_BORDER_GREEN ); this.bordercolorblue = Const.toInt( XMLHandler.getTagValue( notepadnode, "bordercolorblue" ), COLOR_RGB_DEFAULT_BORDER_BLUE ); this.drawshadow = "Y".equalsIgnoreCase( XMLHandler.getTagValue( notepadnode, "drawshadow" ) ); } catch ( Exception e ) { throw new KettleXMLException( "Unable to read Notepad info from XML", e ); } } public ObjectId getObjectId() { return id; } public void setObjectId( ObjectId id ) { this.id = id; } public void setLocation( int x, int y ) { if ( x != location.x || y != location.y ) { setChanged(); } location.x = x; location.y = y; } public void setLocation( Point p ) { setLocation( p.x, p.y ); } public Point getLocation() { return location; } /** * @return Returns the note. */ public String getNote() { return this.note; } /** * @param note * The note to set. */ public void setNote( String note ) { this.note = note; } /** * @param green * the border red color. */ public void setBorderColorRed( int red ) { this.bordercolorred = red; } /** * @param green <SUF>*/ public void setBorderColorGreen( int green ) { this.bordercolorgreen = green; } /** * @param green * the border blue color. */ public void setBorderColorBlue( int blue ) { this.bordercolorblue = blue; } /** * @parm red the backGround red color. */ public void setBackGroundColorRed( int red ) { this.backgroundcolorred = red; } /** * @parm green the backGround green color. */ public void setBackGroundColorGreen( int green ) { this.backgroundcolorgreen = green; } /** * @parm green the backGround blue color. */ public void setBackGroundColorBlue( int blue ) { this.backgroundcolorblue = blue; } /** * @param Returns * the font color red. */ public void setFontColorRed( int red ) { this.fontcolorred = red; } /** * @param Returns * the font color green. */ public void setFontColorGreen( int green ) { this.fontcolorgreen = green; } /** * @param Returns * the font color blue. */ public void setFontColorBlue( int blue ) { this.fontcolorblue = blue; } /** * @return Returns the selected. */ public boolean isSelected() { return selected; } /** * @param selected * The selected to set. */ public void setSelected( boolean selected ) { this.selected = selected; } /** * Change a selected state to not-selected and vice-versa. */ public void flipSelected() { this.selected = !this.selected; } /** * @param drawshadow * The drawshadow to set. */ public void setDrawShadow( boolean drawshadow ) { this.drawshadow = drawshadow; } /** * Change a drawshadow state */ public boolean isDrawShadow() { return this.drawshadow; } public Object clone() { try { Object retval = super.clone(); return retval; } catch ( CloneNotSupportedException e ) { return null; } } public void setChanged() { setChanged( true ); } public void setChanged( boolean ch ) { changed = ch; } public boolean hasChanged() { return changed; } public String toString() { return note; } public String getXML() { StringBuilder retval = new StringBuilder( 100 ); retval.append( " <notepad>" ).append( Const.CR ); retval.append( " " ).append( XMLHandler.addTagValue( "note", note ) ); retval.append( " " ).append( XMLHandler.addTagValue( "xloc", location.x ) ); retval.append( " " ).append( XMLHandler.addTagValue( "yloc", location.y ) ); retval.append( " " ).append( XMLHandler.addTagValue( "width", width ) ); retval.append( " " ).append( XMLHandler.addTagValue( "heigth", height ) ); // Font retval.append( " " ).append( XMLHandler.addTagValue( "fontname", fontname ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontsize", fontsize ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontbold", fontbold ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontitalic", fontitalic ) ); // Font color retval.append( " " ).append( XMLHandler.addTagValue( "fontcolorred", fontcolorred ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontcolorgreen", fontcolorgreen ) ); retval.append( " " ).append( XMLHandler.addTagValue( "fontcolorblue", fontcolorblue ) ); // Background color retval.append( " " ).append( XMLHandler.addTagValue( "backgroundcolorred", backgroundcolorred ) ); retval.append( " " ).append( XMLHandler.addTagValue( "backgroundcolorgreen", backgroundcolorgreen ) ); retval.append( " " ).append( XMLHandler.addTagValue( "backgroundcolorblue", backgroundcolorblue ) ); // border color retval.append( " " ).append( XMLHandler.addTagValue( "bordercolorred", bordercolorred ) ); retval.append( " " ).append( XMLHandler.addTagValue( "bordercolorgreen", bordercolorgreen ) ); retval.append( " " ).append( XMLHandler.addTagValue( "bordercolorblue", bordercolorblue ) ); // draw shadow retval.append( " " ).append( XMLHandler.addTagValue( "drawshadow", drawshadow ) ); retval.append( " </notepad>" ).append( Const.CR ); return retval.toString(); } /** * @return the height */ public int getHeight() { return height; } /** * @param height * the height to set */ public void setHeight( int height ) { this.height = height; } /** * @return the width */ public int getWidth() { return width; } /** * @param width * the width to set */ public void setWidth( int width ) { this.width = width; } /** * @return Returns the font name. */ public String getFontName() { return this.fontname; } /** * @param note * The font name. */ public void setFontName( String fontname ) { this.fontname = fontname; } /** * @return Returns the font size. */ public int getFontSize() { return this.fontsize; } /** * @param note * The font bold. */ public void setFontBold( boolean fontbold ) { this.fontbold = fontbold; } /** * @return Returns the font bold. */ public boolean isFontBold() { return this.fontbold; } /** * @param note * The font italic. */ public void setFontItalic( boolean fontitalic ) { this.fontitalic = fontitalic; } /** * @return Returns the font italic. */ public boolean isFontItalic() { return this.fontitalic; } /** * @return Returns the backGround color red. */ public int getBorderColorRed() { return this.bordercolorred; } /** * @return Returns the backGround color green. */ public int getBorderColorGreen() { return this.bordercolorgreen; } /** * @return Returns the backGround color blue. */ public int getBorderColorBlue() { return this.bordercolorblue; } /** * @return Returns the backGround color red. */ public int getBackGroundColorRed() { return this.backgroundcolorred; } /** * @return Returns the backGround color green. */ public int getBackGroundColorGreen() { return this.backgroundcolorgreen; } /** * @return Returns the backGround color blue. */ public int getBackGroundColorBlue() { return this.backgroundcolorblue; } /** * @return Returns the font color red. */ public int getFontColorRed() { return this.fontcolorred; } /** * @return Returns the font color green. */ public int getFontColorGreen() { return this.fontcolorgreen; } /** * @return Returns the font color blue. */ public int getFontColorBlue() { return this.fontcolorblue; } /** * @param note * The font name. */ public void setFontSize( int fontsize ) { this.fontsize = fontsize; } private void setDefaultFont() { this.fontname = null; this.fontsize = -1; this.fontbold = false; this.fontitalic = false; // font color black this.fontcolorred = COLOR_RGB_BLACK_RED; this.fontcolorgreen = COLOR_RGB_BLACK_GREEN; this.fontcolorblue = COLOR_RGB_BLACK_BLUE; // background yellow this.backgroundcolorred = COLOR_RGB_DEFAULT_BG_RED; this.backgroundcolorgreen = COLOR_RGB_DEFAULT_BG_GREEN; this.backgroundcolorblue = COLOR_RGB_DEFAULT_BG_BLUE; // border gray this.bordercolorred = COLOR_RGB_DEFAULT_BORDER_RED; this.bordercolorgreen = COLOR_RGB_DEFAULT_BORDER_GREEN; this.bordercolorblue = COLOR_RGB_DEFAULT_BORDER_BLUE; this.drawshadow = true; } }
189087_1
// Copyright (c) 2013-2024 xipki. All rights reserved. // License Apache License 2.0 package org.xipki.ca.server; import java.math.BigInteger; import java.security.SecureRandom; /** * Random serial number generator. * * @author Lijun Liao (xipki) * @since 2.0.0 */ class RandomSerialNumberGenerator { private static RandomSerialNumberGenerator instance; private final SecureRandom random; private RandomSerialNumberGenerator() { this.random = new SecureRandom(); } /** * Generate the next serial number. * @param byteLen byte length of the serial number. * @return the serial number. */ public BigInteger nextSerialNumber(int byteLen) { final byte[] rndBytes = new byte[byteLen]; random.nextBytes(rndBytes); // clear the highest bit. rndBytes[0] &= 0x7F; // set the second-highest bit rndBytes[0] |= 0x40; return new BigInteger(rndBytes); } // method nextSerialNumber public static synchronized RandomSerialNumberGenerator getInstance() { if (instance == null) { instance = new RandomSerialNumberGenerator(); } return instance; } // method RandomSerialNumberGenerator }
xipki/xipki
ca-server/src/main/java/org/xipki/ca/server/RandomSerialNumberGenerator.java
344
// License Apache License 2.0
line_comment
nl
// Copyright (c) 2013-2024 xipki. All rights reserved. // License Apache<SUF> package org.xipki.ca.server; import java.math.BigInteger; import java.security.SecureRandom; /** * Random serial number generator. * * @author Lijun Liao (xipki) * @since 2.0.0 */ class RandomSerialNumberGenerator { private static RandomSerialNumberGenerator instance; private final SecureRandom random; private RandomSerialNumberGenerator() { this.random = new SecureRandom(); } /** * Generate the next serial number. * @param byteLen byte length of the serial number. * @return the serial number. */ public BigInteger nextSerialNumber(int byteLen) { final byte[] rndBytes = new byte[byteLen]; random.nextBytes(rndBytes); // clear the highest bit. rndBytes[0] &= 0x7F; // set the second-highest bit rndBytes[0] |= 0x40; return new BigInteger(rndBytes); } // method nextSerialNumber public static synchronized RandomSerialNumberGenerator getInstance() { if (instance == null) { instance = new RandomSerialNumberGenerator(); } return instance; } // method RandomSerialNumberGenerator }
206940_16
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between filenamelist GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne op lijst " + curListIndex); // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou de index zijn op " + targetListIndex); //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
xorgate/TabSwitcherExtreme
src/org/intellij/ideaplugins/tabswitcherextreme/ListManager.java
4,874
//Utils.log("we zittne op lijst " + curListIndex);
line_comment
nl
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between filenamelist GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne<SUF> // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou de index zijn op " + targetListIndex); //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
25968_17
/** * Copyright (C) 2004-2009 Jive Software. 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.xmpp.resultsetmanagement; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.List; import java.util.Map; import net.jcip.annotations.NotThreadSafe; /** * A result set representation as described in XEP-0059. Note that this result * 'set' actually makes use of a List implementations, as the Java Set * definition disallows duplicate elements, while the List definition supplies * most of the required indexing operations. * * This ResultSet implementation loads all all results from the set into memory, * which might be undesirable for very large sets, or for sets where the * retrieval of a result is an expensive operation. sets. * * As most methods are backed by the {@link List#subList(int, int)} method, * non-structural changes in the returned lists are reflected in the ResultSet, * and vice-versa. * * @author Guus der Kinderen, [email protected] * * @param <E> * Each result set should be a collection of instances of the exact * same class. This class must implement the {@link Result} * interface. * @see java.util.List#subList(int, int) * */ /* * TODO: do we want changes to the returned Lists of methods in this class be * applied to the content of the ResultSet itself? Currently, because of the * usage of java.util.List#subList(int, int), it does. I'm thinking a * immodifiable solution would cause less problems. -Guus */ @NotThreadSafe public class ResultSetImpl<E extends Result> extends ResultSet<E> { /** * A list of all results in this ResultSet */ public final List<E> resultList; /** * A mapping of the UIDs of all results in resultList, to the index of those * entries in that list. */ public final Map<String, Integer> uidToIndex; /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is the same * order in which {@link Collection#iterator()} iterates over the * collection. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. */ public ResultSetImpl(final Collection<E> results) { this(results, null); } /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is defined by * the supplied Comparator class. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. * @param comparator * The Comparator that defines the order of the Results in this * result set. */ public ResultSetImpl(final Collection<E> results, final Comparator<E> comparator) { if (results == null) throw new NullPointerException("Argument 'results' cannot be null."); final int size = results.size(); resultList = new ArrayList<E>(size); uidToIndex = new Hashtable<String, Integer>(size); // sort the collection, if need be. List<E> sortedResults = null; if (comparator != null) { sortedResults = new ArrayList<E>(results); Collections.sort(sortedResults, comparator); } int index = 0; // iterate over either the sorted or unsorted collection for (final E result : sortedResults != null ? sortedResults : results) { if (result == null) throw new NullPointerException("The result set must not contain 'null' elements."); final String uid = result.getUID(); if (uidToIndex.containsKey(uid)) throw new IllegalArgumentException("The result set can not contain elements that have the same UID."); resultList.add(result); uidToIndex.put(uid, index); index++; } } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#size() */ @Override public int size() { return resultList.size(); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getAfter(E, int) */ @Override public List<E> getAfter(final String uid, final int maxAmount) { if (uid == null || uid.length() == 0) throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); // the result of this method is exclusive 'result' final int index = uidToIndex.get(uid) + 1; return get(index, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getBefore(E, int) */ @Override public List<E> getBefore(final String uid, final int maxAmount) { if (uid == null || uid.length() == 0) throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); // the result of this method is exclusive 'result' final int indexOfLastElement = uidToIndex.get(uid); final int indexOfFirstElement = indexOfLastElement - maxAmount; if (indexOfFirstElement < 0) return get(0, indexOfLastElement); return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int) */ @Override public E get(final int index) { return resultList.get(index); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getFirst(int) */ @Override public List<E> getFirst(final int maxAmount) { if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); return get(0, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getLast(int) */ @Override public List<E> getLast(final int maxAmount) { if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); final int indexOfFirstElement = size() - maxAmount; if (indexOfFirstElement < 0) return get(0, maxAmount); return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int, int) */ @Override public List<E> get(final int fromIndex, final int maxAmount) { if (fromIndex < 0) throw new IllegalArgumentException("Argument 'fromIndex' must be zero or higher."); if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); if (fromIndex >= size()) return new ArrayList<E>(0); // calculate the last index to return, or return up to the end of last // index if 'amount' surpasses the list length. final int absoluteTo = fromIndex + maxAmount; final int toIndex = absoluteTo > size() ? size() : absoluteTo; return resultList.subList(fromIndex, toIndex); } /* * (non-Javadoc) * * @see * org.jivesoftware.util.resultsetmanager.ResultSet#indexOf(java.lang.String * ) */ @Override public int indexOf(final String uid) { return uidToIndex.get(uid); } }
xose/tinder
src/main/java/org/xmpp/resultsetmanagement/ResultSetImpl.java
2,644
/* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int, int) */
block_comment
nl
/** * Copyright (C) 2004-2009 Jive Software. 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.xmpp.resultsetmanagement; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.List; import java.util.Map; import net.jcip.annotations.NotThreadSafe; /** * A result set representation as described in XEP-0059. Note that this result * 'set' actually makes use of a List implementations, as the Java Set * definition disallows duplicate elements, while the List definition supplies * most of the required indexing operations. * * This ResultSet implementation loads all all results from the set into memory, * which might be undesirable for very large sets, or for sets where the * retrieval of a result is an expensive operation. sets. * * As most methods are backed by the {@link List#subList(int, int)} method, * non-structural changes in the returned lists are reflected in the ResultSet, * and vice-versa. * * @author Guus der Kinderen, [email protected] * * @param <E> * Each result set should be a collection of instances of the exact * same class. This class must implement the {@link Result} * interface. * @see java.util.List#subList(int, int) * */ /* * TODO: do we want changes to the returned Lists of methods in this class be * applied to the content of the ResultSet itself? Currently, because of the * usage of java.util.List#subList(int, int), it does. I'm thinking a * immodifiable solution would cause less problems. -Guus */ @NotThreadSafe public class ResultSetImpl<E extends Result> extends ResultSet<E> { /** * A list of all results in this ResultSet */ public final List<E> resultList; /** * A mapping of the UIDs of all results in resultList, to the index of those * entries in that list. */ public final Map<String, Integer> uidToIndex; /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is the same * order in which {@link Collection#iterator()} iterates over the * collection. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. */ public ResultSetImpl(final Collection<E> results) { this(results, null); } /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is defined by * the supplied Comparator class. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. * @param comparator * The Comparator that defines the order of the Results in this * result set. */ public ResultSetImpl(final Collection<E> results, final Comparator<E> comparator) { if (results == null) throw new NullPointerException("Argument 'results' cannot be null."); final int size = results.size(); resultList = new ArrayList<E>(size); uidToIndex = new Hashtable<String, Integer>(size); // sort the collection, if need be. List<E> sortedResults = null; if (comparator != null) { sortedResults = new ArrayList<E>(results); Collections.sort(sortedResults, comparator); } int index = 0; // iterate over either the sorted or unsorted collection for (final E result : sortedResults != null ? sortedResults : results) { if (result == null) throw new NullPointerException("The result set must not contain 'null' elements."); final String uid = result.getUID(); if (uidToIndex.containsKey(uid)) throw new IllegalArgumentException("The result set can not contain elements that have the same UID."); resultList.add(result); uidToIndex.put(uid, index); index++; } } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#size() */ @Override public int size() { return resultList.size(); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getAfter(E, int) */ @Override public List<E> getAfter(final String uid, final int maxAmount) { if (uid == null || uid.length() == 0) throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); // the result of this method is exclusive 'result' final int index = uidToIndex.get(uid) + 1; return get(index, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getBefore(E, int) */ @Override public List<E> getBefore(final String uid, final int maxAmount) { if (uid == null || uid.length() == 0) throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); // the result of this method is exclusive 'result' final int indexOfLastElement = uidToIndex.get(uid); final int indexOfFirstElement = indexOfLastElement - maxAmount; if (indexOfFirstElement < 0) return get(0, indexOfLastElement); return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int) */ @Override public E get(final int index) { return resultList.get(index); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getFirst(int) */ @Override public List<E> getFirst(final int maxAmount) { if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); return get(0, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getLast(int) */ @Override public List<E> getLast(final int maxAmount) { if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); final int indexOfFirstElement = size() - maxAmount; if (indexOfFirstElement < 0) return get(0, maxAmount); return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) <SUF>*/ @Override public List<E> get(final int fromIndex, final int maxAmount) { if (fromIndex < 0) throw new IllegalArgumentException("Argument 'fromIndex' must be zero or higher."); if (maxAmount < 1) throw new IllegalArgumentException("Argument 'maxAmount' must be a integer higher than zero."); if (fromIndex >= size()) return new ArrayList<E>(0); // calculate the last index to return, or return up to the end of last // index if 'amount' surpasses the list length. final int absoluteTo = fromIndex + maxAmount; final int toIndex = absoluteTo > size() ? size() : absoluteTo; return resultList.subList(fromIndex, toIndex); } /* * (non-Javadoc) * * @see * org.jivesoftware.util.resultsetmanager.ResultSet#indexOf(java.lang.String * ) */ @Override public int indexOf(final String uid) { return uidToIndex.get(uid); } }
149247_17
package com.xperia64.diyedit.savecrypt; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.HashMap; import com.xperia64.diyedit.FileByteOperations; public class Twintig { // Copyright 2007-2009 Segher Boessenkool <[email protected]> // Licensed under the terms of the GNU GPL, version 2 // http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt int verbose = 0; int MAXFILES = 1000; byte[] sd_key=new byte[16]; byte[] sd_iv=new byte[16]; byte[] md5_blanker=new byte[16]; byte[] header=new byte[0xf0c0]; public int n_files; int files_size; byte[][] files=new byte[MAXFILES][0x80]; String[] src=new String[MAXFILES]; String titleid=""; public long title_id; byte[] databin; HashMap<String, Integer> permissions; String drip; String out; BufferedOutputStream bos; public Twintig(String fold, String outfile) { out=outfile; drip=fold; title_id=Long.parseLong(fold.substring(fold.lastIndexOf(File.separator)+1),16); try { bos = new BufferedOutputStream(new FileOutputStream(drip.substring(0,drip.lastIndexOf(File.separator)+1)+outfile.substring(outfile.lastIndexOf(File.separator)+1))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // This is wrong for some reason. It turns the icon green instead of red for some reason and it isn't animated anymore. void read_image(byte[] data, int offset, int w, int h, String name) { int x, y; int ww, hh; File f = new File(name); if(!f.exists()) { System.out.println("No file"); return; } byte[] tmp = FileByteOperations.read(name); String header = ""; /*int o = 0; while(tmp[o-1]!=0x0A) { header+=(char)tmp[o]; o++; }*/ for(int i = 0; tmp[i]!=0x0A; i++) { header+=(char)tmp[i]; } header+=(char)0x0A; //header=header.trim(); // Good enough. if(!(header.startsWith("P6 ")&&header.endsWith(" 255\n"))) { return; } int first=3; while(true) { if(header.charAt(first)==' ') { break; } first++; } ww = Integer.parseInt(header.substring(3,first)); int second = first+1; while(true) { if(header.charAt(second)==' ') { break; } second++; } hh=Integer.parseInt(header.substring(first+1,second)); if(hh!=h||ww!=w) { System.out.println("Bad width/height"); return; } int fread_set = header.length(); for (y = 0; y < h; y++) for (x = 0; x < w; x++) { byte[] pix=new byte[3]; int raw; int x0, x1, y0, y1, off; x0 = x & 3; x1 = x >> 2; y0 = y & 3; y1 = y >> 2; off = x0 + 4 * y0 + 16 * x1 + 4 * w * y1; for(int i = 0; i<3; i++) { pix[i]=tmp[i+fread_set]; } fread_set+=3; raw = (pix[0] & 0xf8) << 7; raw |= (pix[1] & 0xf8) << 2; raw |= (pix[2] & 0xf8) >> 3; raw |= 0x8000; raw &= 0xFFFF; Tools.wbe16(data, 2*off+offset, raw); } tmp=null; f=null; } byte perm_from_path(String path) { int mode; byte perm; int i; if(permissions==null) { String permissionsdat = drip+File.separator+"permissions.dat"; BufferedReader br = null; try { br = new BufferedReader(new FileReader(permissionsdat)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } permissions = new HashMap<String, Integer>(); String line; try { while ((line = br.readLine()) != null) { // process the line. permissions.put(line.substring(0,line.lastIndexOf(' ')), Integer.parseInt(line.substring(line.lastIndexOf(' ')+1))); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } perm = 0; //System.out.println(drip+File.separator+path); mode = permissions.get(path); for (i = 0; i < 3; i++) { perm <<= 2; if ((mode & 0200)!=0) perm |= 2; if ((mode & 0400)!=0) perm |= 1; mode <<= 3; } return perm; } public void do_file_header(long title_id, byte[] toc) { for(int i = 0; i<header.length; i++) { header[i]=0; } Tools.wbe64(header, 0, title_id); header[0x0c] = (0x35); for(int i = 0; i<16; i++) { header[0x0e+i]=Tools.MD5_BLANKER[i]; } byte[] wibn={0x57, 0x49, 0x42, 0x4E}; for(int i = 0; i<4; i++) { header[0x20+i]=wibn[i]; } // XXX: what about the stuff at 0x24? String name; name=drip+File.separator+"###title###"; byte[] title = FileByteOperations.read(name); for(int i = 0; i<0x80; i++) { header[i+0x40]=title[i]; } name=drip+File.separator+"###banner###.ppm"; read_image(header, 0xc0, 192, 64, name); name=drip+File.separator+"###icon###.ppm"; boolean have_anim_icon = true; if(new File(name).exists()) have_anim_icon=false; if (!have_anim_icon) { Tools.wbe32(header, 8, 0x72a0); read_image(header, 0x60c0, 48, 48, name); } else { System.out.println("We have an animation!"); int i; for (i = 0; i < 8; i++) { name=drip+File.separator+"###icon"+i+"###.ppm"; if (new File(name).exists()) { read_image(header, 0x60c0 + 0x1200*i, 48, 48, name); } else{ break; } } Tools.wbe32(header, 8, 0x60a0 + (0x1200*i)); } byte[] md5_calc; md5_calc=Tools.md5(header); for(int i = 0; i<16; i++) { header[i+0x0e]=md5_calc[i]; } header=Tools.aes_cbc_enc(Tools.SDKey, Tools.SDIV, header); try { bos.write(header); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void find_files_recursive(String path) { String name; // No need //int len; //int is_dir; byte[] p; int size; File f = new File(path); if (!f.exists()) { System.out.println("No path"); return; } for(File ff:f.listFiles()) { if(!(ff.getName().equals(".")||ff.getName().equals("..")||ff.getName().startsWith("###")||ff.getName().equals("permissions.dat"))) { name=ff.getAbsolutePath(); src[n_files]=name; if(ff.isDirectory()) size=0; else size=(int) ff.length(); p = new byte[0x80]; Tools.wbe32(p, 0, 0x3adf17e); Tools.wbe32(p, 4, size); p[8] = perm_from_path(name); p[0x0a] = (byte) (ff.isDirectory() ? 2 : 1); for(int i = 0; i<ff.getName().length(); i++) { p[i+0x0b]=(byte)ff.getName().charAt(i); } files[n_files]=p; n_files++; // maybe fill up with dirt size=Math.round(size/0x40)*0x40; files_size += 0x80 + size; if (ff.isDirectory()) find_files_recursive(name); } } } /* int compar(const void *a, const void *b) { return strcmp((char *)a + 0x0b, (char *)b + 0x0b); }*/ public void find_files() { n_files = 0; files_size = 0; for(int i = 0; i<files.length; i++) { files[i]=new byte[0x80]; } find_files_recursive(drip); //Arrays.sort(files, new Compy()); //qsort(files, n_files, 0x80, compar); } int wiggle_name(String name) { //XXX: encode embedded zeroes, etc. return name.length(); } /* void find_files_toc(FILE *toc) { n_files = 0; files_size = 0; memset(files, 0, sizeof files); int len; int is_dir; byte *p; struct stat sb; int size; char line[256]; while (fgets(line, sizeof line, toc)) { line[strlen(line) - 1] = 0; // get rid of linefeed char *name; for (name = line; *name; name++) if (*name == ' ') break; if (!*name) ERROR("no space in TOC line"); *name = 0; name++; len = wiggle_name(name); if (len >= 53) ERROR("path too long"); if (stat(line, &sb)) fatal("stat %s", line); is_dir = S_ISDIR(sb.st_mode); size = (is_dir ? 0 : sb.st_size); strcpy(src[n_files], line); p = files[n_files++]; wbe32(p, 0x3adf17e); wbe32(p + 4, size); p[8] = 0x35; // rwr-r- p[0x0a] = is_dir ? 2 : 1; memcpy(p + 0x0b, name, len); // maybe fill up with dirt size = round_up(size, 0x40); files_size += 0x80 + size; //if (is_dir) // find_files_recursive(name); } if (ferror(toc)) fatal("reading toc"); }*/ public void do_backup_header(long title_id) { byte[] header = new byte[0x80]; for(int i = 0; i<0x80; i++) { header[i] = 0; } Tools.wbe32(header,0, 0x70); Tools.wbe32(header, 4, 0x426b0001); Tools.wbe32(header, 8, Tools.NG_id); Tools.wbe32(header, 0x0c, n_files); Tools.wbe32(header, 0x10, files_size); Tools.wbe32(header, 0x1c, files_size + 0x3c0); Tools.wbe64(header, 0x60, title_id); for(int i = 0; i<6; i++) { header[i+0x68]=Tools.NG_mac[i]; } try { bos.write(header); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*if (fwrite(header, sizeof header, 1, fp) != 1) fatal("write Bk header");*/ } public void do_file(int file_no) { byte[] header; int size; int rounded_size; byte /*perm, attr, */type; //String name=" "; byte[] data; byte[] in; header = files[file_no]; size = Tools.be32(header, 4); //perm = header[8]; //attr = header[9]; type = header[10]; //int loc = 11; //while(header[loc]!=0) //{ // name+=(char)header[loc]; // loc++; //} if (verbose!=0) { //System.out.println(String.format("file: size=%08x perm=%02x attr=%02x type=%02x name=%s\n",size, perm, attr, type, name)); }/*printf( "file: size=%08x perm=%02x attr=%02x type=%02x name=%s\n", size, perm, attr, type, name);*/ byte[] tmp = new byte[0x80]; for(int i = 0; i<0x80; i++) { tmp[i]=header[i]; } try { bos.write(tmp); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } tmp=null; String from = src[file_no]; if (type == 1) { rounded_size = (size/0x40)*0x40; data = new byte[rounded_size]; for(int i = 0; i<rounded_size-size; i++) { data[i+size]=0; } in=FileByteOperations.read(from); for(int i = 0; i<size; i++) { data[i]=in[i]; } tmp = new byte[16]; for(int i = 0; i<16; i++) { tmp[i] = header[i+0x50]; } data=Tools.aes_cbc_enc(Tools.SDKey, tmp, data); try { bos.write(data); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } data=null; } } void make_ec_cert(byte[] cert, byte[] sig, String signer, String name, byte[] priv, int key_id, int certoffset, int sigoffset, int privoffset) { for(int i = 0; i<0x180; i++) { cert[i+certoffset]=0; } Tools.wbe32(cert, certoffset, 0x10002); for(int i = 0; i<60; i++) { cert[i+4+certoffset]=sig[i+sigoffset]; } for(int i = 0; i<signer.length(); i++) { cert[i+0x80+certoffset]=(byte)signer.charAt(i); } Tools.wbe32(cert, certoffset+0xc0, 2); for(int i = 0; i<name.length(); i++) { cert[i+0xc4+certoffset]=(byte) name.charAt(i); } Tools.wbe32(cert, certoffset+ 0x104, key_id); EC.ec_priv_to_pub(priv, cert, certoffset+0x108, privoffset); } public void do_sig() { byte[] sig=new byte[0x40]; byte[] ng_cert=new byte[0x180]; byte[] ap_cert=new byte[0x180]; byte[] hash=new byte[0x14]; byte[] ap_priv=new byte[30]; byte[] ap_sig=new byte[60]; String signer="Root-CA00000001-MS00000002"; String name=String.format("NG%08x", Tools.NG_id); byte[] data; int data_size; make_ec_cert(ng_cert, Tools.NG_sig, signer, name, Tools.NG_priv, Tools.NG_key_id, 0, 0, 0); for(int i = 0; i<ap_priv.length; i++) { ap_priv[i]=0; } ap_priv[10] = 1; for(int i = 0; i<ap_sig.length; i++) { ap_sig[i]=81; } signer=String.format("Root-CA00000001-MS00000002-NG%08x", Tools.NG_id); name=String.format("AP%08x%08x", 1, 2); make_ec_cert(ap_cert, ap_sig, signer, name, ap_priv, 0, 0, 0, 0); byte[] tmp = new byte[0x100]; for(int i = 0; i<0x100; i++) { tmp[i] = ap_cert[i+0x80]; } hash = Tools.sha(tmp); EC.generate_ecdsa(ap_sig, ap_sig, Tools.NG_priv, hash, 0, 30, 0, 0); make_ec_cert(ap_cert, ap_sig, signer, name, ap_priv, 0, 0, 0, 0); data_size = files_size + 0x80; data = new byte[data_size]; int fread=0xf0c0; tmp = FileByteOperations.read(drip.substring(0,drip.lastIndexOf(File.separator)+1)+out.substring(out.lastIndexOf(File.separator)+1)); for(int i = 0; i<data_size; i++) { data[i]=tmp[i+fread]; } fread+=data_size; hash = Tools.sha(data); hash = Tools.sha(hash); data= null; EC.generate_ecdsa(sig, sig, ap_priv, hash, 0, 30, 0, 0); Tools.wbe32(sig, 60, 0x2f536969); try { bos.write(sig); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bos.write(ng_cert); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bos.write(ap_cert); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { copyFile(new File(drip.substring(0,drip.lastIndexOf(File.separator)+1)+out.substring(out.lastIndexOf(File.separator)+1)), new File(out)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if(source != null) { source.close(); } if(destination != null) { destination.close(); } } } /*int main(int argc, char **argv) { u64 title_id; byte tmp[4]; int i; if (argc != 3 && argc != 4) { fprintf(stderr, "Usage: %s <srcdir> <data.bin>\n", argv[0]); fprintf(stderr, "or: %s <srcdir> <data.bin> <toc>\n", argv[0]); return 1; } FILE *toc = 0; if (argc == 4) { toc = fopen(argv[3], "r"); if (!toc) fatal("open %s", argv[3]); } get_key("sd-key", sd_key, 16); get_key("sd-iv", sd_iv, 16); get_key("md5-blanker", md5_blanker, 16); get_key("default/NG-id", tmp, 4); Tools.NG_id = be32(tmp); get_key("default/NG-key-id", tmp, 4); Tools.NG_key_id = be32(tmp); get_key("default/NG-mac", Tools.NG_mac, 6); get_key("default/NG-priv", Tools.NG_priv, 30); get_key("default/NG-sig", Tools.NG_sig, 60); if (sscanf(argv[1], "%016llx", &title_id) != 1) ERROR("not a correct title id"); fp = fopen(argv[2], "wb+"); if (!fp) fatal("open %s", argv[2]); if (!toc) { if (chdir(argv[1])) fatal("chdir %s", argv[1]); } do_file_header(title_id, toc); if (toc!=null&&false) find_files_toc(toc); else find_files(); do_backup_header(title_id); for (i = 0; i < n_files; i++) do_file(i); // XXX: is this needed? if (!toc) { if (chdir("..")) fatal("chdir .."); } do_sig(); fclose(fp); return 0; }*/ }
xperia64/DIYEdit
src/com/xperia64/diyedit/savecrypt/Twintig.java
7,070
//XXX: encode embedded zeroes, etc.
line_comment
nl
package com.xperia64.diyedit.savecrypt; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.HashMap; import com.xperia64.diyedit.FileByteOperations; public class Twintig { // Copyright 2007-2009 Segher Boessenkool <[email protected]> // Licensed under the terms of the GNU GPL, version 2 // http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt int verbose = 0; int MAXFILES = 1000; byte[] sd_key=new byte[16]; byte[] sd_iv=new byte[16]; byte[] md5_blanker=new byte[16]; byte[] header=new byte[0xf0c0]; public int n_files; int files_size; byte[][] files=new byte[MAXFILES][0x80]; String[] src=new String[MAXFILES]; String titleid=""; public long title_id; byte[] databin; HashMap<String, Integer> permissions; String drip; String out; BufferedOutputStream bos; public Twintig(String fold, String outfile) { out=outfile; drip=fold; title_id=Long.parseLong(fold.substring(fold.lastIndexOf(File.separator)+1),16); try { bos = new BufferedOutputStream(new FileOutputStream(drip.substring(0,drip.lastIndexOf(File.separator)+1)+outfile.substring(outfile.lastIndexOf(File.separator)+1))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // This is wrong for some reason. It turns the icon green instead of red for some reason and it isn't animated anymore. void read_image(byte[] data, int offset, int w, int h, String name) { int x, y; int ww, hh; File f = new File(name); if(!f.exists()) { System.out.println("No file"); return; } byte[] tmp = FileByteOperations.read(name); String header = ""; /*int o = 0; while(tmp[o-1]!=0x0A) { header+=(char)tmp[o]; o++; }*/ for(int i = 0; tmp[i]!=0x0A; i++) { header+=(char)tmp[i]; } header+=(char)0x0A; //header=header.trim(); // Good enough. if(!(header.startsWith("P6 ")&&header.endsWith(" 255\n"))) { return; } int first=3; while(true) { if(header.charAt(first)==' ') { break; } first++; } ww = Integer.parseInt(header.substring(3,first)); int second = first+1; while(true) { if(header.charAt(second)==' ') { break; } second++; } hh=Integer.parseInt(header.substring(first+1,second)); if(hh!=h||ww!=w) { System.out.println("Bad width/height"); return; } int fread_set = header.length(); for (y = 0; y < h; y++) for (x = 0; x < w; x++) { byte[] pix=new byte[3]; int raw; int x0, x1, y0, y1, off; x0 = x & 3; x1 = x >> 2; y0 = y & 3; y1 = y >> 2; off = x0 + 4 * y0 + 16 * x1 + 4 * w * y1; for(int i = 0; i<3; i++) { pix[i]=tmp[i+fread_set]; } fread_set+=3; raw = (pix[0] & 0xf8) << 7; raw |= (pix[1] & 0xf8) << 2; raw |= (pix[2] & 0xf8) >> 3; raw |= 0x8000; raw &= 0xFFFF; Tools.wbe16(data, 2*off+offset, raw); } tmp=null; f=null; } byte perm_from_path(String path) { int mode; byte perm; int i; if(permissions==null) { String permissionsdat = drip+File.separator+"permissions.dat"; BufferedReader br = null; try { br = new BufferedReader(new FileReader(permissionsdat)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } permissions = new HashMap<String, Integer>(); String line; try { while ((line = br.readLine()) != null) { // process the line. permissions.put(line.substring(0,line.lastIndexOf(' ')), Integer.parseInt(line.substring(line.lastIndexOf(' ')+1))); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } perm = 0; //System.out.println(drip+File.separator+path); mode = permissions.get(path); for (i = 0; i < 3; i++) { perm <<= 2; if ((mode & 0200)!=0) perm |= 2; if ((mode & 0400)!=0) perm |= 1; mode <<= 3; } return perm; } public void do_file_header(long title_id, byte[] toc) { for(int i = 0; i<header.length; i++) { header[i]=0; } Tools.wbe64(header, 0, title_id); header[0x0c] = (0x35); for(int i = 0; i<16; i++) { header[0x0e+i]=Tools.MD5_BLANKER[i]; } byte[] wibn={0x57, 0x49, 0x42, 0x4E}; for(int i = 0; i<4; i++) { header[0x20+i]=wibn[i]; } // XXX: what about the stuff at 0x24? String name; name=drip+File.separator+"###title###"; byte[] title = FileByteOperations.read(name); for(int i = 0; i<0x80; i++) { header[i+0x40]=title[i]; } name=drip+File.separator+"###banner###.ppm"; read_image(header, 0xc0, 192, 64, name); name=drip+File.separator+"###icon###.ppm"; boolean have_anim_icon = true; if(new File(name).exists()) have_anim_icon=false; if (!have_anim_icon) { Tools.wbe32(header, 8, 0x72a0); read_image(header, 0x60c0, 48, 48, name); } else { System.out.println("We have an animation!"); int i; for (i = 0; i < 8; i++) { name=drip+File.separator+"###icon"+i+"###.ppm"; if (new File(name).exists()) { read_image(header, 0x60c0 + 0x1200*i, 48, 48, name); } else{ break; } } Tools.wbe32(header, 8, 0x60a0 + (0x1200*i)); } byte[] md5_calc; md5_calc=Tools.md5(header); for(int i = 0; i<16; i++) { header[i+0x0e]=md5_calc[i]; } header=Tools.aes_cbc_enc(Tools.SDKey, Tools.SDIV, header); try { bos.write(header); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void find_files_recursive(String path) { String name; // No need //int len; //int is_dir; byte[] p; int size; File f = new File(path); if (!f.exists()) { System.out.println("No path"); return; } for(File ff:f.listFiles()) { if(!(ff.getName().equals(".")||ff.getName().equals("..")||ff.getName().startsWith("###")||ff.getName().equals("permissions.dat"))) { name=ff.getAbsolutePath(); src[n_files]=name; if(ff.isDirectory()) size=0; else size=(int) ff.length(); p = new byte[0x80]; Tools.wbe32(p, 0, 0x3adf17e); Tools.wbe32(p, 4, size); p[8] = perm_from_path(name); p[0x0a] = (byte) (ff.isDirectory() ? 2 : 1); for(int i = 0; i<ff.getName().length(); i++) { p[i+0x0b]=(byte)ff.getName().charAt(i); } files[n_files]=p; n_files++; // maybe fill up with dirt size=Math.round(size/0x40)*0x40; files_size += 0x80 + size; if (ff.isDirectory()) find_files_recursive(name); } } } /* int compar(const void *a, const void *b) { return strcmp((char *)a + 0x0b, (char *)b + 0x0b); }*/ public void find_files() { n_files = 0; files_size = 0; for(int i = 0; i<files.length; i++) { files[i]=new byte[0x80]; } find_files_recursive(drip); //Arrays.sort(files, new Compy()); //qsort(files, n_files, 0x80, compar); } int wiggle_name(String name) { //XXX: encode<SUF> return name.length(); } /* void find_files_toc(FILE *toc) { n_files = 0; files_size = 0; memset(files, 0, sizeof files); int len; int is_dir; byte *p; struct stat sb; int size; char line[256]; while (fgets(line, sizeof line, toc)) { line[strlen(line) - 1] = 0; // get rid of linefeed char *name; for (name = line; *name; name++) if (*name == ' ') break; if (!*name) ERROR("no space in TOC line"); *name = 0; name++; len = wiggle_name(name); if (len >= 53) ERROR("path too long"); if (stat(line, &sb)) fatal("stat %s", line); is_dir = S_ISDIR(sb.st_mode); size = (is_dir ? 0 : sb.st_size); strcpy(src[n_files], line); p = files[n_files++]; wbe32(p, 0x3adf17e); wbe32(p + 4, size); p[8] = 0x35; // rwr-r- p[0x0a] = is_dir ? 2 : 1; memcpy(p + 0x0b, name, len); // maybe fill up with dirt size = round_up(size, 0x40); files_size += 0x80 + size; //if (is_dir) // find_files_recursive(name); } if (ferror(toc)) fatal("reading toc"); }*/ public void do_backup_header(long title_id) { byte[] header = new byte[0x80]; for(int i = 0; i<0x80; i++) { header[i] = 0; } Tools.wbe32(header,0, 0x70); Tools.wbe32(header, 4, 0x426b0001); Tools.wbe32(header, 8, Tools.NG_id); Tools.wbe32(header, 0x0c, n_files); Tools.wbe32(header, 0x10, files_size); Tools.wbe32(header, 0x1c, files_size + 0x3c0); Tools.wbe64(header, 0x60, title_id); for(int i = 0; i<6; i++) { header[i+0x68]=Tools.NG_mac[i]; } try { bos.write(header); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*if (fwrite(header, sizeof header, 1, fp) != 1) fatal("write Bk header");*/ } public void do_file(int file_no) { byte[] header; int size; int rounded_size; byte /*perm, attr, */type; //String name=" "; byte[] data; byte[] in; header = files[file_no]; size = Tools.be32(header, 4); //perm = header[8]; //attr = header[9]; type = header[10]; //int loc = 11; //while(header[loc]!=0) //{ // name+=(char)header[loc]; // loc++; //} if (verbose!=0) { //System.out.println(String.format("file: size=%08x perm=%02x attr=%02x type=%02x name=%s\n",size, perm, attr, type, name)); }/*printf( "file: size=%08x perm=%02x attr=%02x type=%02x name=%s\n", size, perm, attr, type, name);*/ byte[] tmp = new byte[0x80]; for(int i = 0; i<0x80; i++) { tmp[i]=header[i]; } try { bos.write(tmp); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } tmp=null; String from = src[file_no]; if (type == 1) { rounded_size = (size/0x40)*0x40; data = new byte[rounded_size]; for(int i = 0; i<rounded_size-size; i++) { data[i+size]=0; } in=FileByteOperations.read(from); for(int i = 0; i<size; i++) { data[i]=in[i]; } tmp = new byte[16]; for(int i = 0; i<16; i++) { tmp[i] = header[i+0x50]; } data=Tools.aes_cbc_enc(Tools.SDKey, tmp, data); try { bos.write(data); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } data=null; } } void make_ec_cert(byte[] cert, byte[] sig, String signer, String name, byte[] priv, int key_id, int certoffset, int sigoffset, int privoffset) { for(int i = 0; i<0x180; i++) { cert[i+certoffset]=0; } Tools.wbe32(cert, certoffset, 0x10002); for(int i = 0; i<60; i++) { cert[i+4+certoffset]=sig[i+sigoffset]; } for(int i = 0; i<signer.length(); i++) { cert[i+0x80+certoffset]=(byte)signer.charAt(i); } Tools.wbe32(cert, certoffset+0xc0, 2); for(int i = 0; i<name.length(); i++) { cert[i+0xc4+certoffset]=(byte) name.charAt(i); } Tools.wbe32(cert, certoffset+ 0x104, key_id); EC.ec_priv_to_pub(priv, cert, certoffset+0x108, privoffset); } public void do_sig() { byte[] sig=new byte[0x40]; byte[] ng_cert=new byte[0x180]; byte[] ap_cert=new byte[0x180]; byte[] hash=new byte[0x14]; byte[] ap_priv=new byte[30]; byte[] ap_sig=new byte[60]; String signer="Root-CA00000001-MS00000002"; String name=String.format("NG%08x", Tools.NG_id); byte[] data; int data_size; make_ec_cert(ng_cert, Tools.NG_sig, signer, name, Tools.NG_priv, Tools.NG_key_id, 0, 0, 0); for(int i = 0; i<ap_priv.length; i++) { ap_priv[i]=0; } ap_priv[10] = 1; for(int i = 0; i<ap_sig.length; i++) { ap_sig[i]=81; } signer=String.format("Root-CA00000001-MS00000002-NG%08x", Tools.NG_id); name=String.format("AP%08x%08x", 1, 2); make_ec_cert(ap_cert, ap_sig, signer, name, ap_priv, 0, 0, 0, 0); byte[] tmp = new byte[0x100]; for(int i = 0; i<0x100; i++) { tmp[i] = ap_cert[i+0x80]; } hash = Tools.sha(tmp); EC.generate_ecdsa(ap_sig, ap_sig, Tools.NG_priv, hash, 0, 30, 0, 0); make_ec_cert(ap_cert, ap_sig, signer, name, ap_priv, 0, 0, 0, 0); data_size = files_size + 0x80; data = new byte[data_size]; int fread=0xf0c0; tmp = FileByteOperations.read(drip.substring(0,drip.lastIndexOf(File.separator)+1)+out.substring(out.lastIndexOf(File.separator)+1)); for(int i = 0; i<data_size; i++) { data[i]=tmp[i+fread]; } fread+=data_size; hash = Tools.sha(data); hash = Tools.sha(hash); data= null; EC.generate_ecdsa(sig, sig, ap_priv, hash, 0, 30, 0, 0); Tools.wbe32(sig, 60, 0x2f536969); try { bos.write(sig); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bos.write(ng_cert); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bos.write(ap_cert); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { copyFile(new File(drip.substring(0,drip.lastIndexOf(File.separator)+1)+out.substring(out.lastIndexOf(File.separator)+1)), new File(out)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if(source != null) { source.close(); } if(destination != null) { destination.close(); } } } /*int main(int argc, char **argv) { u64 title_id; byte tmp[4]; int i; if (argc != 3 && argc != 4) { fprintf(stderr, "Usage: %s <srcdir> <data.bin>\n", argv[0]); fprintf(stderr, "or: %s <srcdir> <data.bin> <toc>\n", argv[0]); return 1; } FILE *toc = 0; if (argc == 4) { toc = fopen(argv[3], "r"); if (!toc) fatal("open %s", argv[3]); } get_key("sd-key", sd_key, 16); get_key("sd-iv", sd_iv, 16); get_key("md5-blanker", md5_blanker, 16); get_key("default/NG-id", tmp, 4); Tools.NG_id = be32(tmp); get_key("default/NG-key-id", tmp, 4); Tools.NG_key_id = be32(tmp); get_key("default/NG-mac", Tools.NG_mac, 6); get_key("default/NG-priv", Tools.NG_priv, 30); get_key("default/NG-sig", Tools.NG_sig, 60); if (sscanf(argv[1], "%016llx", &title_id) != 1) ERROR("not a correct title id"); fp = fopen(argv[2], "wb+"); if (!fp) fatal("open %s", argv[2]); if (!toc) { if (chdir(argv[1])) fatal("chdir %s", argv[1]); } do_file_header(title_id, toc); if (toc!=null&&false) find_files_toc(toc); else find_files(); do_backup_header(title_id); for (i = 0; i < n_files; i++) do_file(i); // XXX: is this needed? if (!toc) { if (chdir("..")) fatal("chdir .."); } do_sig(); fclose(fp); return 0; }*/ }
33464_46
/* * Copyright (C) 2019 xuexiangjys([email protected]) * * 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.xuexiang.xuidemo.base.webview; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.Gravity; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.PopupMenu; import androidx.fragment.app.Fragment; import com.just.agentweb.action.PermissionInterceptor; import com.just.agentweb.core.AgentWeb; import com.just.agentweb.core.client.DefaultWebClient; import com.just.agentweb.core.client.MiddlewareWebChromeBase; import com.just.agentweb.core.client.MiddlewareWebClientBase; import com.just.agentweb.core.client.WebListenerManager; import com.just.agentweb.core.web.AbsAgentWebSettings; import com.just.agentweb.core.web.AgentWebConfig; import com.just.agentweb.core.web.IAgentWebSettings; import com.just.agentweb.download.AgentWebDownloader; import com.just.agentweb.download.DefaultDownloadImpl; import com.just.agentweb.download.DownloadListenerAdapter; import com.just.agentweb.download.DownloadingService; import com.just.agentweb.widget.IWebLayout; import com.xuexiang.xaop.annotation.SingleClick; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xpage.base.XPageActivity; import com.xuexiang.xpage.base.XPageFragment; import com.xuexiang.xpage.core.PageOption; import com.xuexiang.xui.utils.DrawableUtils; import com.xuexiang.xui.widget.actionbar.TitleBar; import com.xuexiang.xuidemo.R; import com.xuexiang.xuidemo.base.BaseFragment; import com.xuexiang.xuidemo.utils.Utils; import com.xuexiang.xui.utils.XToastUtils; import com.xuexiang.xutil.common.logger.Logger; import com.xuexiang.xutil.net.JsonUtil; import java.util.HashMap; import butterknife.BindView; import butterknife.OnClick; import static com.xuexiang.xuidemo.base.webview.AgentWebFragment.KEY_URL; /** * 使用XPageFragment * * @author xuexiang * @since 2019-05-26 18:15 */ @Page(params = {KEY_URL}) public class XPageWebViewFragment extends BaseFragment { @BindView(R.id.iv_back) AppCompatImageView mIvBack; @BindView(R.id.view_line) View mLineView; @BindView(R.id.toolbar_title) TextView mTvTitle; protected AgentWeb mAgentWeb; private PopupMenu mPopupMenu; private DownloadingService mDownloadingService; /** * 打开网页 * * @param xPageActivity * @param url * @return */ public static Fragment openUrl(XPageActivity xPageActivity, String url) { return PageOption.to(XPageWebViewFragment.class) .putString(KEY_URL, url) .open(xPageActivity); } /** * 打开网页 * * @param fragment * @param url * @return */ public static Fragment openUrl(XPageFragment fragment, String url) { return PageOption.to(XPageWebViewFragment.class) .setNewActivity(true) .putString(KEY_URL, url) .open(fragment); } @Override protected TitleBar initTitle() { return null; } /** * 布局的资源id * * @return */ @Override protected int getLayoutId() { return R.layout.fragment_agentweb; } /** * 初始化控件 */ @Override protected void initViews() { mAgentWeb = AgentWeb.with(this) //传入AgentWeb的父控件。 .setAgentWebParent((LinearLayout) getRootView(), -1, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) //设置进度条颜色与高度,-1为默认值,高度为2,单位为dp。 .useDefaultIndicator(-1, 3) //设置 IAgentWebSettings。 .setAgentWebWebSettings(getSettings()) //WebViewClient , 与 WebView 使用一致 ,但是请勿获取WebView调用setWebViewClient(xx)方法了,会覆盖AgentWeb DefaultWebClient,同时相应的中间件也会失效。 .setWebViewClient(mWebViewClient) //WebChromeClient .setWebChromeClient(mWebChromeClient) //设置WebChromeClient中间件,支持多个WebChromeClient,AgentWeb 3.0.0 加入。 .useMiddlewareWebChrome(getMiddlewareWebChrome()) //设置WebViewClient中间件,支持多个WebViewClient, AgentWeb 3.0.0 加入。 .useMiddlewareWebClient(getMiddlewareWebClient()) //权限拦截 2.0.0 加入。 .setPermissionInterceptor(mPermissionInterceptor) //严格模式 Android 4.2.2 以下会放弃注入对象 ,使用AgentWebView没影响。 .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //自定义UI AgentWeb3.0.0 加入。 .setAgentWebUIController(new UIController(getActivity())) //参数1是错误显示的布局,参数2点击刷新控件ID -1表示点击整个布局都刷新, AgentWeb 3.0.0 加入。 .setMainFrameErrorView(R.layout.agentweb_error_page, -1) .setWebLayout(getWebLayout()) //打开其他页面时,弹窗质询用户前往其他应用 AgentWeb 3.0.0 加入。 .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW) //拦截找不到相关页面的Url AgentWeb 3.0.0 加入。 .interceptUnkownUrl() //创建AgentWeb。 .createAgentWeb() .ready()//设置 WebSettings。 //WebView载入该url地址的页面并显示。 .go(getUrl()); AgentWebConfig.debug(); pageNavigator(View.GONE); // 得到 AgentWeb 最底层的控件 addBackgroundChild(mAgentWeb.getWebCreator().getWebParentLayout()); // AgentWeb 没有把WebView的功能全面覆盖 ,所以某些设置 AgentWeb 没有提供,请从WebView方面入手设置。 mAgentWeb.getWebCreator().getWebView().setOverScrollMode(WebView.OVER_SCROLL_NEVER); } protected IWebLayout getWebLayout() { return new WebLayout(getActivity()); } protected void addBackgroundChild(FrameLayout frameLayout) { TextView textView = new TextView(frameLayout.getContext()); textView.setText("技术由 AgentWeb 提供"); textView.setTextSize(16); textView.setTextColor(Color.parseColor("#727779")); frameLayout.setBackgroundColor(Color.parseColor("#272b2d")); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(-2, -2); params.gravity = Gravity.CENTER_HORIZONTAL; final float scale = frameLayout.getContext().getResources().getDisplayMetrics().density; params.topMargin = (int) (15 * scale + 0.5f); frameLayout.addView(textView, 0, params); } private void pageNavigator(int tag) { //返回的导航按钮 mIvBack.setVisibility(tag); mLineView.setVisibility(tag); } @SingleClick @OnClick({R.id.iv_back, R.id.iv_finish, R.id.iv_more}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_back: // true表示AgentWeb处理了该事件 if (!mAgentWeb.back()) { popToBack(); } break; case R.id.iv_finish: popToBack(); break; case R.id.iv_more: showPoPup(view); break; default: break; } } //=====================下载============================// /** * 更新于 AgentWeb 4.0.0,下载监听 */ protected DownloadListenerAdapter mDownloadListenerAdapter = new DownloadListenerAdapter() { /** * * @param url 下载链接 * @param userAgent UserAgent * @param contentDisposition ContentDisposition * @param mimeType 资源的媒体类型 * @param contentLength 文件长度 * @param extra 下载配置 , 用户可以通过 Extra 修改下载icon , 关闭进度条 , 是否强制下载。 * @return true 表示用户处理了该下载事件 , false 交给 AgentWeb 下载 */ @Override public boolean onStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength, AgentWebDownloader.Extra extra) { Logger.i("onStart:" + url); // 是否开启断点续传 extra.setOpenBreakPointDownload(true) //下载通知的icon .setIcon(R.drawable.ic_file_download_black_24dp) // 连接的超时时间 .setConnectTimeOut(6000) // 以8KB位单位,默认60s ,如果60s内无法从网络流中读满8KB数据,则抛出异常 .setBlockMaxTime(10 * 60 * 1000) // 下载的超时时间 .setDownloadTimeOut(Long.MAX_VALUE) // 串行下载更节省资源哦 .setParallelDownload(false) // false 关闭进度通知 .setEnableIndicator(true) // 自定义请求头 .addHeader("Cookie", "xx") // 下载完成自动打开 .setAutoOpen(true) // 强制下载,不管网络网络类型 .setForceDownload(true); return false; } /** * * 不需要暂停或者停止下载该方法可以不必实现 * @param url * @param downloadingService 用户可以通过 DownloadingService#shutdownNow 终止下载 */ @Override public void onBindService(String url, DownloadingService downloadingService) { super.onBindService(url, downloadingService); mDownloadingService = downloadingService; Logger.i("onBindService:" + url + " DownloadingService:" + downloadingService); } /** * 回调onUnbindService方法,让用户释放掉 DownloadingService。 * @param url * @param downloadingService */ @Override public void onUnbindService(String url, DownloadingService downloadingService) { super.onUnbindService(url, downloadingService); mDownloadingService = null; Logger.i("onUnbindService:" + url); } /** * * @param url 下载链接 * @param loaded 已经下载的长度 * @param length 文件的总大小 * @param usedTime 耗时 ,单位ms * 注意该方法回调在子线程 ,线程名 AsyncTask #XX 或者 AgentWeb # XX */ @Override public void onProgress(String url, long loaded, long length, long usedTime) { int mProgress = (int) ((loaded) / (float) length * 100); Logger.i("onProgress:" + mProgress); super.onProgress(url, loaded, length, usedTime); } /** * * @param path 文件的绝对路径 * @param url 下载地址 * @param throwable 如果异常,返回给用户异常 * @return true 表示用户处理了下载完成后续的事件 ,false 默认交给AgentWeb 处理 */ @Override public boolean onResult(String path, String url, Throwable throwable) { //下载成功 if (null == throwable) { //do you work } else {//下载失败 } // true 不会发出下载完成的通知 , 或者打开文件 return false; } }; /** * 下载服务设置 * * @return IAgentWebSettings */ public IAgentWebSettings getSettings() { return new AbsAgentWebSettings() { private AgentWeb mAgentWeb; @Override protected void bindAgentWebSupport(AgentWeb agentWeb) { this.mAgentWeb = agentWeb; } /** * AgentWeb 4.0.0 内部删除了 DownloadListener 监听 ,以及相关API ,将 Download 部分完全抽离出来独立一个库, * 如果你需要使用 AgentWeb Download 部分 , 请依赖上 compile 'com.just.agentweb:download:4.0.0 , * 如果你需要监听下载结果,请自定义 AgentWebSetting , New 出 DefaultDownloadImpl,传入DownloadListenerAdapter * 实现进度或者结果监听,例如下面这个例子,如果你不需要监听进度,或者下载结果,下面 setDownloader 的例子可以忽略。 * @param webView * @param downloadListener * @return WebListenerManager */ @Override public WebListenerManager setDownloader(WebView webView, android.webkit.DownloadListener downloadListener) { return super.setDownloader(webView, DefaultDownloadImpl .create(getActivity(), webView, mDownloadListenerAdapter, mDownloadListenerAdapter, mAgentWeb.getPermissionInterceptor())); } }; } //===================WebChromeClient 和 WebViewClient===========================// /** * 页面空白,请检查scheme是否加上, scheme://host:port/path?query&query 。 * * @return mUrl */ public String getUrl() { String target = ""; Bundle bundle = getArguments(); if (bundle != null) { target = bundle.getString(KEY_URL); } if (TextUtils.isEmpty(target)) { target = "https://github.com/xuexiangjys"; } return target; } /** * 和浏览器相关,包括和JS的交互 */ protected WebChromeClient mWebChromeClient = new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); //网页加载进度 } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (mTvTitle != null && !TextUtils.isEmpty(title)) { if (title.length() > 10) { title = title.substring(0, 10).concat("..."); } mTvTitle.setText(title); } } }; /** * 和网页url加载相关,统计加载时间 */ protected WebViewClient mWebViewClient = new WebViewClient() { private HashMap<String, Long> mTimer = new HashMap<>(); @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return shouldOverrideUrlLoading(view, request.getUrl() + ""); } @Nullable @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return super.shouldInterceptRequest(view, request); } @Override public boolean shouldOverrideUrlLoading(final WebView view, String url) { //intent:// scheme的处理 如果返回false , 则交给 DefaultWebClient 处理 , 默认会打开该Activity , 如果Activity不存在则跳到应用市场上去. true 表示拦截 //例如优酷视频播放 ,intent://play?...package=com.youku.phone;end; //优酷想唤起自己应用播放该视频 , 下面拦截地址返回 true 则会在应用内 H5 播放 ,禁止优酷唤起播放该视频, 如果返回 false , DefaultWebClient 会根据intent 协议处理 该地址 , 首先匹配该应用存不存在 ,如果存在 , 唤起该应用播放 , 如果不存在 , 则跳到应用市场下载该应用 . return url.startsWith("intent://") && url.contains("com.youku.phone"); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { mTimer.put(url, System.currentTimeMillis()); if (url.equals(getUrl())) { pageNavigator(View.GONE); } else { pageNavigator(View.VISIBLE); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); Long startTime = mTimer.get(url); if (startTime != null) { long overTime = System.currentTimeMillis(); //统计页面的使用时长 Logger.i(" page mUrl:" + url + " used time:" + (overTime - startTime)); } } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); } }; //=====================菜单========================// /** * 显示更多菜单 * * @param view 菜单依附在该View下面 */ private void showPoPup(View view) { if (mPopupMenu == null) { mPopupMenu = new PopupMenu(getContext(), view); mPopupMenu.inflate(R.menu.menu_toolbar_web); mPopupMenu.setOnMenuItemClickListener(mOnMenuItemClickListener); } mPopupMenu.show(); } /** * 菜单事件 */ private PopupMenu.OnMenuItemClickListener mOnMenuItemClickListener = new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.refresh: if (mAgentWeb != null) { mAgentWeb.getUrlLoader().reload(); // 刷新 } return true; case R.id.copy: if (mAgentWeb != null) { toCopy(getContext(), mAgentWeb.getWebCreator().getWebView().getUrl()); } return true; case R.id.default_browser: if (mAgentWeb != null) { openBrowser(mAgentWeb.getWebCreator().getWebView().getUrl()); } return true; case R.id.share: if (mAgentWeb != null) { shareWebUrl(mAgentWeb.getWebCreator().getWebView().getUrl()); } return true; case R.id.capture: if (mAgentWeb != null) { captureWebView(); } return true; case R.id.default_clean: toCleanWebCache(); return true; default: return false; } } }; /** * 打开浏览器 * * @param targetUrl 外部浏览器打开的地址 */ private void openBrowser(String targetUrl) { if (TextUtils.isEmpty(targetUrl) || targetUrl.startsWith("file://")) { XToastUtils.toast(targetUrl + " 该链接无法使用浏览器打开。"); return; } Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); Uri uri = Uri.parse(targetUrl); intent.setData(uri); startActivity(intent); } /** * 分享网页链接 * * @param url 网页链接 */ private void shareWebUrl(String url) { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, url); shareIntent.setType("text/plain"); //设置分享列表的标题,并且每次都显示分享列表 startActivity(Intent.createChooser(shareIntent, "分享到")); } /** * 网页截图保存 */ private void captureWebView() { //简单的截取当前网页可见的内容 // Utils.showCaptureBitmap(mAgentWeb.getWebCreator().getWebView()); //网页长截图 Utils.showCaptureBitmap(getContext(), DrawableUtils.createBitmapFromWebView(mAgentWeb.getWebCreator().getWebView())); } /** * 清除 WebView 缓存 */ private void toCleanWebCache() { if (mAgentWeb != null) { //清理所有跟WebView相关的缓存 ,数据库, 历史记录 等。 mAgentWeb.clearWebCache(); XToastUtils.toast("已清理缓存"); //清空所有 AgentWeb 硬盘缓存,包括 WebView 的缓存 , AgentWeb 下载的图片 ,视频 ,apk 等文件。 // AgentWebConfig.clearDiskCache(this.getContext()); } } /** * 复制字符串 * * @param context * @param text */ private void toCopy(Context context, String text) { ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); if (manager == null) { return; } manager.setPrimaryClip(ClipData.newPlainText(null, text)); } //===================生命周期管理===========================// @Override public void onResume() { if (mAgentWeb != null) { mAgentWeb.getWebLifeCycle().onResume();//恢复 } super.onResume(); } @Override public void onPause() { if (mAgentWeb != null) { mAgentWeb.getWebLifeCycle().onPause(); //暂停应用内所有WebView , 调用mWebView.resumeTimers();/mAgentWeb.getWebLifeCycle().onResume(); 恢复。 } super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mAgentWeb != null && mAgentWeb.handleKeyEvent(keyCode, event); } @Override public void onDestroyView() { if (mAgentWeb != null) { mAgentWeb.destroy(); } super.onDestroyView(); } //===================中间键===========================// /** * MiddlewareWebClientBase 是 AgentWeb 3.0.0 提供一个强大的功能, * 如果用户需要使用 AgentWeb 提供的功能, 不想重写 WebClientView方 * 法覆盖AgentWeb提供的功能,那么 MiddlewareWebClientBase 是一个 * 不错的选择 。 * * @return */ protected MiddlewareWebClientBase getMiddlewareWebClient() { return new MiddlewareWebViewClient() { /** * * @param view * @param url * @return */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // 拦截 url,不执行 DefaultWebClient#shouldOverrideUrlLoading if (url.startsWith("agentweb")) { return true; } // 执行 DefaultWebClient#shouldOverrideUrlLoading return super.shouldOverrideUrlLoading(view, url); // do you work } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } }; } protected MiddlewareWebChromeBase getMiddlewareWebChrome() { return new MiddlewareChromeClient() { }; } /** * 权限申请拦截器 */ protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() { /** * PermissionInterceptor 能达到 url1 允许授权, url2 拒绝授权的效果。 * @param url * @param permissions * @param action * @return true 该Url对应页面请求权限进行拦截 ,false 表示不拦截。 */ @Override public boolean intercept(String url, String[] permissions, String action) { Logger.i("mUrl:" + url + " permission:" + JsonUtil.toJson(permissions) + " action:" + action); return false; } }; }
xuexiangjys/XUI
app/src/main/java/com/xuexiang/xuidemo/base/webview/XPageWebViewFragment.java
7,031
// 拦截 url,不执行 DefaultWebClient#shouldOverrideUrlLoading
line_comment
nl
/* * Copyright (C) 2019 xuexiangjys([email protected]) * * 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.xuexiang.xuidemo.base.webview; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.Gravity; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.PopupMenu; import androidx.fragment.app.Fragment; import com.just.agentweb.action.PermissionInterceptor; import com.just.agentweb.core.AgentWeb; import com.just.agentweb.core.client.DefaultWebClient; import com.just.agentweb.core.client.MiddlewareWebChromeBase; import com.just.agentweb.core.client.MiddlewareWebClientBase; import com.just.agentweb.core.client.WebListenerManager; import com.just.agentweb.core.web.AbsAgentWebSettings; import com.just.agentweb.core.web.AgentWebConfig; import com.just.agentweb.core.web.IAgentWebSettings; import com.just.agentweb.download.AgentWebDownloader; import com.just.agentweb.download.DefaultDownloadImpl; import com.just.agentweb.download.DownloadListenerAdapter; import com.just.agentweb.download.DownloadingService; import com.just.agentweb.widget.IWebLayout; import com.xuexiang.xaop.annotation.SingleClick; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xpage.base.XPageActivity; import com.xuexiang.xpage.base.XPageFragment; import com.xuexiang.xpage.core.PageOption; import com.xuexiang.xui.utils.DrawableUtils; import com.xuexiang.xui.widget.actionbar.TitleBar; import com.xuexiang.xuidemo.R; import com.xuexiang.xuidemo.base.BaseFragment; import com.xuexiang.xuidemo.utils.Utils; import com.xuexiang.xui.utils.XToastUtils; import com.xuexiang.xutil.common.logger.Logger; import com.xuexiang.xutil.net.JsonUtil; import java.util.HashMap; import butterknife.BindView; import butterknife.OnClick; import static com.xuexiang.xuidemo.base.webview.AgentWebFragment.KEY_URL; /** * 使用XPageFragment * * @author xuexiang * @since 2019-05-26 18:15 */ @Page(params = {KEY_URL}) public class XPageWebViewFragment extends BaseFragment { @BindView(R.id.iv_back) AppCompatImageView mIvBack; @BindView(R.id.view_line) View mLineView; @BindView(R.id.toolbar_title) TextView mTvTitle; protected AgentWeb mAgentWeb; private PopupMenu mPopupMenu; private DownloadingService mDownloadingService; /** * 打开网页 * * @param xPageActivity * @param url * @return */ public static Fragment openUrl(XPageActivity xPageActivity, String url) { return PageOption.to(XPageWebViewFragment.class) .putString(KEY_URL, url) .open(xPageActivity); } /** * 打开网页 * * @param fragment * @param url * @return */ public static Fragment openUrl(XPageFragment fragment, String url) { return PageOption.to(XPageWebViewFragment.class) .setNewActivity(true) .putString(KEY_URL, url) .open(fragment); } @Override protected TitleBar initTitle() { return null; } /** * 布局的资源id * * @return */ @Override protected int getLayoutId() { return R.layout.fragment_agentweb; } /** * 初始化控件 */ @Override protected void initViews() { mAgentWeb = AgentWeb.with(this) //传入AgentWeb的父控件。 .setAgentWebParent((LinearLayout) getRootView(), -1, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) //设置进度条颜色与高度,-1为默认值,高度为2,单位为dp。 .useDefaultIndicator(-1, 3) //设置 IAgentWebSettings。 .setAgentWebWebSettings(getSettings()) //WebViewClient , 与 WebView 使用一致 ,但是请勿获取WebView调用setWebViewClient(xx)方法了,会覆盖AgentWeb DefaultWebClient,同时相应的中间件也会失效。 .setWebViewClient(mWebViewClient) //WebChromeClient .setWebChromeClient(mWebChromeClient) //设置WebChromeClient中间件,支持多个WebChromeClient,AgentWeb 3.0.0 加入。 .useMiddlewareWebChrome(getMiddlewareWebChrome()) //设置WebViewClient中间件,支持多个WebViewClient, AgentWeb 3.0.0 加入。 .useMiddlewareWebClient(getMiddlewareWebClient()) //权限拦截 2.0.0 加入。 .setPermissionInterceptor(mPermissionInterceptor) //严格模式 Android 4.2.2 以下会放弃注入对象 ,使用AgentWebView没影响。 .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //自定义UI AgentWeb3.0.0 加入。 .setAgentWebUIController(new UIController(getActivity())) //参数1是错误显示的布局,参数2点击刷新控件ID -1表示点击整个布局都刷新, AgentWeb 3.0.0 加入。 .setMainFrameErrorView(R.layout.agentweb_error_page, -1) .setWebLayout(getWebLayout()) //打开其他页面时,弹窗质询用户前往其他应用 AgentWeb 3.0.0 加入。 .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW) //拦截找不到相关页面的Url AgentWeb 3.0.0 加入。 .interceptUnkownUrl() //创建AgentWeb。 .createAgentWeb() .ready()//设置 WebSettings。 //WebView载入该url地址的页面并显示。 .go(getUrl()); AgentWebConfig.debug(); pageNavigator(View.GONE); // 得到 AgentWeb 最底层的控件 addBackgroundChild(mAgentWeb.getWebCreator().getWebParentLayout()); // AgentWeb 没有把WebView的功能全面覆盖 ,所以某些设置 AgentWeb 没有提供,请从WebView方面入手设置。 mAgentWeb.getWebCreator().getWebView().setOverScrollMode(WebView.OVER_SCROLL_NEVER); } protected IWebLayout getWebLayout() { return new WebLayout(getActivity()); } protected void addBackgroundChild(FrameLayout frameLayout) { TextView textView = new TextView(frameLayout.getContext()); textView.setText("技术由 AgentWeb 提供"); textView.setTextSize(16); textView.setTextColor(Color.parseColor("#727779")); frameLayout.setBackgroundColor(Color.parseColor("#272b2d")); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(-2, -2); params.gravity = Gravity.CENTER_HORIZONTAL; final float scale = frameLayout.getContext().getResources().getDisplayMetrics().density; params.topMargin = (int) (15 * scale + 0.5f); frameLayout.addView(textView, 0, params); } private void pageNavigator(int tag) { //返回的导航按钮 mIvBack.setVisibility(tag); mLineView.setVisibility(tag); } @SingleClick @OnClick({R.id.iv_back, R.id.iv_finish, R.id.iv_more}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_back: // true表示AgentWeb处理了该事件 if (!mAgentWeb.back()) { popToBack(); } break; case R.id.iv_finish: popToBack(); break; case R.id.iv_more: showPoPup(view); break; default: break; } } //=====================下载============================// /** * 更新于 AgentWeb 4.0.0,下载监听 */ protected DownloadListenerAdapter mDownloadListenerAdapter = new DownloadListenerAdapter() { /** * * @param url 下载链接 * @param userAgent UserAgent * @param contentDisposition ContentDisposition * @param mimeType 资源的媒体类型 * @param contentLength 文件长度 * @param extra 下载配置 , 用户可以通过 Extra 修改下载icon , 关闭进度条 , 是否强制下载。 * @return true 表示用户处理了该下载事件 , false 交给 AgentWeb 下载 */ @Override public boolean onStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength, AgentWebDownloader.Extra extra) { Logger.i("onStart:" + url); // 是否开启断点续传 extra.setOpenBreakPointDownload(true) //下载通知的icon .setIcon(R.drawable.ic_file_download_black_24dp) // 连接的超时时间 .setConnectTimeOut(6000) // 以8KB位单位,默认60s ,如果60s内无法从网络流中读满8KB数据,则抛出异常 .setBlockMaxTime(10 * 60 * 1000) // 下载的超时时间 .setDownloadTimeOut(Long.MAX_VALUE) // 串行下载更节省资源哦 .setParallelDownload(false) // false 关闭进度通知 .setEnableIndicator(true) // 自定义请求头 .addHeader("Cookie", "xx") // 下载完成自动打开 .setAutoOpen(true) // 强制下载,不管网络网络类型 .setForceDownload(true); return false; } /** * * 不需要暂停或者停止下载该方法可以不必实现 * @param url * @param downloadingService 用户可以通过 DownloadingService#shutdownNow 终止下载 */ @Override public void onBindService(String url, DownloadingService downloadingService) { super.onBindService(url, downloadingService); mDownloadingService = downloadingService; Logger.i("onBindService:" + url + " DownloadingService:" + downloadingService); } /** * 回调onUnbindService方法,让用户释放掉 DownloadingService。 * @param url * @param downloadingService */ @Override public void onUnbindService(String url, DownloadingService downloadingService) { super.onUnbindService(url, downloadingService); mDownloadingService = null; Logger.i("onUnbindService:" + url); } /** * * @param url 下载链接 * @param loaded 已经下载的长度 * @param length 文件的总大小 * @param usedTime 耗时 ,单位ms * 注意该方法回调在子线程 ,线程名 AsyncTask #XX 或者 AgentWeb # XX */ @Override public void onProgress(String url, long loaded, long length, long usedTime) { int mProgress = (int) ((loaded) / (float) length * 100); Logger.i("onProgress:" + mProgress); super.onProgress(url, loaded, length, usedTime); } /** * * @param path 文件的绝对路径 * @param url 下载地址 * @param throwable 如果异常,返回给用户异常 * @return true 表示用户处理了下载完成后续的事件 ,false 默认交给AgentWeb 处理 */ @Override public boolean onResult(String path, String url, Throwable throwable) { //下载成功 if (null == throwable) { //do you work } else {//下载失败 } // true 不会发出下载完成的通知 , 或者打开文件 return false; } }; /** * 下载服务设置 * * @return IAgentWebSettings */ public IAgentWebSettings getSettings() { return new AbsAgentWebSettings() { private AgentWeb mAgentWeb; @Override protected void bindAgentWebSupport(AgentWeb agentWeb) { this.mAgentWeb = agentWeb; } /** * AgentWeb 4.0.0 内部删除了 DownloadListener 监听 ,以及相关API ,将 Download 部分完全抽离出来独立一个库, * 如果你需要使用 AgentWeb Download 部分 , 请依赖上 compile 'com.just.agentweb:download:4.0.0 , * 如果你需要监听下载结果,请自定义 AgentWebSetting , New 出 DefaultDownloadImpl,传入DownloadListenerAdapter * 实现进度或者结果监听,例如下面这个例子,如果你不需要监听进度,或者下载结果,下面 setDownloader 的例子可以忽略。 * @param webView * @param downloadListener * @return WebListenerManager */ @Override public WebListenerManager setDownloader(WebView webView, android.webkit.DownloadListener downloadListener) { return super.setDownloader(webView, DefaultDownloadImpl .create(getActivity(), webView, mDownloadListenerAdapter, mDownloadListenerAdapter, mAgentWeb.getPermissionInterceptor())); } }; } //===================WebChromeClient 和 WebViewClient===========================// /** * 页面空白,请检查scheme是否加上, scheme://host:port/path?query&query 。 * * @return mUrl */ public String getUrl() { String target = ""; Bundle bundle = getArguments(); if (bundle != null) { target = bundle.getString(KEY_URL); } if (TextUtils.isEmpty(target)) { target = "https://github.com/xuexiangjys"; } return target; } /** * 和浏览器相关,包括和JS的交互 */ protected WebChromeClient mWebChromeClient = new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); //网页加载进度 } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (mTvTitle != null && !TextUtils.isEmpty(title)) { if (title.length() > 10) { title = title.substring(0, 10).concat("..."); } mTvTitle.setText(title); } } }; /** * 和网页url加载相关,统计加载时间 */ protected WebViewClient mWebViewClient = new WebViewClient() { private HashMap<String, Long> mTimer = new HashMap<>(); @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return shouldOverrideUrlLoading(view, request.getUrl() + ""); } @Nullable @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return super.shouldInterceptRequest(view, request); } @Override public boolean shouldOverrideUrlLoading(final WebView view, String url) { //intent:// scheme的处理 如果返回false , 则交给 DefaultWebClient 处理 , 默认会打开该Activity , 如果Activity不存在则跳到应用市场上去. true 表示拦截 //例如优酷视频播放 ,intent://play?...package=com.youku.phone;end; //优酷想唤起自己应用播放该视频 , 下面拦截地址返回 true 则会在应用内 H5 播放 ,禁止优酷唤起播放该视频, 如果返回 false , DefaultWebClient 会根据intent 协议处理 该地址 , 首先匹配该应用存不存在 ,如果存在 , 唤起该应用播放 , 如果不存在 , 则跳到应用市场下载该应用 . return url.startsWith("intent://") && url.contains("com.youku.phone"); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { mTimer.put(url, System.currentTimeMillis()); if (url.equals(getUrl())) { pageNavigator(View.GONE); } else { pageNavigator(View.VISIBLE); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); Long startTime = mTimer.get(url); if (startTime != null) { long overTime = System.currentTimeMillis(); //统计页面的使用时长 Logger.i(" page mUrl:" + url + " used time:" + (overTime - startTime)); } } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); } }; //=====================菜单========================// /** * 显示更多菜单 * * @param view 菜单依附在该View下面 */ private void showPoPup(View view) { if (mPopupMenu == null) { mPopupMenu = new PopupMenu(getContext(), view); mPopupMenu.inflate(R.menu.menu_toolbar_web); mPopupMenu.setOnMenuItemClickListener(mOnMenuItemClickListener); } mPopupMenu.show(); } /** * 菜单事件 */ private PopupMenu.OnMenuItemClickListener mOnMenuItemClickListener = new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.refresh: if (mAgentWeb != null) { mAgentWeb.getUrlLoader().reload(); // 刷新 } return true; case R.id.copy: if (mAgentWeb != null) { toCopy(getContext(), mAgentWeb.getWebCreator().getWebView().getUrl()); } return true; case R.id.default_browser: if (mAgentWeb != null) { openBrowser(mAgentWeb.getWebCreator().getWebView().getUrl()); } return true; case R.id.share: if (mAgentWeb != null) { shareWebUrl(mAgentWeb.getWebCreator().getWebView().getUrl()); } return true; case R.id.capture: if (mAgentWeb != null) { captureWebView(); } return true; case R.id.default_clean: toCleanWebCache(); return true; default: return false; } } }; /** * 打开浏览器 * * @param targetUrl 外部浏览器打开的地址 */ private void openBrowser(String targetUrl) { if (TextUtils.isEmpty(targetUrl) || targetUrl.startsWith("file://")) { XToastUtils.toast(targetUrl + " 该链接无法使用浏览器打开。"); return; } Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); Uri uri = Uri.parse(targetUrl); intent.setData(uri); startActivity(intent); } /** * 分享网页链接 * * @param url 网页链接 */ private void shareWebUrl(String url) { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, url); shareIntent.setType("text/plain"); //设置分享列表的标题,并且每次都显示分享列表 startActivity(Intent.createChooser(shareIntent, "分享到")); } /** * 网页截图保存 */ private void captureWebView() { //简单的截取当前网页可见的内容 // Utils.showCaptureBitmap(mAgentWeb.getWebCreator().getWebView()); //网页长截图 Utils.showCaptureBitmap(getContext(), DrawableUtils.createBitmapFromWebView(mAgentWeb.getWebCreator().getWebView())); } /** * 清除 WebView 缓存 */ private void toCleanWebCache() { if (mAgentWeb != null) { //清理所有跟WebView相关的缓存 ,数据库, 历史记录 等。 mAgentWeb.clearWebCache(); XToastUtils.toast("已清理缓存"); //清空所有 AgentWeb 硬盘缓存,包括 WebView 的缓存 , AgentWeb 下载的图片 ,视频 ,apk 等文件。 // AgentWebConfig.clearDiskCache(this.getContext()); } } /** * 复制字符串 * * @param context * @param text */ private void toCopy(Context context, String text) { ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); if (manager == null) { return; } manager.setPrimaryClip(ClipData.newPlainText(null, text)); } //===================生命周期管理===========================// @Override public void onResume() { if (mAgentWeb != null) { mAgentWeb.getWebLifeCycle().onResume();//恢复 } super.onResume(); } @Override public void onPause() { if (mAgentWeb != null) { mAgentWeb.getWebLifeCycle().onPause(); //暂停应用内所有WebView , 调用mWebView.resumeTimers();/mAgentWeb.getWebLifeCycle().onResume(); 恢复。 } super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mAgentWeb != null && mAgentWeb.handleKeyEvent(keyCode, event); } @Override public void onDestroyView() { if (mAgentWeb != null) { mAgentWeb.destroy(); } super.onDestroyView(); } //===================中间键===========================// /** * MiddlewareWebClientBase 是 AgentWeb 3.0.0 提供一个强大的功能, * 如果用户需要使用 AgentWeb 提供的功能, 不想重写 WebClientView方 * 法覆盖AgentWeb提供的功能,那么 MiddlewareWebClientBase 是一个 * 不错的选择 。 * * @return */ protected MiddlewareWebClientBase getMiddlewareWebClient() { return new MiddlewareWebViewClient() { /** * * @param view * @param url * @return */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // 拦截 url,不执行<SUF> if (url.startsWith("agentweb")) { return true; } // 执行 DefaultWebClient#shouldOverrideUrlLoading return super.shouldOverrideUrlLoading(view, url); // do you work } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } }; } protected MiddlewareWebChromeBase getMiddlewareWebChrome() { return new MiddlewareChromeClient() { }; } /** * 权限申请拦截器 */ protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() { /** * PermissionInterceptor 能达到 url1 允许授权, url2 拒绝授权的效果。 * @param url * @param permissions * @param action * @return true 该Url对应页面请求权限进行拦截 ,false 表示不拦截。 */ @Override public boolean intercept(String url, String[] permissions, String action) { Logger.i("mUrl:" + url + " permission:" + JsonUtil.toJson(permissions) + " action:" + action); return false; } }; }
207517_13
package com.mossle.core.page; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; /** * 分页参数与分页结果. * * @author Lingo */ public class Page { // ========================================== // static fields... /** 正序. */ public static final String ASC = "ASC"; /** 倒序. */ public static final String DESC = "DESC"; /** 默认每页显示10条数据. */ public static final int DEFAULT_PAGE_SIZE = 10; // ========================================== // fields... /** 当前第几页,默认值为1,既第一页. */ private int pageNo = 1; /** 每页最大记录数,默认值为10. */ private int pageSize = DEFAULT_PAGE_SIZE; /** 排序字段名. */ private List<String> orderBys = new ArrayList<String>(); /** 使用正序还是倒序. */ private List<String> orders = new ArrayList<String>(); /** 查询结果. */ private Object result; /** 总记录数,默认值为-1,表示totalCount不可用. */ private long totalCount = -1L; /** 是否计算数据库中的记录总数. */ private boolean autoCount; /** 当前页第一条记录的索引,默认值为0,既第一页第一条记录. */ private long start; /** 总页数,默认值为-1,表示pageCount不可用. */ private long pageCount = -1; // ========================================== // constructor... /** 构造方法. */ public Page() { totalCount = 0; result = new ArrayList(); } /** * 构造方法. * * @param result * Object * @param totalCount * int */ public Page(Object result, int totalCount) { this.result = result; this.totalCount = totalCount; } /** * 构造方法. * * @param pageNo * int * @param pageSize * int * @param orderBy * String * @param order * String */ public Page(int pageNo, int pageSize, String orderBy, String order) { this.pageNo = pageNo; this.pageSize = pageSize; this.setOrderBy(orderBy); this.checkAndSetOrder(order); this.calculateStart(); } // ========================================== // 工具方法 /** * 是否为正序排序. * * @return boolean */ public boolean isAsc() { return !DESC.equalsIgnoreCase(this.getOrder()); } /** * 取得倒转的排序方向. * * @return 如果dir=='ASC'就返回'DESC',如果dir='DESC'就返回'ASC' */ public String getInverseOrder() { if (DESC.equalsIgnoreCase(this.getOrder())) { return ASC; } else { return DESC; } } /** * 页面显示最大记录数是否可用. * * @return pageSize > 0 */ public boolean isPageSizeEnabled() { return pageSize > 0; } /** * 页面第一条记录的索引是否可用. * * @return start */ public boolean isStartEnabled() { return start >= 0; } /** * 排序是否可用. * * @return orderBy是否非空 */ public boolean isOrderEnabled() { return ((!orderBys.isEmpty()) && (!orders.isEmpty())); } /** * 是否有前一页. * * @return boolean */ public boolean isPreviousEnabled() { return pageNo > 1; } /** * 是否有后一页. * * @return boolean */ public boolean isNextEnabled() { return pageNo < pageCount; } /** * 总页数是否可用. * * @return boolean */ public boolean isPageCountEnabled() { return pageCount >= 0; } /** 计算本页第一条记录的索引. */ private void calculateStart() { if ((pageNo < 1) || (pageSize < 1)) { start = -1; } else { start = (pageNo - 1L) * pageSize; } } /** 计算最大页数. */ private void calculatePageCount() { if ((totalCount < 0) || (pageSize < 1)) { pageCount = -1; } else { pageCount = ((totalCount - 1) / pageSize) + 1; } } // ========================================== // getter and setter method... /** @return pageNo. */ public int getPageNo() { return pageNo; } /** * @param pageNo * int. */ public void setPageNo(int pageNo) { this.pageNo = pageNo; this.calculateStart(); } /** @return pageSize. */ public int getPageSize() { return pageSize; } /** * @param pageSize * int. */ public void setPageSize(int pageSize) { this.pageSize = pageSize; this.calculateStart(); this.calculatePageCount(); } /** @return orderBy. */ public String getOrderBy() { if (!this.orderBys.isEmpty()) { return this.orderBys.get(0); } return null; } /** * @param orderBy * String. */ public void setOrderBy(String orderBy) { if ((orderBy == null) || (orderBy.trim().length() == 0)) { throw new IllegalArgumentException("orderBy should be blank"); } this.orderBys.clear(); this.orderBys.add(orderBy); if (this.getOrders().size() != 1) { this.setOrder(ASC); } } /** @return order. */ public String getOrder() { if (!this.orders.isEmpty()) { return this.orders.get(0); } return ASC; } /** * @param order * String. */ public void setOrder(String order) { this.checkAndSetOrder(order); } /** @return result. */ public Object getResult() { return result; } /** * @param result * Object. */ public void setResult(Object result) { this.result = result; } /** @return totalCount. */ public long getTotalCount() { return totalCount; } /** * @param totalCount * int. */ public void setTotalCount(long totalCount) { this.totalCount = totalCount; this.calculatePageCount(); } /** @return autoCount. */ public boolean isAutoCount() { return autoCount; } /** * @param autoCount * boolean. */ public void setAutoCount(boolean autoCount) { this.autoCount = autoCount; } /** @return start. */ public long getStart() { return start; } /** @return pageCount. */ public long getPageCount() { return pageCount; } /** @return result size. */ public int getResultSize() { if (result instanceof Collection) { return ((Collection) result).size(); } else { return 0; } } /** * chck and set order. * * @param text * String */ private void checkAndSetOrder(String text) { if (ASC.equalsIgnoreCase(text) || DESC.equalsIgnoreCase(text)) { text = text.toUpperCase(Locale.CHINA); this.orders.clear(); this.orders.add(text); } else { throw new IllegalArgumentException( "order should be 'DESC' or 'ASC'"); } } public void setDefaultOrder(String orderBy, String order) { if (!this.isOrderEnabled()) { this.setOrderBy(orderBy); this.setOrder(order); } } public void addOrder(String orderBy, String order) { if (this.orderBys.size() != this.orders.size()) { this.orderBys.clear(); this.orders.clear(); } this.orderBys.add(orderBy); if (ASC.equalsIgnoreCase(order) || DESC.equalsIgnoreCase(order)) { order = order.toUpperCase(Locale.CHINA); this.orders.add(order); } else { throw new IllegalArgumentException( "order should be 'DESC' or 'ASC'"); } } public List<String> getOrderBys() { return this.orderBys; } public void setOrderBys(List<String> orderBys) { this.orderBys = orderBys; } public List<String> getOrders() { return this.orders; } public void setOrders(List<String> orders) { this.orders = orders; } }
xuhuisheng/lemon
src/main/java/com/mossle/core/page/Page.java
2,517
/** * @param pageSize * int. */
block_comment
nl
package com.mossle.core.page; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; /** * 分页参数与分页结果. * * @author Lingo */ public class Page { // ========================================== // static fields... /** 正序. */ public static final String ASC = "ASC"; /** 倒序. */ public static final String DESC = "DESC"; /** 默认每页显示10条数据. */ public static final int DEFAULT_PAGE_SIZE = 10; // ========================================== // fields... /** 当前第几页,默认值为1,既第一页. */ private int pageNo = 1; /** 每页最大记录数,默认值为10. */ private int pageSize = DEFAULT_PAGE_SIZE; /** 排序字段名. */ private List<String> orderBys = new ArrayList<String>(); /** 使用正序还是倒序. */ private List<String> orders = new ArrayList<String>(); /** 查询结果. */ private Object result; /** 总记录数,默认值为-1,表示totalCount不可用. */ private long totalCount = -1L; /** 是否计算数据库中的记录总数. */ private boolean autoCount; /** 当前页第一条记录的索引,默认值为0,既第一页第一条记录. */ private long start; /** 总页数,默认值为-1,表示pageCount不可用. */ private long pageCount = -1; // ========================================== // constructor... /** 构造方法. */ public Page() { totalCount = 0; result = new ArrayList(); } /** * 构造方法. * * @param result * Object * @param totalCount * int */ public Page(Object result, int totalCount) { this.result = result; this.totalCount = totalCount; } /** * 构造方法. * * @param pageNo * int * @param pageSize * int * @param orderBy * String * @param order * String */ public Page(int pageNo, int pageSize, String orderBy, String order) { this.pageNo = pageNo; this.pageSize = pageSize; this.setOrderBy(orderBy); this.checkAndSetOrder(order); this.calculateStart(); } // ========================================== // 工具方法 /** * 是否为正序排序. * * @return boolean */ public boolean isAsc() { return !DESC.equalsIgnoreCase(this.getOrder()); } /** * 取得倒转的排序方向. * * @return 如果dir=='ASC'就返回'DESC',如果dir='DESC'就返回'ASC' */ public String getInverseOrder() { if (DESC.equalsIgnoreCase(this.getOrder())) { return ASC; } else { return DESC; } } /** * 页面显示最大记录数是否可用. * * @return pageSize > 0 */ public boolean isPageSizeEnabled() { return pageSize > 0; } /** * 页面第一条记录的索引是否可用. * * @return start */ public boolean isStartEnabled() { return start >= 0; } /** * 排序是否可用. * * @return orderBy是否非空 */ public boolean isOrderEnabled() { return ((!orderBys.isEmpty()) && (!orders.isEmpty())); } /** * 是否有前一页. * * @return boolean */ public boolean isPreviousEnabled() { return pageNo > 1; } /** * 是否有后一页. * * @return boolean */ public boolean isNextEnabled() { return pageNo < pageCount; } /** * 总页数是否可用. * * @return boolean */ public boolean isPageCountEnabled() { return pageCount >= 0; } /** 计算本页第一条记录的索引. */ private void calculateStart() { if ((pageNo < 1) || (pageSize < 1)) { start = -1; } else { start = (pageNo - 1L) * pageSize; } } /** 计算最大页数. */ private void calculatePageCount() { if ((totalCount < 0) || (pageSize < 1)) { pageCount = -1; } else { pageCount = ((totalCount - 1) / pageSize) + 1; } } // ========================================== // getter and setter method... /** @return pageNo. */ public int getPageNo() { return pageNo; } /** * @param pageNo * int. */ public void setPageNo(int pageNo) { this.pageNo = pageNo; this.calculateStart(); } /** @return pageSize. */ public int getPageSize() { return pageSize; } /** * @param pageSize <SUF>*/ public void setPageSize(int pageSize) { this.pageSize = pageSize; this.calculateStart(); this.calculatePageCount(); } /** @return orderBy. */ public String getOrderBy() { if (!this.orderBys.isEmpty()) { return this.orderBys.get(0); } return null; } /** * @param orderBy * String. */ public void setOrderBy(String orderBy) { if ((orderBy == null) || (orderBy.trim().length() == 0)) { throw new IllegalArgumentException("orderBy should be blank"); } this.orderBys.clear(); this.orderBys.add(orderBy); if (this.getOrders().size() != 1) { this.setOrder(ASC); } } /** @return order. */ public String getOrder() { if (!this.orders.isEmpty()) { return this.orders.get(0); } return ASC; } /** * @param order * String. */ public void setOrder(String order) { this.checkAndSetOrder(order); } /** @return result. */ public Object getResult() { return result; } /** * @param result * Object. */ public void setResult(Object result) { this.result = result; } /** @return totalCount. */ public long getTotalCount() { return totalCount; } /** * @param totalCount * int. */ public void setTotalCount(long totalCount) { this.totalCount = totalCount; this.calculatePageCount(); } /** @return autoCount. */ public boolean isAutoCount() { return autoCount; } /** * @param autoCount * boolean. */ public void setAutoCount(boolean autoCount) { this.autoCount = autoCount; } /** @return start. */ public long getStart() { return start; } /** @return pageCount. */ public long getPageCount() { return pageCount; } /** @return result size. */ public int getResultSize() { if (result instanceof Collection) { return ((Collection) result).size(); } else { return 0; } } /** * chck and set order. * * @param text * String */ private void checkAndSetOrder(String text) { if (ASC.equalsIgnoreCase(text) || DESC.equalsIgnoreCase(text)) { text = text.toUpperCase(Locale.CHINA); this.orders.clear(); this.orders.add(text); } else { throw new IllegalArgumentException( "order should be 'DESC' or 'ASC'"); } } public void setDefaultOrder(String orderBy, String order) { if (!this.isOrderEnabled()) { this.setOrderBy(orderBy); this.setOrder(order); } } public void addOrder(String orderBy, String order) { if (this.orderBys.size() != this.orders.size()) { this.orderBys.clear(); this.orders.clear(); } this.orderBys.add(orderBy); if (ASC.equalsIgnoreCase(order) || DESC.equalsIgnoreCase(order)) { order = order.toUpperCase(Locale.CHINA); this.orders.add(order); } else { throw new IllegalArgumentException( "order should be 'DESC' or 'ASC'"); } } public List<String> getOrderBys() { return this.orderBys; } public void setOrderBys(List<String> orderBys) { this.orderBys = orderBys; } public List<String> getOrders() { return this.orders; } public void setOrders(List<String> orders) { this.orders = orders; } }
14315_77
/* * Copyright (C) 2012 www.amsoft.cn * * 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.ab.view.cropimage; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.ImageView; // TODO: Auto-generated Javadoc /** * The Class CropViewBase. */ public abstract class CropViewBase extends ImageView { /** The Constant TAG. */ private static final String TAG = "ImageViewTouchBase"; // This is the base transformation which is used to show the image // initially. The current computation for this shows the image in // it's entirety, letterboxing as needed. One could choose to // show the image as cropped instead. // // This matrix is recomputed when we go from the thumbnail image to // the full size image. /** The m base matrix. */ protected Matrix mBaseMatrix = new Matrix(); // This is the supplementary transformation which reflects what // the user has done in terms of zooming and panning. // // This matrix remains the same when we go from the thumbnail image // to the full size image. /** The m supp matrix. */ protected Matrix mSuppMatrix = new Matrix(); // This is the final matrix which is computed as the concatentation // of the base matrix and the supplementary matrix. /** The m display matrix. */ private final Matrix mDisplayMatrix = new Matrix(); // Temporary buffer used for getting the values out of a matrix. /** The m matrix values. */ private final float[] mMatrixValues = new float[9]; // The current bitmap being displayed. /** The m bitmap displayed. */ final public RotateBitmap mBitmapDisplayed = new RotateBitmap(null); /** The m this height. */ int mThisWidth = -1, mThisHeight = -1; /** The m max zoom. */ float mMaxZoom; /** 高亮状态. */ public static final int STATE_HIGHLIGHT = 0x0; /** 涂鸦状态. */ public static final int STATE_DOODLE = STATE_HIGHLIGHT + 1; /** 没有任何操作. */ public static final int STATE_NONE = STATE_HIGHLIGHT + 2; /** The m state. */ protected int mState = STATE_HIGHLIGHT; // ImageViewTouchBase will pass a Bitmap to the Recycler if it has finished // its use of that Bitmap. /** * The Interface Recycler. */ public interface Recycler { /** * Recycle. * * @param b the b */ public void recycle(Bitmap b); } /** * Sets the recycler. * * @param r the new recycler */ public void setRecycler(Recycler r) { mRecycler = r; } /** The m recycler. */ private Recycler mRecycler; /** * 描述:TODO. * * @version v1.0 * @param changed the changed * @param left the left * @param top the top * @param right the right * @param bottom the bottom * @see android.view.View#onLayout(boolean, int, int, int, int) * @author: amsoft.cn * @date:2013-6-17 上午9:04:50 */ @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mThisWidth = right - left; mThisHeight = bottom - top; Runnable r = mOnLayoutRunnable; if (r != null) { mOnLayoutRunnable = null; r.run(); } if (mBitmapDisplayed.getBitmap() != null) { getProperBaseMatrix(mBitmapDisplayed, mBaseMatrix); setImageMatrix(getImageViewMatrix()); } } /** * 描述:TODO. * * @version v1.0 * @param keyCode the key code * @param event the event * @return true, if successful * @see android.view.View#onKeyDown(int, android.view.KeyEvent) * @author: amsoft.cn * @date:2013-6-17 上午9:04:50 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && getScale() > 1.0f) { // If we're zoomed in, pressing Back jumps out to show the entire // image, otherwise Back returns the user to the gallery. zoomTo(1.0f); return true; } return super.onKeyDown(keyCode, event); } /** The m handler. */ protected Handler mHandler = new Handler(); /** The m last x touch pos. */ protected int mLastXTouchPos; /** The m last y touch pos. */ protected int mLastYTouchPos; /** * 描述:TODO. * * @version v1.0 * @param bitmap the new image bitmap * @see android.widget.ImageView#setImageBitmap(android.graphics.Bitmap) * @author: amsoft.cn * @date:2013-6-17 上午9:04:50 */ @Override public void setImageBitmap(Bitmap bitmap) { setImageBitmap(bitmap, 0); } /** * Sets the image bitmap. * * @param bitmap the bitmap * @param rotation the rotation */ private void setImageBitmap(Bitmap bitmap, int rotation) { super.setImageBitmap(bitmap); Drawable d = getDrawable(); if (d != null) { d.setDither(true); } Bitmap old = mBitmapDisplayed.getBitmap(); mBitmapDisplayed.setBitmap(bitmap); mBitmapDisplayed.setRotation(rotation); if (old != null && old != bitmap && mRecycler != null) { mRecycler.recycle(old); } } /** * Clear. */ public void clear() { setImageBitmapResetBase(null, true); } /** The m on layout runnable. */ private Runnable mOnLayoutRunnable = null; // This function changes bitmap, reset base matrix according to the size // of the bitmap, and optionally reset the supplementary matrix. /** * Sets the image bitmap reset base. * * @param bitmap the bitmap * @param resetSupp the reset supp */ public void setImageBitmapResetBase(final Bitmap bitmap, final boolean resetSupp) { setImageRotateBitmapResetBase(new RotateBitmap(bitmap), resetSupp); } /** * Sets the image rotate bitmap reset base. * * @param bitmap the bitmap * @param resetSupp the reset supp */ public void setImageRotateBitmapResetBase(final RotateBitmap bitmap, final boolean resetSupp) { final int viewWidth = getWidth(); if (viewWidth <= 0) { mOnLayoutRunnable = new Runnable() { public void run() { setImageRotateBitmapResetBase(bitmap, resetSupp); } }; return; } if (bitmap.getBitmap() != null) { getProperBaseMatrix(bitmap, mBaseMatrix); setImageBitmap(bitmap.getBitmap(), bitmap.getRotation()); } else { mBaseMatrix.reset(); setImageBitmap(null); } if (resetSupp) { mSuppMatrix.reset(); } setImageMatrix(getImageViewMatrix()); mMaxZoom = maxZoom(); } // Center as much as possible in one or both axis. Centering is // defined as follows: if the image is scaled down below the // view's dimensions then center it (literally). If the image // is scaled larger than the view and is translated out of view // then translate it back into view (i.e. eliminate black bars). /** * Center. * * @param horizontal the horizontal * @param vertical the vertical */ public void center(boolean horizontal, boolean vertical) { if (mBitmapDisplayed.getBitmap() == null) { return; } Matrix m = getImageViewMatrix(); RectF rect = new RectF(0, 0, mBitmapDisplayed.getBitmap().getWidth(), mBitmapDisplayed.getBitmap().getHeight()); m.mapRect(rect); float height = rect.height(); float width = rect.width(); float deltaX = 0, deltaY = 0; if (vertical) { int viewHeight = getHeight(); if (height < viewHeight) { deltaY = (viewHeight - height) / 2 - rect.top; } else if (rect.top > 0) { deltaY = -rect.top; } else if (rect.bottom < viewHeight) { deltaY = getHeight() - rect.bottom; } } if (horizontal) { int viewWidth = getWidth(); if (width < viewWidth) { deltaX = (viewWidth - width) / 2 - rect.left; } else if (rect.left > 0) { deltaX = -rect.left; } else if (rect.right < viewWidth) { deltaX = viewWidth - rect.right; } } postTranslate(deltaX, deltaY); setImageMatrix(getImageViewMatrix()); } /** * Instantiates a new crop view base. * * @param context the context */ public CropViewBase(Context context) { super(context); init(); } /** * Instantiates a new crop view base. * * @param context the context * @param attrs the attrs */ public CropViewBase(Context context, AttributeSet attrs) { super(context, attrs); init(); } /** * Inits the. */ private void init() { setScaleType(ImageView.ScaleType.MATRIX); } /** * Gets the value. * * @param matrix the matrix * @param whichValue the which value * @return the value */ protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } // Get the scale factor out of the matrix. /** * Gets the scale. * * @param matrix the matrix * @return the scale */ protected float getScale(Matrix matrix) { return getValue(matrix, Matrix.MSCALE_X); } /** * Gets the scale. * * @return the scale */ public float getScale() { return getScale(mSuppMatrix); } // Setup the base matrix so that the image is centered and scaled properly. /** * Gets the proper base matrix. * * @param bitmap the bitmap * @param matrix the matrix * @return the proper base matrix */ private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix) { float viewWidth = getWidth(); float viewHeight = getHeight(); float w = bitmap.getWidth(); float h = bitmap.getHeight(); matrix.reset(); // We limit up-scaling to 2x otherwise the result may look bad if it's // a small icon. float widthScale = Math.min(viewWidth / w, 2.0f); float heightScale = Math.min(viewHeight / h, 2.0f); float scale = Math.min(widthScale, heightScale); matrix.postConcat(bitmap.getRotateMatrix()); matrix.postScale(scale, scale); matrix.postTranslate((viewWidth - w * scale) / 2F, (viewHeight - h * scale) / 2F); } // Combine the base matrix and the supp matrix to make the final matrix. /** * Gets the image view matrix. * * @return the image view matrix */ protected Matrix getImageViewMatrix() { // The final matrix is computed as the concatentation of the base matrix // and the supplementary matrix. mDisplayMatrix.set(mBaseMatrix); mDisplayMatrix.postConcat(mSuppMatrix); return mDisplayMatrix; } /** The Constant SCALE_RATE. */ static final float SCALE_RATE = 1.25F; // Sets the maximum zoom, which is a scale relative to the base matrix. It // is calculated to show the image at 400% zoom regardless of screen or // image orientation. If in the future we decode the full 3 megapixel image, // rather than the current 1024x768, this should be changed down to 200%. /** * Max zoom. * * @return the float */ protected float maxZoom() { if (mBitmapDisplayed.getBitmap() == null) { return 1F; } float fw = (float) mBitmapDisplayed.getWidth() / (float) mThisWidth; float fh = (float) mBitmapDisplayed.getHeight() / (float) mThisHeight; float max = Math.max(fw, fh) * 4; max = (max < 1.0f) ? 1.0f : max; return max; } /** * Zoom to. * * @param scale the scale * @param centerX the center x * @param centerY the center y */ protected void zoomTo(float scale, float centerX, float centerY) { if (scale > mMaxZoom) { scale = mMaxZoom; } float oldScale = getScale(); float deltaScale = scale / oldScale; mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY); setImageMatrix(getImageViewMatrix()); center(true, true); } /** * Zoom to. * * @param scale the scale * @param centerX the center x * @param centerY the center y * @param durationMs the duration ms */ protected void zoomTo(final float scale, final float centerX, final float centerY, final float durationMs) { final float incrementPerMs = (scale - getScale()) / durationMs; final float oldScale = getScale(); final long startTime = System.currentTimeMillis(); mHandler.post(new Runnable() { public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min(durationMs, now - startTime); float target = oldScale + (incrementPerMs * currentMs); zoomTo(target, centerX, centerY); if (currentMs < durationMs) { mHandler.post(this); } } }); } /** * Zoom to. * * @param scale the scale */ protected void zoomTo(float scale) { float cx = getWidth() / 2F; float cy = getHeight() / 2F; zoomTo(scale, cx, cy); } /** * Zoom in. */ protected void zoomIn() { zoomIn(SCALE_RATE); } /** * Zoom out. */ protected void zoomOut() { zoomOut(SCALE_RATE); } /** * Zoom in. * * @param rate the rate */ protected void zoomIn(float rate) { if (getScale() >= mMaxZoom) { return; // Don't let the user zoom into the molecular level. } if (mBitmapDisplayed.getBitmap() == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; mSuppMatrix.postScale(rate, rate, cx, cy); setImageMatrix(getImageViewMatrix()); } /** * Zoom out. * * @param rate the rate */ protected void zoomOut(float rate) { if (mBitmapDisplayed.getBitmap() == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; // Zoom out to at most 1x. Matrix tmp = new Matrix(mSuppMatrix); tmp.postScale(1F / rate, 1F / rate, cx, cy); if (getScale(tmp) < 1F) { mSuppMatrix.setScale(1F, 1F, cx, cy); } else { mSuppMatrix.postScale(1F / rate, 1F / rate, cx, cy); } setImageMatrix(getImageViewMatrix()); center(true, true); } /** * Post translate. * * @param dx the dx * @param dy the dy */ protected void postTranslate(float dx, float dy) { mSuppMatrix.postTranslate(dx, dy); } /** * Pan by. * * @param dx the dx * @param dy the dy */ protected void panBy(float dx, float dy) { postTranslate(dx, dy); setImageMatrix(getImageViewMatrix()); } }
xuyisheng/andbase
AndBase/src/com/ab/view/cropimage/CropViewBase.java
4,867
/** * Zoom in. */
block_comment
nl
/* * Copyright (C) 2012 www.amsoft.cn * * 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.ab.view.cropimage; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.ImageView; // TODO: Auto-generated Javadoc /** * The Class CropViewBase. */ public abstract class CropViewBase extends ImageView { /** The Constant TAG. */ private static final String TAG = "ImageViewTouchBase"; // This is the base transformation which is used to show the image // initially. The current computation for this shows the image in // it's entirety, letterboxing as needed. One could choose to // show the image as cropped instead. // // This matrix is recomputed when we go from the thumbnail image to // the full size image. /** The m base matrix. */ protected Matrix mBaseMatrix = new Matrix(); // This is the supplementary transformation which reflects what // the user has done in terms of zooming and panning. // // This matrix remains the same when we go from the thumbnail image // to the full size image. /** The m supp matrix. */ protected Matrix mSuppMatrix = new Matrix(); // This is the final matrix which is computed as the concatentation // of the base matrix and the supplementary matrix. /** The m display matrix. */ private final Matrix mDisplayMatrix = new Matrix(); // Temporary buffer used for getting the values out of a matrix. /** The m matrix values. */ private final float[] mMatrixValues = new float[9]; // The current bitmap being displayed. /** The m bitmap displayed. */ final public RotateBitmap mBitmapDisplayed = new RotateBitmap(null); /** The m this height. */ int mThisWidth = -1, mThisHeight = -1; /** The m max zoom. */ float mMaxZoom; /** 高亮状态. */ public static final int STATE_HIGHLIGHT = 0x0; /** 涂鸦状态. */ public static final int STATE_DOODLE = STATE_HIGHLIGHT + 1; /** 没有任何操作. */ public static final int STATE_NONE = STATE_HIGHLIGHT + 2; /** The m state. */ protected int mState = STATE_HIGHLIGHT; // ImageViewTouchBase will pass a Bitmap to the Recycler if it has finished // its use of that Bitmap. /** * The Interface Recycler. */ public interface Recycler { /** * Recycle. * * @param b the b */ public void recycle(Bitmap b); } /** * Sets the recycler. * * @param r the new recycler */ public void setRecycler(Recycler r) { mRecycler = r; } /** The m recycler. */ private Recycler mRecycler; /** * 描述:TODO. * * @version v1.0 * @param changed the changed * @param left the left * @param top the top * @param right the right * @param bottom the bottom * @see android.view.View#onLayout(boolean, int, int, int, int) * @author: amsoft.cn * @date:2013-6-17 上午9:04:50 */ @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mThisWidth = right - left; mThisHeight = bottom - top; Runnable r = mOnLayoutRunnable; if (r != null) { mOnLayoutRunnable = null; r.run(); } if (mBitmapDisplayed.getBitmap() != null) { getProperBaseMatrix(mBitmapDisplayed, mBaseMatrix); setImageMatrix(getImageViewMatrix()); } } /** * 描述:TODO. * * @version v1.0 * @param keyCode the key code * @param event the event * @return true, if successful * @see android.view.View#onKeyDown(int, android.view.KeyEvent) * @author: amsoft.cn * @date:2013-6-17 上午9:04:50 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && getScale() > 1.0f) { // If we're zoomed in, pressing Back jumps out to show the entire // image, otherwise Back returns the user to the gallery. zoomTo(1.0f); return true; } return super.onKeyDown(keyCode, event); } /** The m handler. */ protected Handler mHandler = new Handler(); /** The m last x touch pos. */ protected int mLastXTouchPos; /** The m last y touch pos. */ protected int mLastYTouchPos; /** * 描述:TODO. * * @version v1.0 * @param bitmap the new image bitmap * @see android.widget.ImageView#setImageBitmap(android.graphics.Bitmap) * @author: amsoft.cn * @date:2013-6-17 上午9:04:50 */ @Override public void setImageBitmap(Bitmap bitmap) { setImageBitmap(bitmap, 0); } /** * Sets the image bitmap. * * @param bitmap the bitmap * @param rotation the rotation */ private void setImageBitmap(Bitmap bitmap, int rotation) { super.setImageBitmap(bitmap); Drawable d = getDrawable(); if (d != null) { d.setDither(true); } Bitmap old = mBitmapDisplayed.getBitmap(); mBitmapDisplayed.setBitmap(bitmap); mBitmapDisplayed.setRotation(rotation); if (old != null && old != bitmap && mRecycler != null) { mRecycler.recycle(old); } } /** * Clear. */ public void clear() { setImageBitmapResetBase(null, true); } /** The m on layout runnable. */ private Runnable mOnLayoutRunnable = null; // This function changes bitmap, reset base matrix according to the size // of the bitmap, and optionally reset the supplementary matrix. /** * Sets the image bitmap reset base. * * @param bitmap the bitmap * @param resetSupp the reset supp */ public void setImageBitmapResetBase(final Bitmap bitmap, final boolean resetSupp) { setImageRotateBitmapResetBase(new RotateBitmap(bitmap), resetSupp); } /** * Sets the image rotate bitmap reset base. * * @param bitmap the bitmap * @param resetSupp the reset supp */ public void setImageRotateBitmapResetBase(final RotateBitmap bitmap, final boolean resetSupp) { final int viewWidth = getWidth(); if (viewWidth <= 0) { mOnLayoutRunnable = new Runnable() { public void run() { setImageRotateBitmapResetBase(bitmap, resetSupp); } }; return; } if (bitmap.getBitmap() != null) { getProperBaseMatrix(bitmap, mBaseMatrix); setImageBitmap(bitmap.getBitmap(), bitmap.getRotation()); } else { mBaseMatrix.reset(); setImageBitmap(null); } if (resetSupp) { mSuppMatrix.reset(); } setImageMatrix(getImageViewMatrix()); mMaxZoom = maxZoom(); } // Center as much as possible in one or both axis. Centering is // defined as follows: if the image is scaled down below the // view's dimensions then center it (literally). If the image // is scaled larger than the view and is translated out of view // then translate it back into view (i.e. eliminate black bars). /** * Center. * * @param horizontal the horizontal * @param vertical the vertical */ public void center(boolean horizontal, boolean vertical) { if (mBitmapDisplayed.getBitmap() == null) { return; } Matrix m = getImageViewMatrix(); RectF rect = new RectF(0, 0, mBitmapDisplayed.getBitmap().getWidth(), mBitmapDisplayed.getBitmap().getHeight()); m.mapRect(rect); float height = rect.height(); float width = rect.width(); float deltaX = 0, deltaY = 0; if (vertical) { int viewHeight = getHeight(); if (height < viewHeight) { deltaY = (viewHeight - height) / 2 - rect.top; } else if (rect.top > 0) { deltaY = -rect.top; } else if (rect.bottom < viewHeight) { deltaY = getHeight() - rect.bottom; } } if (horizontal) { int viewWidth = getWidth(); if (width < viewWidth) { deltaX = (viewWidth - width) / 2 - rect.left; } else if (rect.left > 0) { deltaX = -rect.left; } else if (rect.right < viewWidth) { deltaX = viewWidth - rect.right; } } postTranslate(deltaX, deltaY); setImageMatrix(getImageViewMatrix()); } /** * Instantiates a new crop view base. * * @param context the context */ public CropViewBase(Context context) { super(context); init(); } /** * Instantiates a new crop view base. * * @param context the context * @param attrs the attrs */ public CropViewBase(Context context, AttributeSet attrs) { super(context, attrs); init(); } /** * Inits the. */ private void init() { setScaleType(ImageView.ScaleType.MATRIX); } /** * Gets the value. * * @param matrix the matrix * @param whichValue the which value * @return the value */ protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } // Get the scale factor out of the matrix. /** * Gets the scale. * * @param matrix the matrix * @return the scale */ protected float getScale(Matrix matrix) { return getValue(matrix, Matrix.MSCALE_X); } /** * Gets the scale. * * @return the scale */ public float getScale() { return getScale(mSuppMatrix); } // Setup the base matrix so that the image is centered and scaled properly. /** * Gets the proper base matrix. * * @param bitmap the bitmap * @param matrix the matrix * @return the proper base matrix */ private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix) { float viewWidth = getWidth(); float viewHeight = getHeight(); float w = bitmap.getWidth(); float h = bitmap.getHeight(); matrix.reset(); // We limit up-scaling to 2x otherwise the result may look bad if it's // a small icon. float widthScale = Math.min(viewWidth / w, 2.0f); float heightScale = Math.min(viewHeight / h, 2.0f); float scale = Math.min(widthScale, heightScale); matrix.postConcat(bitmap.getRotateMatrix()); matrix.postScale(scale, scale); matrix.postTranslate((viewWidth - w * scale) / 2F, (viewHeight - h * scale) / 2F); } // Combine the base matrix and the supp matrix to make the final matrix. /** * Gets the image view matrix. * * @return the image view matrix */ protected Matrix getImageViewMatrix() { // The final matrix is computed as the concatentation of the base matrix // and the supplementary matrix. mDisplayMatrix.set(mBaseMatrix); mDisplayMatrix.postConcat(mSuppMatrix); return mDisplayMatrix; } /** The Constant SCALE_RATE. */ static final float SCALE_RATE = 1.25F; // Sets the maximum zoom, which is a scale relative to the base matrix. It // is calculated to show the image at 400% zoom regardless of screen or // image orientation. If in the future we decode the full 3 megapixel image, // rather than the current 1024x768, this should be changed down to 200%. /** * Max zoom. * * @return the float */ protected float maxZoom() { if (mBitmapDisplayed.getBitmap() == null) { return 1F; } float fw = (float) mBitmapDisplayed.getWidth() / (float) mThisWidth; float fh = (float) mBitmapDisplayed.getHeight() / (float) mThisHeight; float max = Math.max(fw, fh) * 4; max = (max < 1.0f) ? 1.0f : max; return max; } /** * Zoom to. * * @param scale the scale * @param centerX the center x * @param centerY the center y */ protected void zoomTo(float scale, float centerX, float centerY) { if (scale > mMaxZoom) { scale = mMaxZoom; } float oldScale = getScale(); float deltaScale = scale / oldScale; mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY); setImageMatrix(getImageViewMatrix()); center(true, true); } /** * Zoom to. * * @param scale the scale * @param centerX the center x * @param centerY the center y * @param durationMs the duration ms */ protected void zoomTo(final float scale, final float centerX, final float centerY, final float durationMs) { final float incrementPerMs = (scale - getScale()) / durationMs; final float oldScale = getScale(); final long startTime = System.currentTimeMillis(); mHandler.post(new Runnable() { public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min(durationMs, now - startTime); float target = oldScale + (incrementPerMs * currentMs); zoomTo(target, centerX, centerY); if (currentMs < durationMs) { mHandler.post(this); } } }); } /** * Zoom to. * * @param scale the scale */ protected void zoomTo(float scale) { float cx = getWidth() / 2F; float cy = getHeight() / 2F; zoomTo(scale, cx, cy); } /** * Zoom in. <SUF>*/ protected void zoomIn() { zoomIn(SCALE_RATE); } /** * Zoom out. */ protected void zoomOut() { zoomOut(SCALE_RATE); } /** * Zoom in. * * @param rate the rate */ protected void zoomIn(float rate) { if (getScale() >= mMaxZoom) { return; // Don't let the user zoom into the molecular level. } if (mBitmapDisplayed.getBitmap() == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; mSuppMatrix.postScale(rate, rate, cx, cy); setImageMatrix(getImageViewMatrix()); } /** * Zoom out. * * @param rate the rate */ protected void zoomOut(float rate) { if (mBitmapDisplayed.getBitmap() == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; // Zoom out to at most 1x. Matrix tmp = new Matrix(mSuppMatrix); tmp.postScale(1F / rate, 1F / rate, cx, cy); if (getScale(tmp) < 1F) { mSuppMatrix.setScale(1F, 1F, cx, cy); } else { mSuppMatrix.postScale(1F / rate, 1F / rate, cx, cy); } setImageMatrix(getImageViewMatrix()); center(true, true); } /** * Post translate. * * @param dx the dx * @param dy the dy */ protected void postTranslate(float dx, float dy) { mSuppMatrix.postTranslate(dx, dy); } /** * Pan by. * * @param dx the dx * @param dy the dy */ protected void panBy(float dx, float dy) { postTranslate(dx, dy); setImageMatrix(getImageViewMatrix()); } }
109203_40
//serverObjects.java //----------------------- //(C) by Michael Peter Christen; [email protected] //first published on http://www.anomic.de //Frankfurt, Germany, 2004 //(C) changes by Bjoern 'fuchs' Krombholz // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // //This program 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 2 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 General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /* Why do we need this Class? The purpose of this class is to provide a hashtable object to the server and implementing interfaces. Values to and from cgi pages are encapsulated in this object. The server shall be executable in a Java 1.0 environment, so the following other options did not comply: Properties - setProperty would be needed, but only available in 1.2 HashMap, TreeMap - only in 1.2 Hashtable - available in 1.0, but 'put' does not accept null values //FIXME: it's 2012, do we still need support for Java 1.0?! So this class was created as a convenience. It will also contain special methods that read data from internet-resources in the background, while data can already be read out of the object. This shall speed up usage when a slow internet connection is used (dial-up) */ package net.yacy.server; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import net.yacy.cora.document.encoding.UTF8; import net.yacy.cora.document.id.MultiProtocolURL; import net.yacy.cora.protocol.RequestHeader; import net.yacy.cora.protocol.RequestHeader.FileType; import net.yacy.document.parser.html.CharacterCoding; import net.yacy.kelondro.util.Formatter; import net.yacy.search.Switchboard; import net.yacy.search.schema.CollectionSchema; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.FacetParams; import org.apache.solr.common.params.MultiMapSolrParams; import org.json.JSONObject; public class serverObjects implements Serializable, Cloneable { private static final long serialVersionUID = 3999165204849858546L; public static final String ACTION_AUTHENTICATE = "AUTHENTICATE"; /** Key for an URL redirection : should be associated with the redirected location. * The main servlet handles this to produce an HTTP 302 status. */ public static final String ACTION_LOCATION = "LOCATION"; public final static String ADMIN_AUTHENTICATE_MSG = "admin log-in. If you don't know the password, set it with {yacyhome}/bin/passwd.sh {newpassword}"; private final static Pattern patternNewline = Pattern.compile("\n"); private boolean localized = true; private final static char BOM = '\uFEFF'; // ByteOrderMark character that may appear at beginnings of Strings (Browser may append that) private final MultiMapSolrParams map; public serverObjects() { super(); this.map = new MultiMapSolrParams(new HashMap<String, String[]>()); } protected serverObjects(serverObjects o) { super(); this.map = o.map; } protected serverObjects(final Map<String, String[]> input) { super(); this.map = new MultiMapSolrParams(input); } public void authenticationRequired() { this.put(ACTION_AUTHENTICATE, ADMIN_AUTHENTICATE_MSG); } public int size() { return this.map.toNamedList().size() / 2; } public void clear() { this.map.getMap().clear(); } public boolean isEmpty() { return this.map.getMap().isEmpty(); } private static final String removeByteOrderMark(final String s) { if (s == null || s.isEmpty()) return s; if (s.charAt(0) == BOM) return s.substring(1); return s; } public boolean containsKey(String key) { String[] arr = this.map.getParams(key); return arr != null && arr.length > 0; } public MultiMapSolrParams getSolrParams() { return this.map; } public List<Map.Entry<String, String>> entrySet() { List<Map.Entry<String, String>> set = new ArrayList<Map.Entry<String, String>>(this.map.getMap().size() * 2); Set<Map.Entry<String, String[]>> mset = this.map.getMap().entrySet(); for (Map.Entry<String, String[]> entry: mset) { String[] vlist = entry.getValue(); for (String v: vlist) set.add(new AbstractMap.SimpleEntry<String, String>(entry.getKey(), v)); } return set; } public Set<String> values() { Set<String> set = new HashSet<String>(this.map.getMap().size() * 2); for (Map.Entry<String, String[]> entry: this.map.getMap().entrySet()) { for (String v: entry.getValue()) set.add(v); } return set; } public Set<String> keySet() { return this.map.getMap().keySet(); } public String[] remove(String key) { return this.map.getMap().remove(key); } public int remove(String key, int dflt) { final String result = removeByteOrderMark(get(key)); this.map.getMap().remove(key); if (result == null) return dflt; try { return Integer.parseInt(result); } catch (final NumberFormatException e) { return dflt; } } public void putAll(Map<String, String> m) { for (Map.Entry<String, String> e: m.entrySet()) { put(e.getKey(), e.getValue()); } } public void add(final String key, final String value) { if (key == null) { // this does nothing return; } if (value == null) { return; } String[] a = map.getMap().get(key); if (a == null) { map.getMap().put(key, new String[]{value}); return; } for (int i = 0; i < a.length; i++) { if (a[i].equals(value)) return; // double-check } String[] aa = new String[a.length + 1]; System.arraycopy(a, 0, aa, 0, a.length); aa[a.length] = value; map.getMap().put(key, aa); return; } public void put(final String key, final boolean value) { put(key, value ? "1" : "0"); } public void put(final String key, final String value) { if (key == null) { // this does nothing return; } if (value == null) { // assigning the null value creates the same effect like removing the element map.getMap().remove(key); return; } String[] a = map.getMap().get(key); if (a == null) { map.getMap().put(key, new String[]{value}); return; } map.getMap().put(key, new String[]{value}); } public void add(final String key, final byte[] value) { if (value == null) return; add(key, UTF8.String(value)); } public void put(final String key, final byte[] value) { if (value == null) return; put(key, UTF8.String(value)); } public void put(final String key, final String[] values) { if (key == null) { // this does nothing return; } else if (values == null) { // assigning the null value creates the same effect like removing the element map.getMap().remove(key); return; } else { map.getMap().put(key, values); } } /** * Add an unformatted String representation of a double/float value * to the map. * @param key key name as String. * @param value value as double/float. */ public void put(final String key, final float value) { put(key, Float.toString(value)); } public void put(final String key, final double value) { put(key, Double.toString(value)); } /** * same as {@link #put(String, double)} but for integer types */ public void put(final String key, final long value) { put(key, Long.toString(value)); } public void put(final String key, final java.util.Date value) { put(key, value.toString()); } public void put(final String key, final InetAddress value) { put(key, value.toString()); } /** * Add a String to the map. The content of the String is escaped to be usable in JSON output. * @param key key name as String. * @param value a String that will be reencoded for JSON output. */ public void putJSON(final String key, String value) { value = JSONObject.quote(value); value = value.substring(1, value.length() - 1); put(key, value); } /** * Add a String to the map. The content of the string is first decoded to removed any URL encoding (application/x-www-form-urlencoded). * Then the content of the String is escaped to be usable in HTML output. * @param key key name as String. * @param value a String that will be reencoded for HTML output. * @see CharacterCoding#encodeUnicode2html(String, boolean) */ public void putHTML(final String key, final String value) { put(key, value == null ? "" : CharacterCoding.unicode2html(UTF8.decodeURL(value), true)); } /** * Add a String UTF-8 encoded bytes to the map. The content of the string is first decoded to removed any URL encoding (application/x-www-form-urlencoded). * Then the content of the String is escaped to be usable in HTML output. * @param key key name as String. * @param value the UTF-8 encoded byte array of a String that will be reencoded for HTML output. * @see CharacterCoding#encodeUnicode2html(String, boolean) */ public void putHTML(final String key, final byte[] value) { putHTML(key, value == null ? "" : UTF8.String(value)); } /** * Add a String to the map. The eventual URL encoding * (application/x-www-form-urlencoded) is retained, but the String is still * escaped to be usable in HTML output. * * @param key key name as String. * @param value a String that will be reencoded for HTML output. * @see CharacterCoding#encodeUnicode2html(String, boolean) */ public void putUrlEncodedHTML(final String key, final String value) { put(key, value == null ? "" : CharacterCoding.unicode2html(value, true)); } /** * Like {@link #putHTML(String, String)} but takes an extra argument defining, if the returned * String should be used in normal HTML: <code>false</code>. * If forXML is <code>true</code>, then only the characters <b>&amp; &quot; &lt; &gt;</b> will be * replaced in the returned String. */ public void putXML(final String key, final String value) { put(key, value == null ? "" : CharacterCoding.unicode2xml(value, true)); } /** * Put the key/value pair, escaping characters depending on the target fileType. When the target is HTML, the content of the string is first decoded to removed any URL encoding (application/x-www-form-urlencoded). * @param fileType the response target file type * @param key * @param value */ public void put(final RequestHeader.FileType fileType, final String key, final String value) { if (fileType == FileType.JSON) putJSON(key, value == null ? "" : value); else if (fileType == FileType.XML) putXML(key, value == null ? "" : value); else putHTML(key, value == null ? "" : value); } /** * Put the key/value pair, escaping characters depending on the target fileType. * The eventual URL encoding (application/x-www-form-urlencoded) is retained. * * @param fileType the response target file type * @param key * @param value */ public void putUrlEncoded(final RequestHeader.FileType fileType, final String key, final String value) { if (fileType == FileType.JSON) { putJSON(key, value == null ? "" : value); } else if (fileType == FileType.XML) { putXML(key, value == null ? "" : value); } else { putUrlEncodedHTML(key, value == null ? "" : value); } } /** * Add a byte/long/integer to the map. The number will be encoded into a String using * a localized format specified by {@link Formatter} and {@link #setLocalized(boolean)}. * @param key key name as String. * @param value integer type value to be added to the map in its formatted String * representation. * @return the String value added to the map. */ public void putNum(final String key, final long value) { this.put(key, Formatter.number(value, this.localized)); } /** * Variant for double/float types. * @see #putNum(String, long) */ public void putNum(final String key, final double value) { this.put(key, Formatter.number(value, this.localized)); } /** * Variant for string encoded numbers. * @see #putNum(String, long) */ public void putNum(final String key, final String value) { this.put(key, value == null ? "" : Formatter.number(value)); } /** * Add a String to the map. The content of the String is first parsed and interpreted as Wiki code. * @param hostport (optional) peer host and port, added when not empty as the base of relative Wiki link URLs. * @param key key name as String. * @param wikiCode wiki code content as String. */ public void putWiki(final String hostport, final String key, final String wikiCode){ this.put(key, Switchboard.wikiParser.transform(hostport, wikiCode)); } /** * Add a String to the map. The content of the String is first parsed and interpreted as Wiki code. * @param key key name as String. * @param wikiCode wiki code content as String. */ public void putWiki(final String key, final String wikiCode){ this.putWiki(null, key, wikiCode); } /** * Add a byte array to the map. The content of the array is first parsed and interpreted as Wiki code. * @param hostport (optional) peer host and port, added when not empty as the base of relative Wiki link URLs. * @param key key name as String. * @param wikiCode wiki code content as byte array. */ public void putWiki(final String hostport, final String key, final byte[] wikiCode) { try { this.put(key, Switchboard.wikiParser.transform(hostport, wikiCode)); } catch (final UnsupportedEncodingException e) { this.put(key, "Internal error pasting wiki-code: " + e.getMessage()); } } /** * Add a byte array to the map. The content of the array is first parsed and interpreted as Wiki code. * @param key key name as String. * @param wikiCode wiki code content as byte array. */ public void putWiki(final String key, final byte[] wikiCode) { this.putWiki(null, key, wikiCode); } // inc variant: for counters public long inc(final String key) { String c = get(key); if (c == null) c = "0"; final long l = Long.parseLong(c) + 1; put(key, Long.toString(l)); return l; } public String[] getParams(String name) { return map.getMap().get(name); } public String get(String name) { String[] arr = map.getMap().get(name); return arr == null || arr.length == 0 ? null : arr[0]; } // new get with default objects public Object get(final String key, final Object dflt) { final Object result = get(key); return (result == null) ? dflt : result; } // string variant public String get(final String key, final String dflt) { final String result = removeByteOrderMark(get(key)); return (result == null) ? dflt : result; } public int getInt(final String key, final int dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Integer.parseInt(s); } catch (final NumberFormatException e) { return dflt; } } public long getLong(final String key, final long dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Long.parseLong(s); } catch (final NumberFormatException e) { return dflt; } } public float getFloat(final String key, final float dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Float.parseFloat(s); } catch (final NumberFormatException e) { return dflt; } } public double getDouble(final String key, final double dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Double.parseDouble(s); } catch (final NumberFormatException e) { return dflt; } } /** * get the boolean value of a post field * DO NOT INTRODUCE A DEFAULT FIELD HERE, * this is an application for html checkboxes which do not appear * in the post if they are not selected. * Therefore the default value MUST be always FALSE. * @param key * @return the boolean value of a field or false, if the field does not appear. */ public boolean getBoolean(final String key) { String s = removeByteOrderMark(get(key)); if (s == null) return false; s = s.toLowerCase(Locale.ROOT); return s.equals("true") || s.equals("on") || s.equals("1"); } /** * @param keyMapper a regular expression for keys matching * @return a set of all values where their key mappes the keyMapper * @throws PatternSyntaxException when the keyMapper syntax is not valid */ public String[] getAll(final String keyMapper) throws PatternSyntaxException { // the keyMapper may contain regular expressions as defined in String.matches // this method is particulary useful when parsing the result of checkbox forms final List<String> v = new ArrayList<String>(); final Pattern keyPattern = Pattern.compile(keyMapper); for (final Map.Entry<String, String> entry: entrySet()) { if (keyPattern.matcher(entry.getKey()).matches()) { v.add(entry.getValue()); } } return v.toArray(new String[0]); } /** * @param keyMapper a regular expression for keys matching * @return a map of keys/values where keys matches the keyMapper * @throws PatternSyntaxException when the keyMapper syntax is not valid */ public Map<String, String> getMatchingEntries(final String keyMapper) throws PatternSyntaxException { // the keyMapper may contain regular expressions as defined in String.matches // this method is particulary useful when parsing the result of checkbox forms final Pattern keyPattern = Pattern.compile(keyMapper); final Map<String, String> map = new HashMap<>(); for (final Map.Entry<String, String> entry: entrySet()) { if (keyPattern.matcher(entry.getKey()).matches()) { map.put(entry.getKey(), entry.getValue()); } } return map; } // put all elements of another hashtable into the own table public void putAll(final serverObjects add) { for (final Map.Entry<String, String> entry: add.entrySet()) { put(entry.getKey(), entry.getValue()); } } // convenience methods for storing and loading to a file system public void store(final File f) throws IOException { BufferedOutputStream fos = null; try { fos = new BufferedOutputStream(new FileOutputStream(f)); final StringBuilder line = new StringBuilder(64); for (final Map.Entry<String, String> entry : entrySet()) { line.delete(0, line.length()); line.append(entry.getKey()); line.append("="); line.append(patternNewline.matcher(entry.getValue()).replaceAll("\\\\n")); line.append("\r\n"); fos.write(UTF8.getBytes(line.toString())); } } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (final Exception e){} } } } /** * Defines the localization state of this object. * Currently it is used for numbers added with the putNum() methods only. * @param loc if <code>true</code> store numbers in a localized format, otherwise * use a default english locale without grouping. * @see Formatter#setLocale(String) */ public void setLocalized(final boolean loc) { this.localized = loc; } @Override public Object clone() { return new serverObjects(this.map.getMap()); } /** * output the objects in a HTTP GET syntax */ @Override public String toString() { if (this.map.getMap().isEmpty()) return ""; final StringBuilder param = new StringBuilder(this.map.getMap().size() * 40); for (final Map.Entry<String, String> entry: entrySet()) { param.append(MultiProtocolURL.escape(entry.getKey())) .append('=') .append(MultiProtocolURL.escape(entry.getValue())) .append('&'); } param.setLength(param.length() - 1); return param.toString(); } public MultiMapSolrParams toSolrParams(CollectionSchema[] facets) { // check if all required post fields are there if (!this.containsKey(CommonParams.DF)) this.put(CommonParams.DF, CollectionSchema.text_t.getSolrFieldName()); // set default field to the text field if (!this.containsKey(CommonParams.START)) this.put(CommonParams.START, "0"); // set default start item if (!this.containsKey(CommonParams.ROWS)) this.put(CommonParams.ROWS, "10"); // set default number of search results if (facets != null && facets.length > 0) { this.remove("facet"); this.put("facet", "true"); for (int i = 0; i < facets.length; i++) this.add(FacetParams.FACET_FIELD, facets[i].getSolrFieldName()); } return this.map; } }
yacy/yacy_search_server
source/net/yacy/server/serverObjects.java
6,683
// new get with default objects
line_comment
nl
//serverObjects.java //----------------------- //(C) by Michael Peter Christen; [email protected] //first published on http://www.anomic.de //Frankfurt, Germany, 2004 //(C) changes by Bjoern 'fuchs' Krombholz // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // //This program 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 2 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 General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /* Why do we need this Class? The purpose of this class is to provide a hashtable object to the server and implementing interfaces. Values to and from cgi pages are encapsulated in this object. The server shall be executable in a Java 1.0 environment, so the following other options did not comply: Properties - setProperty would be needed, but only available in 1.2 HashMap, TreeMap - only in 1.2 Hashtable - available in 1.0, but 'put' does not accept null values //FIXME: it's 2012, do we still need support for Java 1.0?! So this class was created as a convenience. It will also contain special methods that read data from internet-resources in the background, while data can already be read out of the object. This shall speed up usage when a slow internet connection is used (dial-up) */ package net.yacy.server; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import net.yacy.cora.document.encoding.UTF8; import net.yacy.cora.document.id.MultiProtocolURL; import net.yacy.cora.protocol.RequestHeader; import net.yacy.cora.protocol.RequestHeader.FileType; import net.yacy.document.parser.html.CharacterCoding; import net.yacy.kelondro.util.Formatter; import net.yacy.search.Switchboard; import net.yacy.search.schema.CollectionSchema; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.FacetParams; import org.apache.solr.common.params.MultiMapSolrParams; import org.json.JSONObject; public class serverObjects implements Serializable, Cloneable { private static final long serialVersionUID = 3999165204849858546L; public static final String ACTION_AUTHENTICATE = "AUTHENTICATE"; /** Key for an URL redirection : should be associated with the redirected location. * The main servlet handles this to produce an HTTP 302 status. */ public static final String ACTION_LOCATION = "LOCATION"; public final static String ADMIN_AUTHENTICATE_MSG = "admin log-in. If you don't know the password, set it with {yacyhome}/bin/passwd.sh {newpassword}"; private final static Pattern patternNewline = Pattern.compile("\n"); private boolean localized = true; private final static char BOM = '\uFEFF'; // ByteOrderMark character that may appear at beginnings of Strings (Browser may append that) private final MultiMapSolrParams map; public serverObjects() { super(); this.map = new MultiMapSolrParams(new HashMap<String, String[]>()); } protected serverObjects(serverObjects o) { super(); this.map = o.map; } protected serverObjects(final Map<String, String[]> input) { super(); this.map = new MultiMapSolrParams(input); } public void authenticationRequired() { this.put(ACTION_AUTHENTICATE, ADMIN_AUTHENTICATE_MSG); } public int size() { return this.map.toNamedList().size() / 2; } public void clear() { this.map.getMap().clear(); } public boolean isEmpty() { return this.map.getMap().isEmpty(); } private static final String removeByteOrderMark(final String s) { if (s == null || s.isEmpty()) return s; if (s.charAt(0) == BOM) return s.substring(1); return s; } public boolean containsKey(String key) { String[] arr = this.map.getParams(key); return arr != null && arr.length > 0; } public MultiMapSolrParams getSolrParams() { return this.map; } public List<Map.Entry<String, String>> entrySet() { List<Map.Entry<String, String>> set = new ArrayList<Map.Entry<String, String>>(this.map.getMap().size() * 2); Set<Map.Entry<String, String[]>> mset = this.map.getMap().entrySet(); for (Map.Entry<String, String[]> entry: mset) { String[] vlist = entry.getValue(); for (String v: vlist) set.add(new AbstractMap.SimpleEntry<String, String>(entry.getKey(), v)); } return set; } public Set<String> values() { Set<String> set = new HashSet<String>(this.map.getMap().size() * 2); for (Map.Entry<String, String[]> entry: this.map.getMap().entrySet()) { for (String v: entry.getValue()) set.add(v); } return set; } public Set<String> keySet() { return this.map.getMap().keySet(); } public String[] remove(String key) { return this.map.getMap().remove(key); } public int remove(String key, int dflt) { final String result = removeByteOrderMark(get(key)); this.map.getMap().remove(key); if (result == null) return dflt; try { return Integer.parseInt(result); } catch (final NumberFormatException e) { return dflt; } } public void putAll(Map<String, String> m) { for (Map.Entry<String, String> e: m.entrySet()) { put(e.getKey(), e.getValue()); } } public void add(final String key, final String value) { if (key == null) { // this does nothing return; } if (value == null) { return; } String[] a = map.getMap().get(key); if (a == null) { map.getMap().put(key, new String[]{value}); return; } for (int i = 0; i < a.length; i++) { if (a[i].equals(value)) return; // double-check } String[] aa = new String[a.length + 1]; System.arraycopy(a, 0, aa, 0, a.length); aa[a.length] = value; map.getMap().put(key, aa); return; } public void put(final String key, final boolean value) { put(key, value ? "1" : "0"); } public void put(final String key, final String value) { if (key == null) { // this does nothing return; } if (value == null) { // assigning the null value creates the same effect like removing the element map.getMap().remove(key); return; } String[] a = map.getMap().get(key); if (a == null) { map.getMap().put(key, new String[]{value}); return; } map.getMap().put(key, new String[]{value}); } public void add(final String key, final byte[] value) { if (value == null) return; add(key, UTF8.String(value)); } public void put(final String key, final byte[] value) { if (value == null) return; put(key, UTF8.String(value)); } public void put(final String key, final String[] values) { if (key == null) { // this does nothing return; } else if (values == null) { // assigning the null value creates the same effect like removing the element map.getMap().remove(key); return; } else { map.getMap().put(key, values); } } /** * Add an unformatted String representation of a double/float value * to the map. * @param key key name as String. * @param value value as double/float. */ public void put(final String key, final float value) { put(key, Float.toString(value)); } public void put(final String key, final double value) { put(key, Double.toString(value)); } /** * same as {@link #put(String, double)} but for integer types */ public void put(final String key, final long value) { put(key, Long.toString(value)); } public void put(final String key, final java.util.Date value) { put(key, value.toString()); } public void put(final String key, final InetAddress value) { put(key, value.toString()); } /** * Add a String to the map. The content of the String is escaped to be usable in JSON output. * @param key key name as String. * @param value a String that will be reencoded for JSON output. */ public void putJSON(final String key, String value) { value = JSONObject.quote(value); value = value.substring(1, value.length() - 1); put(key, value); } /** * Add a String to the map. The content of the string is first decoded to removed any URL encoding (application/x-www-form-urlencoded). * Then the content of the String is escaped to be usable in HTML output. * @param key key name as String. * @param value a String that will be reencoded for HTML output. * @see CharacterCoding#encodeUnicode2html(String, boolean) */ public void putHTML(final String key, final String value) { put(key, value == null ? "" : CharacterCoding.unicode2html(UTF8.decodeURL(value), true)); } /** * Add a String UTF-8 encoded bytes to the map. The content of the string is first decoded to removed any URL encoding (application/x-www-form-urlencoded). * Then the content of the String is escaped to be usable in HTML output. * @param key key name as String. * @param value the UTF-8 encoded byte array of a String that will be reencoded for HTML output. * @see CharacterCoding#encodeUnicode2html(String, boolean) */ public void putHTML(final String key, final byte[] value) { putHTML(key, value == null ? "" : UTF8.String(value)); } /** * Add a String to the map. The eventual URL encoding * (application/x-www-form-urlencoded) is retained, but the String is still * escaped to be usable in HTML output. * * @param key key name as String. * @param value a String that will be reencoded for HTML output. * @see CharacterCoding#encodeUnicode2html(String, boolean) */ public void putUrlEncodedHTML(final String key, final String value) { put(key, value == null ? "" : CharacterCoding.unicode2html(value, true)); } /** * Like {@link #putHTML(String, String)} but takes an extra argument defining, if the returned * String should be used in normal HTML: <code>false</code>. * If forXML is <code>true</code>, then only the characters <b>&amp; &quot; &lt; &gt;</b> will be * replaced in the returned String. */ public void putXML(final String key, final String value) { put(key, value == null ? "" : CharacterCoding.unicode2xml(value, true)); } /** * Put the key/value pair, escaping characters depending on the target fileType. When the target is HTML, the content of the string is first decoded to removed any URL encoding (application/x-www-form-urlencoded). * @param fileType the response target file type * @param key * @param value */ public void put(final RequestHeader.FileType fileType, final String key, final String value) { if (fileType == FileType.JSON) putJSON(key, value == null ? "" : value); else if (fileType == FileType.XML) putXML(key, value == null ? "" : value); else putHTML(key, value == null ? "" : value); } /** * Put the key/value pair, escaping characters depending on the target fileType. * The eventual URL encoding (application/x-www-form-urlencoded) is retained. * * @param fileType the response target file type * @param key * @param value */ public void putUrlEncoded(final RequestHeader.FileType fileType, final String key, final String value) { if (fileType == FileType.JSON) { putJSON(key, value == null ? "" : value); } else if (fileType == FileType.XML) { putXML(key, value == null ? "" : value); } else { putUrlEncodedHTML(key, value == null ? "" : value); } } /** * Add a byte/long/integer to the map. The number will be encoded into a String using * a localized format specified by {@link Formatter} and {@link #setLocalized(boolean)}. * @param key key name as String. * @param value integer type value to be added to the map in its formatted String * representation. * @return the String value added to the map. */ public void putNum(final String key, final long value) { this.put(key, Formatter.number(value, this.localized)); } /** * Variant for double/float types. * @see #putNum(String, long) */ public void putNum(final String key, final double value) { this.put(key, Formatter.number(value, this.localized)); } /** * Variant for string encoded numbers. * @see #putNum(String, long) */ public void putNum(final String key, final String value) { this.put(key, value == null ? "" : Formatter.number(value)); } /** * Add a String to the map. The content of the String is first parsed and interpreted as Wiki code. * @param hostport (optional) peer host and port, added when not empty as the base of relative Wiki link URLs. * @param key key name as String. * @param wikiCode wiki code content as String. */ public void putWiki(final String hostport, final String key, final String wikiCode){ this.put(key, Switchboard.wikiParser.transform(hostport, wikiCode)); } /** * Add a String to the map. The content of the String is first parsed and interpreted as Wiki code. * @param key key name as String. * @param wikiCode wiki code content as String. */ public void putWiki(final String key, final String wikiCode){ this.putWiki(null, key, wikiCode); } /** * Add a byte array to the map. The content of the array is first parsed and interpreted as Wiki code. * @param hostport (optional) peer host and port, added when not empty as the base of relative Wiki link URLs. * @param key key name as String. * @param wikiCode wiki code content as byte array. */ public void putWiki(final String hostport, final String key, final byte[] wikiCode) { try { this.put(key, Switchboard.wikiParser.transform(hostport, wikiCode)); } catch (final UnsupportedEncodingException e) { this.put(key, "Internal error pasting wiki-code: " + e.getMessage()); } } /** * Add a byte array to the map. The content of the array is first parsed and interpreted as Wiki code. * @param key key name as String. * @param wikiCode wiki code content as byte array. */ public void putWiki(final String key, final byte[] wikiCode) { this.putWiki(null, key, wikiCode); } // inc variant: for counters public long inc(final String key) { String c = get(key); if (c == null) c = "0"; final long l = Long.parseLong(c) + 1; put(key, Long.toString(l)); return l; } public String[] getParams(String name) { return map.getMap().get(name); } public String get(String name) { String[] arr = map.getMap().get(name); return arr == null || arr.length == 0 ? null : arr[0]; } // new get<SUF> public Object get(final String key, final Object dflt) { final Object result = get(key); return (result == null) ? dflt : result; } // string variant public String get(final String key, final String dflt) { final String result = removeByteOrderMark(get(key)); return (result == null) ? dflt : result; } public int getInt(final String key, final int dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Integer.parseInt(s); } catch (final NumberFormatException e) { return dflt; } } public long getLong(final String key, final long dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Long.parseLong(s); } catch (final NumberFormatException e) { return dflt; } } public float getFloat(final String key, final float dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Float.parseFloat(s); } catch (final NumberFormatException e) { return dflt; } } public double getDouble(final String key, final double dflt) { final String s = removeByteOrderMark(get(key)); if (s == null) return dflt; try { return Double.parseDouble(s); } catch (final NumberFormatException e) { return dflt; } } /** * get the boolean value of a post field * DO NOT INTRODUCE A DEFAULT FIELD HERE, * this is an application for html checkboxes which do not appear * in the post if they are not selected. * Therefore the default value MUST be always FALSE. * @param key * @return the boolean value of a field or false, if the field does not appear. */ public boolean getBoolean(final String key) { String s = removeByteOrderMark(get(key)); if (s == null) return false; s = s.toLowerCase(Locale.ROOT); return s.equals("true") || s.equals("on") || s.equals("1"); } /** * @param keyMapper a regular expression for keys matching * @return a set of all values where their key mappes the keyMapper * @throws PatternSyntaxException when the keyMapper syntax is not valid */ public String[] getAll(final String keyMapper) throws PatternSyntaxException { // the keyMapper may contain regular expressions as defined in String.matches // this method is particulary useful when parsing the result of checkbox forms final List<String> v = new ArrayList<String>(); final Pattern keyPattern = Pattern.compile(keyMapper); for (final Map.Entry<String, String> entry: entrySet()) { if (keyPattern.matcher(entry.getKey()).matches()) { v.add(entry.getValue()); } } return v.toArray(new String[0]); } /** * @param keyMapper a regular expression for keys matching * @return a map of keys/values where keys matches the keyMapper * @throws PatternSyntaxException when the keyMapper syntax is not valid */ public Map<String, String> getMatchingEntries(final String keyMapper) throws PatternSyntaxException { // the keyMapper may contain regular expressions as defined in String.matches // this method is particulary useful when parsing the result of checkbox forms final Pattern keyPattern = Pattern.compile(keyMapper); final Map<String, String> map = new HashMap<>(); for (final Map.Entry<String, String> entry: entrySet()) { if (keyPattern.matcher(entry.getKey()).matches()) { map.put(entry.getKey(), entry.getValue()); } } return map; } // put all elements of another hashtable into the own table public void putAll(final serverObjects add) { for (final Map.Entry<String, String> entry: add.entrySet()) { put(entry.getKey(), entry.getValue()); } } // convenience methods for storing and loading to a file system public void store(final File f) throws IOException { BufferedOutputStream fos = null; try { fos = new BufferedOutputStream(new FileOutputStream(f)); final StringBuilder line = new StringBuilder(64); for (final Map.Entry<String, String> entry : entrySet()) { line.delete(0, line.length()); line.append(entry.getKey()); line.append("="); line.append(patternNewline.matcher(entry.getValue()).replaceAll("\\\\n")); line.append("\r\n"); fos.write(UTF8.getBytes(line.toString())); } } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (final Exception e){} } } } /** * Defines the localization state of this object. * Currently it is used for numbers added with the putNum() methods only. * @param loc if <code>true</code> store numbers in a localized format, otherwise * use a default english locale without grouping. * @see Formatter#setLocale(String) */ public void setLocalized(final boolean loc) { this.localized = loc; } @Override public Object clone() { return new serverObjects(this.map.getMap()); } /** * output the objects in a HTTP GET syntax */ @Override public String toString() { if (this.map.getMap().isEmpty()) return ""; final StringBuilder param = new StringBuilder(this.map.getMap().size() * 40); for (final Map.Entry<String, String> entry: entrySet()) { param.append(MultiProtocolURL.escape(entry.getKey())) .append('=') .append(MultiProtocolURL.escape(entry.getValue())) .append('&'); } param.setLength(param.length() - 1); return param.toString(); } public MultiMapSolrParams toSolrParams(CollectionSchema[] facets) { // check if all required post fields are there if (!this.containsKey(CommonParams.DF)) this.put(CommonParams.DF, CollectionSchema.text_t.getSolrFieldName()); // set default field to the text field if (!this.containsKey(CommonParams.START)) this.put(CommonParams.START, "0"); // set default start item if (!this.containsKey(CommonParams.ROWS)) this.put(CommonParams.ROWS, "10"); // set default number of search results if (facets != null && facets.length > 0) { this.remove("facet"); this.put("facet", "true"); for (int i = 0; i < facets.length; i++) this.add(FacetParams.FACET_FIELD, facets[i].getSolrFieldName()); } return this.map; } }
143235_7
/* * 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.coyote; import java.io.IOException; import java.io.StringReader; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.WriteListener; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.HttpParser; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [[email protected]] * @author Jason Hunter [[email protected]] * @author James Todd [[email protected]] * @author Harish Prabandham * @author Hans Bergsten <[email protected]> * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ protected int status = 200; /** * Status message. */ protected String message = null; /** * Response headers. */ protected final MimeHeaders headers = new MimeHeaders(); /** * Associated output buffer. */ protected OutputBuffer outputBuffer; /** * Notes. */ protected final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ protected boolean commited = false; /** * Action hook. */ public ActionHook hook; /** * HTTP specific fields. */ protected String contentType = null; protected String contentLanguage = null; protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; protected long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General informations private long contentWritten = 0; private long commitTime = -1; /** * Holds request error exception. */ protected Exception errorException = null; /** * Has the charset been explicitly set. */ protected boolean charsetSet = false; protected Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public OutputBuffer getOutputBuffer() { return outputBuffer; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } public ActionHook getHook() { return hook; } public void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if( param==null ) hook.action(actionCode, this); else hook.action(actionCode, param); } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status */ public void setStatus( int status ) { this.status = status; } /** * Get the status message. */ public String getMessage() { return message; } /** * Set the status message. */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return commited; } public void setCommitted(boolean v) { if (v && !this.commited) { this.commitTime = System.currentTimeMillis(); } this.commited = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return commitTime; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during * request processing. */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during request * processing. */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return ( errorException != null ); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); } public void finish() { action(ActionCode.CLOSE, this); } public void acknowledge() { action(ActionCode.ACK, this); } // -------------------- Headers -------------------- /** * Warning: This method always returns <code>false<code> for Content-Type * and Content-Length. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.addValue(name).setString( value ); } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and * the default encoding */ public void setLocale(Locale locale) { if (locale == null) { return; // throw an exception? } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.getLanguage(); if ((contentLanguage != null) && (contentLanguage.length() > 0)) { String country = locale.getCountry(); StringBuilder value = new StringBuilder(contentLanguage); if ((country != null) && (country.length() > 0)) { value.append('-'); value.append(country); } contentLanguage = value.toString(); } } /** * Return the content language. */ public String getContentLanguage() { return contentLanguage; } /* * Overrides the name of the character encoding used in the body * of the response. This method must be called prior to writing output * using getWriter(). * * @param charset String containing the name of the character encoding. */ public void setCharacterEncoding(String charset) { if (isCommitted()) return; if (charset == null) return; characterEncoding = charset; charsetSet=true; } public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = HttpParser.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue != null) { charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { charsetSet = true; this.characterEncoding = charsetValue; } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && characterEncoding != null && charsetSet) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(int contentLength) { this.contentLength = contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. */ public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/) throws IOException { outputBuffer.doWrite(chunk, this); contentWritten+=chunk.getLength(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; charsetSet = false; contentLength = -1; status = 200; message = null; commited = false; commitTime = -1; errorException = null; headers.clear(); listener = null; // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ protected volatile WriteListener listener; private boolean fireListener = false; private boolean registeredForWrite = false; private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { action(ActionCode.DISPATCH_WRITE, null); // Need to set the fireListener flag otherwise when the container // tries to trigger onWritePossible, nothing will happen synchronized (nonBlockingStateLock) { fireListener = true; } } } public boolean isReady() { if (listener == null) { // TODO i18n throw new IllegalStateException("not in non blocking mode."); } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(false); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite(boolean internal) { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite || internal) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
yale-zhang/Tomcat-Research
java/org/apache/coyote/Response.java
4,484
/** * Response headers. */
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.coyote; import java.io.IOException; import java.io.StringReader; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.WriteListener; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.HttpParser; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [[email protected]] * @author Jason Hunter [[email protected]] * @author James Todd [[email protected]] * @author Harish Prabandham * @author Hans Bergsten <[email protected]> * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ protected int status = 200; /** * Status message. */ protected String message = null; /** * Response headers. <SUF>*/ protected final MimeHeaders headers = new MimeHeaders(); /** * Associated output buffer. */ protected OutputBuffer outputBuffer; /** * Notes. */ protected final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ protected boolean commited = false; /** * Action hook. */ public ActionHook hook; /** * HTTP specific fields. */ protected String contentType = null; protected String contentLanguage = null; protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; protected long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General informations private long contentWritten = 0; private long commitTime = -1; /** * Holds request error exception. */ protected Exception errorException = null; /** * Has the charset been explicitly set. */ protected boolean charsetSet = false; protected Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public OutputBuffer getOutputBuffer() { return outputBuffer; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } public ActionHook getHook() { return hook; } public void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if( param==null ) hook.action(actionCode, this); else hook.action(actionCode, param); } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status */ public void setStatus( int status ) { this.status = status; } /** * Get the status message. */ public String getMessage() { return message; } /** * Set the status message. */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return commited; } public void setCommitted(boolean v) { if (v && !this.commited) { this.commitTime = System.currentTimeMillis(); } this.commited = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return commitTime; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during * request processing. */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during request * processing. */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return ( errorException != null ); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); } public void finish() { action(ActionCode.CLOSE, this); } public void acknowledge() { action(ActionCode.ACK, this); } // -------------------- Headers -------------------- /** * Warning: This method always returns <code>false<code> for Content-Type * and Content-Length. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.addValue(name).setString( value ); } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and * the default encoding */ public void setLocale(Locale locale) { if (locale == null) { return; // throw an exception? } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.getLanguage(); if ((contentLanguage != null) && (contentLanguage.length() > 0)) { String country = locale.getCountry(); StringBuilder value = new StringBuilder(contentLanguage); if ((country != null) && (country.length() > 0)) { value.append('-'); value.append(country); } contentLanguage = value.toString(); } } /** * Return the content language. */ public String getContentLanguage() { return contentLanguage; } /* * Overrides the name of the character encoding used in the body * of the response. This method must be called prior to writing output * using getWriter(). * * @param charset String containing the name of the character encoding. */ public void setCharacterEncoding(String charset) { if (isCommitted()) return; if (charset == null) return; characterEncoding = charset; charsetSet=true; } public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = HttpParser.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue != null) { charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { charsetSet = true; this.characterEncoding = charsetValue; } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && characterEncoding != null && charsetSet) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(int contentLength) { this.contentLength = contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. */ public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/) throws IOException { outputBuffer.doWrite(chunk, this); contentWritten+=chunk.getLength(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; charsetSet = false; contentLength = -1; status = 200; message = null; commited = false; commitTime = -1; errorException = null; headers.clear(); listener = null; // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ protected volatile WriteListener listener; private boolean fireListener = false; private boolean registeredForWrite = false; private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { action(ActionCode.DISPATCH_WRITE, null); // Need to set the fireListener flag otherwise when the container // tries to trigger onWritePossible, nothing will happen synchronized (nonBlockingStateLock) { fireListener = true; } } } public boolean isReady() { if (listener == null) { // TODO i18n throw new IllegalStateException("not in non blocking mode."); } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(false); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite(boolean internal) { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite || internal) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
20115_66
/* * Written by Josh Bloch of Google Inc. and released to the public domain, * as explained at http://creativecommons.org/licenses/publicdomain. */ package net.tsz.afinal.core; // BEGIN android-note // removed link to collections framework docs // END android-note import java.io.*; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; /** * Resizable-array implementation of the {@link Deque} interface. Array * deques have no capacity restrictions; they grow as necessary to support * usage. They are not thread-safe; in the absence of external * synchronization, they do not support concurrent access by multiple threads. * Null elements are prohibited. This class is likely to be faster than * {@link Stack} when used as a stack, and faster than {@link LinkedList} * when used as a queue. * * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time. * Exceptions include {@link #remove(Object) remove}, {@link * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence * removeLastOccurrence}, {@link #contains contains}, {@link #iterator * iterator.remove()}, and the bulk operations, all of which run in linear * time. * * <p>The iterators returned by this class's <tt>iterator</tt> method are * <i>fail-fast</i>: If the deque is modified at any time after the iterator * is created, in any way except through the iterator's own <tt>remove</tt> * method, the iterator will generally throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * @author Josh Bloch and Doug Lea * @since 1.6 * @param <E> the type of elements held in this collection */ public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable { /** * The array in which the elements of the deque are stored. * The capacity of the deque is the length of this array, which is * always a power of two. The array is never allowed to become * full, except transiently within an addX method where it is * resized (see doubleCapacity) immediately upon becoming full, * thus avoiding head and tail wrapping around to equal each * other. We also guarantee that all array cells not holding * deque elements are always null. */ private transient E[] elements; /** * The index of the element at the head of the deque (which is the * element that would be removed by remove() or pop()); or an * arbitrary number equal to tail if the deque is empty. */ private transient int head; /** * The index at which the next element would be added to the tail * of the deque (via addLast(E), add(E), or push(E)). */ private transient int tail; /** * The minimum capacity that we'll use for a newly created deque. * Must be a power of 2. */ private static final int MIN_INITIAL_CAPACITY = 8; // ****** Array allocation and resizing utilities ****** /** * Allocate empty array to hold the given number of elements. * * @param numElements the number of elements to hold */ @SuppressWarnings("unchecked") private void allocateElements(int numElements) { int initialCapacity = MIN_INITIAL_CAPACITY; // Find the best power of two to hold elements. // Tests "<=" because arrays aren't kept full. if (numElements >= initialCapacity) { initialCapacity = numElements; initialCapacity |= (initialCapacity >>> 1); initialCapacity |= (initialCapacity >>> 2); initialCapacity |= (initialCapacity >>> 4); initialCapacity |= (initialCapacity >>> 8); initialCapacity |= (initialCapacity >>> 16); initialCapacity++; if (initialCapacity < 0) // Too many elements, must back off initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements } elements = (E[]) new Object[initialCapacity]; } /** * Double the capacity of this deque. Call only when full, i.e., * when head and tail have wrapped around to become equal. */ @SuppressWarnings("unchecked") private void doubleCapacity() { assert head == tail; int p = head; int n = elements.length; int r = n - p; // number of elements to the right of p int newCapacity = n << 1; if (newCapacity < 0) throw new IllegalStateException("Sorry, deque too big"); Object[] a = new Object[newCapacity]; System.arraycopy(elements, p, a, 0, r); System.arraycopy(elements, 0, a, r, p); elements = (E[])a; head = 0; tail = n; } /** * Copies the elements from our element array into the specified array, * in order (from first to last element in the deque). It is assumed * that the array is large enough to hold all elements in the deque. * * @return its argument */ private <T> T[] copyElements(T[] a) { if (head < tail) { System.arraycopy(elements, head, a, 0, size()); } else if (head > tail) { int headPortionLen = elements.length - head; System.arraycopy(elements, head, a, 0, headPortionLen); System.arraycopy(elements, 0, a, headPortionLen, tail); } return a; } /** * Constructs an empty array deque with an initial capacity * sufficient to hold 16 elements. */ @SuppressWarnings("unchecked") public ArrayDeque() { elements = (E[]) new Object[16]; } /** * Constructs an empty array deque with an initial capacity * sufficient to hold the specified number of elements. * * @param numElements lower bound on initial capacity of the deque */ public ArrayDeque(int numElements) { allocateElements(numElements); } /** * Constructs a deque containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. (The first element returned by the collection's * iterator becomes the first element, or <i>front</i> of the * deque.) * * @param c the collection whose elements are to be placed into the deque * @throws NullPointerException if the specified collection is null */ public ArrayDeque(Collection<? extends E> c) { allocateElements(c.size()); addAll(c); } // The main insertion and extraction methods are addFirst, // addLast, pollFirst, pollLast. The other methods are defined in // terms of these. /** * Inserts the specified element at the front of this deque. * * @param e the element to add * @throws NullPointerException if the specified element is null */ public void addFirst(E e) { if (e == null) throw new NullPointerException(); elements[head = (head - 1) & (elements.length - 1)] = e; if (head == tail) doubleCapacity(); } /** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #add}. * * @param e the element to add * @throws NullPointerException if the specified element is null */ public void addLast(E e) { if (e == null) throw new NullPointerException(); elements[tail] = e; if ( (tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity(); } /** * Inserts the specified element at the front of this deque. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Deque#offerFirst}) * @throws NullPointerException if the specified element is null */ public boolean offerFirst(E e) { addFirst(e); return true; } /** * Inserts the specified element at the end of this deque. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Deque#offerLast}) * @throws NullPointerException if the specified element is null */ public boolean offerLast(E e) { addLast(e); return true; } /** * @throws NoSuchElementException {@inheritDoc} */ public E removeFirst() { E x = pollFirst(); if (x == null) throw new NoSuchElementException(); return x; } /** * @throws NoSuchElementException {@inheritDoc} */ public E removeLast() { E x = pollLast(); if (x == null) throw new NoSuchElementException(); return x; } public E pollFirst() { int h = head; E result = elements[h]; // Element is null if deque empty if (result == null) return null; elements[h] = null; // Must null out slot head = (h + 1) & (elements.length - 1); return result; } public E pollLast() { int t = (tail - 1) & (elements.length - 1); E result = elements[t]; if (result == null) return null; elements[t] = null; tail = t; return result; } /** * @throws NoSuchElementException {@inheritDoc} */ public E getFirst() { E x = elements[head]; if (x == null) throw new NoSuchElementException(); return x; } /** * @throws NoSuchElementException {@inheritDoc} */ public E getLast() { E x = elements[(tail - 1) & (elements.length - 1)]; if (x == null) throw new NoSuchElementException(); return x; } public E peekFirst() { return elements[head]; // elements[head] is null if deque empty } public E peekLast() { return elements[(tail - 1) & (elements.length - 1)]; } /** * Removes the first occurrence of the specified element in this * deque (when traversing the deque from head to tail). * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if the deque contained the specified element */ public boolean removeFirstOccurrence(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = head; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) { delete(i); return true; } i = (i + 1) & mask; } return false; } /** * Removes the last occurrence of the specified element in this * deque (when traversing the deque from head to tail). * If the deque does not contain the element, it is unchanged. * More formally, removes the last element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if the deque contained the specified element */ public boolean removeLastOccurrence(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = (tail - 1) & mask; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) { delete(i); return true; } i = (i - 1) & mask; } return false; } // *** Queue methods *** /** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #addLast}. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws NullPointerException if the specified element is null */ public boolean add(E e) { addLast(e); return true; } /** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #offerLast}. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Queue#offer}) * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { return offerLast(e); } /** * Retrieves and removes the head of the queue represented by this deque. * * This method differs from {@link #poll poll} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #removeFirst}. * * @return the head of the queue represented by this deque * @throws NoSuchElementException {@inheritDoc} */ public E remove() { return removeFirst(); } /** * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), or returns * <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #pollFirst}. * * @return the head of the queue represented by this deque, or * <tt>null</tt> if this deque is empty */ public E poll() { return pollFirst(); } /** * Retrieves, but does not remove, the head of the queue represented by * this deque. This method differs from {@link #peek peek} only in * that it throws an exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst}. * * @return the head of the queue represented by this deque * @throws NoSuchElementException {@inheritDoc} */ public E element() { return getFirst(); } /** * Retrieves, but does not remove, the head of the queue represented by * this deque, or returns <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #peekFirst}. * * @return the head of the queue represented by this deque, or * <tt>null</tt> if this deque is empty */ public E peek() { return peekFirst(); } // *** Stack methods *** /** * Pushes an element onto the stack represented by this deque. In other * words, inserts the element at the front of this deque. * * <p>This method is equivalent to {@link #addFirst}. * * @param e the element to push * @throws NullPointerException if the specified element is null */ public void push(E e) { addFirst(e); } /** * Pops an element from the stack represented by this deque. In other * words, removes and returns the first element of this deque. * * <p>This method is equivalent to {@link #removeFirst()}. * * @return the element at the front of this deque (which is the top * of the stack represented by this deque) * @throws NoSuchElementException {@inheritDoc} */ public E pop() { return removeFirst(); } private void checkInvariants() { assert elements[tail] == null; assert head == tail ? elements[head] == null : (elements[head] != null && elements[(tail - 1) & (elements.length - 1)] != null); assert elements[(head - 1) & (elements.length - 1)] == null; } /** * Removes the element at the specified position in the elements array, * adjusting head and tail as necessary. This can result in motion of * elements backwards or forwards in the array. * * <p>This method is called delete rather than remove to emphasize * that its semantics differ from those of {@link List#remove(int)}. * * @return true if elements moved backwards */ private boolean delete(int i) { checkInvariants(); final E[] elements = this.elements; final int mask = elements.length - 1; final int h = head; final int t = tail; final int front = (i - h) & mask; final int back = (t - i) & mask; // Invariant: head <= i < tail mod circularity if (front >= ((t - h) & mask)) throw new ConcurrentModificationException(); // Optimize for least element motion if (front < back) { if (h <= i) { System.arraycopy(elements, h, elements, h + 1, front); } else { // Wrap around System.arraycopy(elements, 0, elements, 1, i); elements[0] = elements[mask]; System.arraycopy(elements, h, elements, h + 1, mask - h); } elements[h] = null; head = (h + 1) & mask; return false; } else { if (i < t) { // Copy the null tail as well System.arraycopy(elements, i + 1, elements, i, back); tail = t - 1; } else { // Wrap around System.arraycopy(elements, i + 1, elements, i, mask - i); elements[mask] = elements[0]; System.arraycopy(elements, 1, elements, 0, t); tail = (t - 1) & mask; } return true; } } // *** Collection Methods *** /** * Returns the number of elements in this deque. * * @return the number of elements in this deque */ public int size() { return (tail - head) & (elements.length - 1); } /** * Returns <tt>true</tt> if this deque contains no elements. * * @return <tt>true</tt> if this deque contains no elements */ public boolean isEmpty() { return head == tail; } /** * Returns an iterator over the elements in this deque. The elements * will be ordered from first (head) to last (tail). This is the same * order that elements would be dequeued (via successive calls to * {@link #remove} or popped (via successive calls to {@link #pop}). * * @return an iterator over the elements in this deque */ public Iterator<E> iterator() { return new DeqIterator(); } public Iterator<E> descendingIterator() { return new DescendingIterator(); } private class DeqIterator implements Iterator<E> { /** * Index of element to be returned by subsequent call to next. */ private int cursor = head; /** * Tail recorded at construction (also in remove), to stop * iterator and also to check for comodification. */ private int fence = tail; /** * Index of element returned by most recent call to next. * Reset to -1 if element is deleted by a call to remove. */ private int lastRet = -1; public boolean hasNext() { return cursor != fence; } public E next() { if (cursor == fence) throw new NoSuchElementException(); E result = elements[cursor]; // This check doesn't catch all possible comodifications, // but does catch the ones that corrupt traversal if (tail != fence || result == null) throw new ConcurrentModificationException(); lastRet = cursor; cursor = (cursor + 1) & (elements.length - 1); return result; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); if (delete(lastRet)) { // if left-shifted, undo increment in next() cursor = (cursor - 1) & (elements.length - 1); fence = tail; } lastRet = -1; } } private class DescendingIterator implements Iterator<E> { /* * This class is nearly a mirror-image of DeqIterator, using * tail instead of head for initial cursor, and head instead of * tail for fence. */ private int cursor = tail; private int fence = head; private int lastRet = -1; public boolean hasNext() { return cursor != fence; } public E next() { if (cursor == fence) throw new NoSuchElementException(); cursor = (cursor - 1) & (elements.length - 1); E result = elements[cursor]; if (head != fence || result == null) throw new ConcurrentModificationException(); lastRet = cursor; return result; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); if (!delete(lastRet)) { cursor = (cursor + 1) & (elements.length - 1); fence = head; } lastRet = -1; } } /** * Returns <tt>true</tt> if this deque contains the specified element. * More formally, returns <tt>true</tt> if and only if this deque contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * * @param o object to be checked for containment in this deque * @return <tt>true</tt> if this deque contains the specified element */ public boolean contains(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = head; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) return true; i = (i + 1) & mask; } return false; } /** * Removes a single instance of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p>This method is equivalent to {@link #removeFirstOccurrence}. * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if this deque contained the specified element */ public boolean remove(Object o) { return removeFirstOccurrence(o); } /** * Removes all of the elements from this deque. * The deque will be empty after this call returns. */ public void clear() { int h = head; int t = tail; if (h != t) { // clear all cells head = tail = 0; int i = h; int mask = elements.length - 1; do { elements[i] = null; i = (i + 1) & mask; } while (i != t); } } /** * Returns an array containing all of the elements in this deque * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this deque. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this deque */ public Object[] toArray() { return copyElements(new Object[size()]); } /** * Returns an array containing all of the elements in this deque in * proper sequence (from first to last element); the runtime type of the * returned array is that of the specified array. If the deque fits in * the specified array, it is returned therein. Otherwise, a new array * is allocated with the runtime type of the specified array and the * size of this deque. * * <p>If this deque fits in the specified array with room to spare * (i.e., the array has more elements than this deque), the element in * the array immediately following the end of the deque is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a deque known to contain only strings. * The following code can be used to dump the deque into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * * @param a the array into which the elements of the deque are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this deque * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this deque * @throws NullPointerException if the specified array is null */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { int size = size(); if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); copyElements(a); if (a.length > size) a[size] = null; return a; } // *** Object methods *** /** * Returns a copy of this deque. * * @return a copy of this deque */ public ArrayDeque<E> clone() { try { @SuppressWarnings("unchecked") ArrayDeque<E> result = (ArrayDeque<E>) super.clone(); result.elements = Arrays.copyOf(elements, elements.length); return result; } catch (CloneNotSupportedException e) { throw new AssertionError(); } } /** * Appease the serialization gods. */ private static final long serialVersionUID = 2340985798034038923L; /** * Serialize this deque. * * @serialData The current size (<tt>int</tt>) of the deque, * followed by all of its elements (each an object reference) in * first-to-last order. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // Write out size s.writeInt(size()); // Write out elements in order. int mask = elements.length - 1; for (int i = head; i != tail; i = (i + 1) & mask) s.writeObject(elements[i]); } /** * Deserialize this deque. */ @SuppressWarnings("unchecked") private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // Read in size and allocate array int size = s.readInt(); allocateElements(size); head = 0; tail = size; // Read in all elements in the proper order. for (int i = 0; i < size; i++) elements[i] = (E)s.readObject(); } }
yangfuhai/afinal
src/net/tsz/afinal/core/ArrayDeque.java
7,873
// *** Object methods ***
line_comment
nl
/* * Written by Josh Bloch of Google Inc. and released to the public domain, * as explained at http://creativecommons.org/licenses/publicdomain. */ package net.tsz.afinal.core; // BEGIN android-note // removed link to collections framework docs // END android-note import java.io.*; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; /** * Resizable-array implementation of the {@link Deque} interface. Array * deques have no capacity restrictions; they grow as necessary to support * usage. They are not thread-safe; in the absence of external * synchronization, they do not support concurrent access by multiple threads. * Null elements are prohibited. This class is likely to be faster than * {@link Stack} when used as a stack, and faster than {@link LinkedList} * when used as a queue. * * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time. * Exceptions include {@link #remove(Object) remove}, {@link * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence * removeLastOccurrence}, {@link #contains contains}, {@link #iterator * iterator.remove()}, and the bulk operations, all of which run in linear * time. * * <p>The iterators returned by this class's <tt>iterator</tt> method are * <i>fail-fast</i>: If the deque is modified at any time after the iterator * is created, in any way except through the iterator's own <tt>remove</tt> * method, the iterator will generally throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * @author Josh Bloch and Doug Lea * @since 1.6 * @param <E> the type of elements held in this collection */ public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable { /** * The array in which the elements of the deque are stored. * The capacity of the deque is the length of this array, which is * always a power of two. The array is never allowed to become * full, except transiently within an addX method where it is * resized (see doubleCapacity) immediately upon becoming full, * thus avoiding head and tail wrapping around to equal each * other. We also guarantee that all array cells not holding * deque elements are always null. */ private transient E[] elements; /** * The index of the element at the head of the deque (which is the * element that would be removed by remove() or pop()); or an * arbitrary number equal to tail if the deque is empty. */ private transient int head; /** * The index at which the next element would be added to the tail * of the deque (via addLast(E), add(E), or push(E)). */ private transient int tail; /** * The minimum capacity that we'll use for a newly created deque. * Must be a power of 2. */ private static final int MIN_INITIAL_CAPACITY = 8; // ****** Array allocation and resizing utilities ****** /** * Allocate empty array to hold the given number of elements. * * @param numElements the number of elements to hold */ @SuppressWarnings("unchecked") private void allocateElements(int numElements) { int initialCapacity = MIN_INITIAL_CAPACITY; // Find the best power of two to hold elements. // Tests "<=" because arrays aren't kept full. if (numElements >= initialCapacity) { initialCapacity = numElements; initialCapacity |= (initialCapacity >>> 1); initialCapacity |= (initialCapacity >>> 2); initialCapacity |= (initialCapacity >>> 4); initialCapacity |= (initialCapacity >>> 8); initialCapacity |= (initialCapacity >>> 16); initialCapacity++; if (initialCapacity < 0) // Too many elements, must back off initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements } elements = (E[]) new Object[initialCapacity]; } /** * Double the capacity of this deque. Call only when full, i.e., * when head and tail have wrapped around to become equal. */ @SuppressWarnings("unchecked") private void doubleCapacity() { assert head == tail; int p = head; int n = elements.length; int r = n - p; // number of elements to the right of p int newCapacity = n << 1; if (newCapacity < 0) throw new IllegalStateException("Sorry, deque too big"); Object[] a = new Object[newCapacity]; System.arraycopy(elements, p, a, 0, r); System.arraycopy(elements, 0, a, r, p); elements = (E[])a; head = 0; tail = n; } /** * Copies the elements from our element array into the specified array, * in order (from first to last element in the deque). It is assumed * that the array is large enough to hold all elements in the deque. * * @return its argument */ private <T> T[] copyElements(T[] a) { if (head < tail) { System.arraycopy(elements, head, a, 0, size()); } else if (head > tail) { int headPortionLen = elements.length - head; System.arraycopy(elements, head, a, 0, headPortionLen); System.arraycopy(elements, 0, a, headPortionLen, tail); } return a; } /** * Constructs an empty array deque with an initial capacity * sufficient to hold 16 elements. */ @SuppressWarnings("unchecked") public ArrayDeque() { elements = (E[]) new Object[16]; } /** * Constructs an empty array deque with an initial capacity * sufficient to hold the specified number of elements. * * @param numElements lower bound on initial capacity of the deque */ public ArrayDeque(int numElements) { allocateElements(numElements); } /** * Constructs a deque containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. (The first element returned by the collection's * iterator becomes the first element, or <i>front</i> of the * deque.) * * @param c the collection whose elements are to be placed into the deque * @throws NullPointerException if the specified collection is null */ public ArrayDeque(Collection<? extends E> c) { allocateElements(c.size()); addAll(c); } // The main insertion and extraction methods are addFirst, // addLast, pollFirst, pollLast. The other methods are defined in // terms of these. /** * Inserts the specified element at the front of this deque. * * @param e the element to add * @throws NullPointerException if the specified element is null */ public void addFirst(E e) { if (e == null) throw new NullPointerException(); elements[head = (head - 1) & (elements.length - 1)] = e; if (head == tail) doubleCapacity(); } /** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #add}. * * @param e the element to add * @throws NullPointerException if the specified element is null */ public void addLast(E e) { if (e == null) throw new NullPointerException(); elements[tail] = e; if ( (tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity(); } /** * Inserts the specified element at the front of this deque. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Deque#offerFirst}) * @throws NullPointerException if the specified element is null */ public boolean offerFirst(E e) { addFirst(e); return true; } /** * Inserts the specified element at the end of this deque. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Deque#offerLast}) * @throws NullPointerException if the specified element is null */ public boolean offerLast(E e) { addLast(e); return true; } /** * @throws NoSuchElementException {@inheritDoc} */ public E removeFirst() { E x = pollFirst(); if (x == null) throw new NoSuchElementException(); return x; } /** * @throws NoSuchElementException {@inheritDoc} */ public E removeLast() { E x = pollLast(); if (x == null) throw new NoSuchElementException(); return x; } public E pollFirst() { int h = head; E result = elements[h]; // Element is null if deque empty if (result == null) return null; elements[h] = null; // Must null out slot head = (h + 1) & (elements.length - 1); return result; } public E pollLast() { int t = (tail - 1) & (elements.length - 1); E result = elements[t]; if (result == null) return null; elements[t] = null; tail = t; return result; } /** * @throws NoSuchElementException {@inheritDoc} */ public E getFirst() { E x = elements[head]; if (x == null) throw new NoSuchElementException(); return x; } /** * @throws NoSuchElementException {@inheritDoc} */ public E getLast() { E x = elements[(tail - 1) & (elements.length - 1)]; if (x == null) throw new NoSuchElementException(); return x; } public E peekFirst() { return elements[head]; // elements[head] is null if deque empty } public E peekLast() { return elements[(tail - 1) & (elements.length - 1)]; } /** * Removes the first occurrence of the specified element in this * deque (when traversing the deque from head to tail). * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if the deque contained the specified element */ public boolean removeFirstOccurrence(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = head; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) { delete(i); return true; } i = (i + 1) & mask; } return false; } /** * Removes the last occurrence of the specified element in this * deque (when traversing the deque from head to tail). * If the deque does not contain the element, it is unchanged. * More formally, removes the last element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if the deque contained the specified element */ public boolean removeLastOccurrence(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = (tail - 1) & mask; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) { delete(i); return true; } i = (i - 1) & mask; } return false; } // *** Queue methods *** /** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #addLast}. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws NullPointerException if the specified element is null */ public boolean add(E e) { addLast(e); return true; } /** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #offerLast}. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Queue#offer}) * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { return offerLast(e); } /** * Retrieves and removes the head of the queue represented by this deque. * * This method differs from {@link #poll poll} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #removeFirst}. * * @return the head of the queue represented by this deque * @throws NoSuchElementException {@inheritDoc} */ public E remove() { return removeFirst(); } /** * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), or returns * <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #pollFirst}. * * @return the head of the queue represented by this deque, or * <tt>null</tt> if this deque is empty */ public E poll() { return pollFirst(); } /** * Retrieves, but does not remove, the head of the queue represented by * this deque. This method differs from {@link #peek peek} only in * that it throws an exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst}. * * @return the head of the queue represented by this deque * @throws NoSuchElementException {@inheritDoc} */ public E element() { return getFirst(); } /** * Retrieves, but does not remove, the head of the queue represented by * this deque, or returns <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #peekFirst}. * * @return the head of the queue represented by this deque, or * <tt>null</tt> if this deque is empty */ public E peek() { return peekFirst(); } // *** Stack methods *** /** * Pushes an element onto the stack represented by this deque. In other * words, inserts the element at the front of this deque. * * <p>This method is equivalent to {@link #addFirst}. * * @param e the element to push * @throws NullPointerException if the specified element is null */ public void push(E e) { addFirst(e); } /** * Pops an element from the stack represented by this deque. In other * words, removes and returns the first element of this deque. * * <p>This method is equivalent to {@link #removeFirst()}. * * @return the element at the front of this deque (which is the top * of the stack represented by this deque) * @throws NoSuchElementException {@inheritDoc} */ public E pop() { return removeFirst(); } private void checkInvariants() { assert elements[tail] == null; assert head == tail ? elements[head] == null : (elements[head] != null && elements[(tail - 1) & (elements.length - 1)] != null); assert elements[(head - 1) & (elements.length - 1)] == null; } /** * Removes the element at the specified position in the elements array, * adjusting head and tail as necessary. This can result in motion of * elements backwards or forwards in the array. * * <p>This method is called delete rather than remove to emphasize * that its semantics differ from those of {@link List#remove(int)}. * * @return true if elements moved backwards */ private boolean delete(int i) { checkInvariants(); final E[] elements = this.elements; final int mask = elements.length - 1; final int h = head; final int t = tail; final int front = (i - h) & mask; final int back = (t - i) & mask; // Invariant: head <= i < tail mod circularity if (front >= ((t - h) & mask)) throw new ConcurrentModificationException(); // Optimize for least element motion if (front < back) { if (h <= i) { System.arraycopy(elements, h, elements, h + 1, front); } else { // Wrap around System.arraycopy(elements, 0, elements, 1, i); elements[0] = elements[mask]; System.arraycopy(elements, h, elements, h + 1, mask - h); } elements[h] = null; head = (h + 1) & mask; return false; } else { if (i < t) { // Copy the null tail as well System.arraycopy(elements, i + 1, elements, i, back); tail = t - 1; } else { // Wrap around System.arraycopy(elements, i + 1, elements, i, mask - i); elements[mask] = elements[0]; System.arraycopy(elements, 1, elements, 0, t); tail = (t - 1) & mask; } return true; } } // *** Collection Methods *** /** * Returns the number of elements in this deque. * * @return the number of elements in this deque */ public int size() { return (tail - head) & (elements.length - 1); } /** * Returns <tt>true</tt> if this deque contains no elements. * * @return <tt>true</tt> if this deque contains no elements */ public boolean isEmpty() { return head == tail; } /** * Returns an iterator over the elements in this deque. The elements * will be ordered from first (head) to last (tail). This is the same * order that elements would be dequeued (via successive calls to * {@link #remove} or popped (via successive calls to {@link #pop}). * * @return an iterator over the elements in this deque */ public Iterator<E> iterator() { return new DeqIterator(); } public Iterator<E> descendingIterator() { return new DescendingIterator(); } private class DeqIterator implements Iterator<E> { /** * Index of element to be returned by subsequent call to next. */ private int cursor = head; /** * Tail recorded at construction (also in remove), to stop * iterator and also to check for comodification. */ private int fence = tail; /** * Index of element returned by most recent call to next. * Reset to -1 if element is deleted by a call to remove. */ private int lastRet = -1; public boolean hasNext() { return cursor != fence; } public E next() { if (cursor == fence) throw new NoSuchElementException(); E result = elements[cursor]; // This check doesn't catch all possible comodifications, // but does catch the ones that corrupt traversal if (tail != fence || result == null) throw new ConcurrentModificationException(); lastRet = cursor; cursor = (cursor + 1) & (elements.length - 1); return result; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); if (delete(lastRet)) { // if left-shifted, undo increment in next() cursor = (cursor - 1) & (elements.length - 1); fence = tail; } lastRet = -1; } } private class DescendingIterator implements Iterator<E> { /* * This class is nearly a mirror-image of DeqIterator, using * tail instead of head for initial cursor, and head instead of * tail for fence. */ private int cursor = tail; private int fence = head; private int lastRet = -1; public boolean hasNext() { return cursor != fence; } public E next() { if (cursor == fence) throw new NoSuchElementException(); cursor = (cursor - 1) & (elements.length - 1); E result = elements[cursor]; if (head != fence || result == null) throw new ConcurrentModificationException(); lastRet = cursor; return result; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); if (!delete(lastRet)) { cursor = (cursor + 1) & (elements.length - 1); fence = head; } lastRet = -1; } } /** * Returns <tt>true</tt> if this deque contains the specified element. * More formally, returns <tt>true</tt> if and only if this deque contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * * @param o object to be checked for containment in this deque * @return <tt>true</tt> if this deque contains the specified element */ public boolean contains(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = head; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) return true; i = (i + 1) & mask; } return false; } /** * Removes a single instance of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p>This method is equivalent to {@link #removeFirstOccurrence}. * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if this deque contained the specified element */ public boolean remove(Object o) { return removeFirstOccurrence(o); } /** * Removes all of the elements from this deque. * The deque will be empty after this call returns. */ public void clear() { int h = head; int t = tail; if (h != t) { // clear all cells head = tail = 0; int i = h; int mask = elements.length - 1; do { elements[i] = null; i = (i + 1) & mask; } while (i != t); } } /** * Returns an array containing all of the elements in this deque * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this deque. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this deque */ public Object[] toArray() { return copyElements(new Object[size()]); } /** * Returns an array containing all of the elements in this deque in * proper sequence (from first to last element); the runtime type of the * returned array is that of the specified array. If the deque fits in * the specified array, it is returned therein. Otherwise, a new array * is allocated with the runtime type of the specified array and the * size of this deque. * * <p>If this deque fits in the specified array with room to spare * (i.e., the array has more elements than this deque), the element in * the array immediately following the end of the deque is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a deque known to contain only strings. * The following code can be used to dump the deque into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * * @param a the array into which the elements of the deque are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this deque * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this deque * @throws NullPointerException if the specified array is null */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { int size = size(); if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); copyElements(a); if (a.length > size) a[size] = null; return a; } // *** Object methods<SUF> /** * Returns a copy of this deque. * * @return a copy of this deque */ public ArrayDeque<E> clone() { try { @SuppressWarnings("unchecked") ArrayDeque<E> result = (ArrayDeque<E>) super.clone(); result.elements = Arrays.copyOf(elements, elements.length); return result; } catch (CloneNotSupportedException e) { throw new AssertionError(); } } /** * Appease the serialization gods. */ private static final long serialVersionUID = 2340985798034038923L; /** * Serialize this deque. * * @serialData The current size (<tt>int</tt>) of the deque, * followed by all of its elements (each an object reference) in * first-to-last order. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // Write out size s.writeInt(size()); // Write out elements in order. int mask = elements.length - 1; for (int i = head; i != tail; i = (i + 1) & mask) s.writeObject(elements[i]); } /** * Deserialize this deque. */ @SuppressWarnings("unchecked") private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // Read in size and allocate array int size = s.readInt(); allocateElements(size); head = 0; tail = size; // Read in all elements in the proper order. for (int i = 0; i < size; i++) elements[i] = (E)s.readObject(); } }
37897_7
import java.time.LocalDate; public class Auto extends Voertuig { private String kenteken; public Auto(String type, double nieuwPrijs, int bouwJaar, String kenteken) { super(type, nieuwPrijs, bouwJaar); this.kenteken = kenteken; } @Override public double huidigeWaarde() { // Als de bouwJaar kleiner is dan het huidige jaar // Dan gaat er 30% van het huidige waarde af if (bouwJaar < LocalDate.now().getYear()) { return nieuwPrijs * Math.pow(0.7, LocalDate.now().getYear() - bouwJaar); } return nieuwPrijs; } @Override public boolean equals(Object object) { // gelijkeObject erft de waarden over van equals methode uit de Parent clas boolean gelijkeObjecten = super.equals(object); // Als gelijkeObjecten true is // Dan wordt de instantie van door gepaste object gecheckt if (gelijkeObjecten) { // Als object instantie is van Auto // Dan word er gecheckt of het kenteken van auto true is. // (Bij true betekent dit dat de waarden van het kenteken niet uniek is) if (object instanceof Auto andereAuto) { gelijkeObjecten = this.kenteken.equals(andereAuto.kenteken); } } return gelijkeObjecten; } }
yannick-coolen/SchoolAssignment_Bedrijf
src/Auto.java
400
// (Bij true betekent dit dat de waarden van het kenteken niet uniek is)
line_comment
nl
import java.time.LocalDate; public class Auto extends Voertuig { private String kenteken; public Auto(String type, double nieuwPrijs, int bouwJaar, String kenteken) { super(type, nieuwPrijs, bouwJaar); this.kenteken = kenteken; } @Override public double huidigeWaarde() { // Als de bouwJaar kleiner is dan het huidige jaar // Dan gaat er 30% van het huidige waarde af if (bouwJaar < LocalDate.now().getYear()) { return nieuwPrijs * Math.pow(0.7, LocalDate.now().getYear() - bouwJaar); } return nieuwPrijs; } @Override public boolean equals(Object object) { // gelijkeObject erft de waarden over van equals methode uit de Parent clas boolean gelijkeObjecten = super.equals(object); // Als gelijkeObjecten true is // Dan wordt de instantie van door gepaste object gecheckt if (gelijkeObjecten) { // Als object instantie is van Auto // Dan word er gecheckt of het kenteken van auto true is. // (Bij true<SUF> if (object instanceof Auto andereAuto) { gelijkeObjecten = this.kenteken.equals(andereAuto.kenteken); } } return gelijkeObjecten; } }
3022_2
import java.util.ArrayList; public class Persoon { private String naam; private double budget; private ArrayList<Game> mijnGames; public Persoon(String naam, double budget) { this.naam = naam; this.budget = budget; this.mijnGames = new ArrayList<Game>(); } /** * Toont het budget van wat er binnen de parameter van de geïnstantieerde. * Object van Class is ingevoerd. * @return Huidige budget. */ public double getBudget() { return budget; } /** * Biedt de mogelijkheid om te kunnen zien of de game wel of niet is verkocht aan persoon.<br><br> * Als het budget van persoon hoger is dan de huidige waarde van de game en de persoon heeft * dat game nog niet tot zijn bezit, dan wordt deze aan de persoon verkocht waardoor ook automatisch * deze aan het lijst mijnGames wordt toegevoegd en de waarde van budget van persoon waarde afgetrokken * met het huidige budget van de game waardoor er een nieuwe waarde in het budget wordt gezet. * @param game Huidige waarde van game. * @return true als de game wordt verkocht, anders false. */ public boolean koop(Game game) { if (getBudget() >= game.huidigeWaarde() && !mijnGames.contains(game)) { budget -= game.huidigeWaarde(); mijnGames.add(game); return true; } return false; } /** * Biedt de mogelijkheid om te kunnen zien dat het game aan een andere persoon wordt verkocht.<br><br> * Als eerste persoon de game bevat en de tweede persoon deze niet in bezit heeft en voldoende budget * heeft deze te kopen, wordt de game van eerste persoon verkocht aan het tweede persoon waardoor * het budget van de eerste persoon stijgt en die van de tweede persoon daalt in huidige waarde. * @param game De game zelf, naam en het huidige waarde. * @param koper Andere persoon. * @return true als de game wordt verkocht, anders false. */ public boolean verkoop(Game game, Persoon koper) { if (mijnGames.contains(game) && koper.getBudget() >= game.huidigeWaarde() && !koper.mijnGames.contains(game)) { mijnGames.remove(game); koper.budget -= game.huidigeWaarde(); budget += game.huidigeWaarde(); koper.mijnGames.add(game); return true; } return false; } @Override public String toString() { StringBuilder sGames= new StringBuilder(); for (Game mijnGame : mijnGames) { sGames.append("\n").append(mijnGame); } return naam + " heeft een budget van \u20AC" + String.format("%.2f", budget) + " en bezit de volgende games:" + sGames ; } }
yannick-coolen/SchoolAssignment_Games
src/Persoon.java
828
/** * Biedt de mogelijkheid om te kunnen zien dat het game aan een andere persoon wordt verkocht.<br><br> * Als eerste persoon de game bevat en de tweede persoon deze niet in bezit heeft en voldoende budget * heeft deze te kopen, wordt de game van eerste persoon verkocht aan het tweede persoon waardoor * het budget van de eerste persoon stijgt en die van de tweede persoon daalt in huidige waarde. * @param game De game zelf, naam en het huidige waarde. * @param koper Andere persoon. * @return true als de game wordt verkocht, anders false. */
block_comment
nl
import java.util.ArrayList; public class Persoon { private String naam; private double budget; private ArrayList<Game> mijnGames; public Persoon(String naam, double budget) { this.naam = naam; this.budget = budget; this.mijnGames = new ArrayList<Game>(); } /** * Toont het budget van wat er binnen de parameter van de geïnstantieerde. * Object van Class is ingevoerd. * @return Huidige budget. */ public double getBudget() { return budget; } /** * Biedt de mogelijkheid om te kunnen zien of de game wel of niet is verkocht aan persoon.<br><br> * Als het budget van persoon hoger is dan de huidige waarde van de game en de persoon heeft * dat game nog niet tot zijn bezit, dan wordt deze aan de persoon verkocht waardoor ook automatisch * deze aan het lijst mijnGames wordt toegevoegd en de waarde van budget van persoon waarde afgetrokken * met het huidige budget van de game waardoor er een nieuwe waarde in het budget wordt gezet. * @param game Huidige waarde van game. * @return true als de game wordt verkocht, anders false. */ public boolean koop(Game game) { if (getBudget() >= game.huidigeWaarde() && !mijnGames.contains(game)) { budget -= game.huidigeWaarde(); mijnGames.add(game); return true; } return false; } /** * Biedt de mogelijkheid<SUF>*/ public boolean verkoop(Game game, Persoon koper) { if (mijnGames.contains(game) && koper.getBudget() >= game.huidigeWaarde() && !koper.mijnGames.contains(game)) { mijnGames.remove(game); koper.budget -= game.huidigeWaarde(); budget += game.huidigeWaarde(); koper.mijnGames.add(game); return true; } return false; } @Override public String toString() { StringBuilder sGames= new StringBuilder(); for (Game mijnGame : mijnGames) { sGames.append("\n").append(mijnGame); } return naam + " heeft een budget van \u20AC" + String.format("%.2f", budget) + " en bezit de volgende games:" + sGames ; } }
13756_7
/* * Copyright (C) 2006 * Thomas van Dijk * Jan-Pieter van den Heuvel * Wouter Slob * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ package nl.uu.cs.treewidth.algorithm; import java.util.Collections; import nl.uu.cs.treewidth.input.GraphInput.InputData; import nl.uu.cs.treewidth.ngraph.NGraph; import nl.uu.cs.treewidth.ngraph.NVertex; import nl.uu.cs.treewidth.ngraph.NVertexOrder; /** * Triangulation obtained by using the elimination scheme produced by the MCS (Maximum Cardinality Search) algorithm of Berry et al. * This is a version of MCS that produces minimal triangulations. * * Reference paper: Maximum Cardinality Search for Computing Minimal Triangulations * Anne Berry, Jean R. S. Blair, and Pinar Heggernes * * @author tw team * */ public class MaximumCardinalitySearchMinimal<D extends InputData> implements Permutation<D>{ protected NGraph<MCSMData> graph; private NVertexOrder<D> vertexOrder; public MaximumCardinalitySearchMinimal() { vertexOrder = new NVertexOrder<D>(); } public NVertexOrder<D> getPermutation() { return vertexOrder; } public String getName() { return "MCS-M; Maximum Cardinality Search Algorithm Minimal"; } class MCSMData extends InputData { public MCSMData( NVertex<D> old ) { super( old.data.id, old.data.name ); } int value; int dfs; boolean visited; public NVertex<D> original; public NVertex<D> getOriginal() {return original;} public String toString() { String s = super.toString(); s = s.concat( " (" + value + (visited?"; visited":"")+ ")" ); return s; } } class MyConvertor implements NGraph.Convertor< D, MCSMData > { public MCSMData convert( NVertex<D> old ) { MCSMData d = new MCSMData( old ); d.value = 0; d.visited = false; d.dfs = Integer.MAX_VALUE; d.original = old; return d; } } public void setInput( NGraph<D> g ) { graph = g.copy( new MyConvertor() ); vertexOrder = new NVertexOrder<D>(); } public void run() { /* * F = ?; for all vertices v in G do w(v) = 0; * for i = n downto 1 do * Choose an unnumbered vertex z of maximum weight; ?(z) = i; * for all unnumbered vertices y ? G do * if there is a path y, x1, x2, ..., xk, z in G through unnumbered vertices * such that wz?(xi) < wz?(y) for 1 ? i ? k then * w(y) = w(y) + 1; * F = F ? {yz}; * H = (V,E ? F); */ //Output.present( graph, "MCS-M" ); for( int i = graph.getNumberOfVertices(); i > 0; --i ) { //Find unnumbered vertex with max weight int max = 0; NVertex<MCSMData> z = null; for( NVertex<MCSMData> v : graph ) { if( !v.data.visited && v.data.value>=max ) { z = v; max = v.data.value; } } if(z==null) continue; z.data.visited = true; vertexOrder.order.add( z.data.getOriginal() ); // Hoog de value van alle unnumbered vertices op, iff, // er een pad van die vertices via andere unnumbered vertices bestaat, // waarbij de vertices op dat pad een lager gewicht hebben. for( NVertex<MCSMData> v : graph ) { v.data.dfs = Integer.MAX_VALUE; } for( NVertex<MCSMData> other : z ) { //Kijk alleen naar unnumbered vertices if( ! other.data.visited ) { //Buren worden zowiezo opgehoogd goRecursive( other, other.data.value ); } } for( NVertex<MCSMData> other : z ) { //Kijk alleen naar unnumbered vertices if( ! other.data.visited ) { // Buren worden hoe dan ook opgehoogd. other.data.dfs = -1; } } // Hoog alle vertices met een legaal pad op. for( NVertex<MCSMData> v : graph ) { if( !v.data.visited ) { if( v.data.value > v.data.dfs ) { ++v.data.value; } } } } Collections.reverse(vertexOrder.order); } public void goRecursive( NVertex<MCSMData> v, int w ) { if( !v.data.visited && w<v.data.dfs ) { v.data.dfs = w; for( NVertex<MCSMData> other : v ) { int max; if( w>v.data.value ) max = v.data.value; else max = w; goRecursive( other, max ); } } } }
yannponty/RNARedPrint
lib/treewidth-java/nl/uu/cs/treewidth/algorithm/MaximumCardinalitySearchMinimal.java
1,810
// waarbij de vertices op dat pad een lager gewicht hebben.
line_comment
nl
/* * Copyright (C) 2006 * Thomas van Dijk * Jan-Pieter van den Heuvel * Wouter Slob * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ package nl.uu.cs.treewidth.algorithm; import java.util.Collections; import nl.uu.cs.treewidth.input.GraphInput.InputData; import nl.uu.cs.treewidth.ngraph.NGraph; import nl.uu.cs.treewidth.ngraph.NVertex; import nl.uu.cs.treewidth.ngraph.NVertexOrder; /** * Triangulation obtained by using the elimination scheme produced by the MCS (Maximum Cardinality Search) algorithm of Berry et al. * This is a version of MCS that produces minimal triangulations. * * Reference paper: Maximum Cardinality Search for Computing Minimal Triangulations * Anne Berry, Jean R. S. Blair, and Pinar Heggernes * * @author tw team * */ public class MaximumCardinalitySearchMinimal<D extends InputData> implements Permutation<D>{ protected NGraph<MCSMData> graph; private NVertexOrder<D> vertexOrder; public MaximumCardinalitySearchMinimal() { vertexOrder = new NVertexOrder<D>(); } public NVertexOrder<D> getPermutation() { return vertexOrder; } public String getName() { return "MCS-M; Maximum Cardinality Search Algorithm Minimal"; } class MCSMData extends InputData { public MCSMData( NVertex<D> old ) { super( old.data.id, old.data.name ); } int value; int dfs; boolean visited; public NVertex<D> original; public NVertex<D> getOriginal() {return original;} public String toString() { String s = super.toString(); s = s.concat( " (" + value + (visited?"; visited":"")+ ")" ); return s; } } class MyConvertor implements NGraph.Convertor< D, MCSMData > { public MCSMData convert( NVertex<D> old ) { MCSMData d = new MCSMData( old ); d.value = 0; d.visited = false; d.dfs = Integer.MAX_VALUE; d.original = old; return d; } } public void setInput( NGraph<D> g ) { graph = g.copy( new MyConvertor() ); vertexOrder = new NVertexOrder<D>(); } public void run() { /* * F = ?; for all vertices v in G do w(v) = 0; * for i = n downto 1 do * Choose an unnumbered vertex z of maximum weight; ?(z) = i; * for all unnumbered vertices y ? G do * if there is a path y, x1, x2, ..., xk, z in G through unnumbered vertices * such that wz?(xi) < wz?(y) for 1 ? i ? k then * w(y) = w(y) + 1; * F = F ? {yz}; * H = (V,E ? F); */ //Output.present( graph, "MCS-M" ); for( int i = graph.getNumberOfVertices(); i > 0; --i ) { //Find unnumbered vertex with max weight int max = 0; NVertex<MCSMData> z = null; for( NVertex<MCSMData> v : graph ) { if( !v.data.visited && v.data.value>=max ) { z = v; max = v.data.value; } } if(z==null) continue; z.data.visited = true; vertexOrder.order.add( z.data.getOriginal() ); // Hoog de value van alle unnumbered vertices op, iff, // er een pad van die vertices via andere unnumbered vertices bestaat, // waarbij de<SUF> for( NVertex<MCSMData> v : graph ) { v.data.dfs = Integer.MAX_VALUE; } for( NVertex<MCSMData> other : z ) { //Kijk alleen naar unnumbered vertices if( ! other.data.visited ) { //Buren worden zowiezo opgehoogd goRecursive( other, other.data.value ); } } for( NVertex<MCSMData> other : z ) { //Kijk alleen naar unnumbered vertices if( ! other.data.visited ) { // Buren worden hoe dan ook opgehoogd. other.data.dfs = -1; } } // Hoog alle vertices met een legaal pad op. for( NVertex<MCSMData> v : graph ) { if( !v.data.visited ) { if( v.data.value > v.data.dfs ) { ++v.data.value; } } } } Collections.reverse(vertexOrder.order); } public void goRecursive( NVertex<MCSMData> v, int w ) { if( !v.data.visited && w<v.data.dfs ) { v.data.dfs = w; for( NVertex<MCSMData> other : v ) { int max; if( w>v.data.value ) max = v.data.value; else max = w; goRecursive( other, max ); } } } }
84692_0
package main; import javafx.application.Application; /** * CodeCademy */ public class CodeCademy { public static void main(String[] args) { // start javafx vanuit class Application.launch(GUI.class); } }
yasirkel/codecademy
src/main/CodeCademy.java
68
// start javafx vanuit class
line_comment
nl
package main; import javafx.application.Application; /** * CodeCademy */ public class CodeCademy { public static void main(String[] args) { // start javafx<SUF> Application.launch(GUI.class); } }
34885_2
import java.util.ArrayList; import java.util.Scanner; public class kalender { public static void main(String[] args) { ArrayList<String> verjaardagen = new ArrayList<>(); Scanner scanner = new Scanner(System.in); while (true) { System.out.println("Verjaardagskalender 0.1"); System.out.println("Kies een optie:"); System.out.println("1. Verjaardag toevoegen"); System.out.println("2. Verjaardag verwijderen"); System.out.println("3. Alle verjaardagen zien"); System.out.println("4. Afsluiten"); int keuze = scanner.nextInt(); switch (keuze) { case 1: System.out.println("Wie is er jarig?"); scanner.nextLine(); // Leeg de newline String naam = scanner.nextLine(); System.out.println("Op welke dag?"); int dag = scanner.nextInt(); System.out.println("Van welke maand?"); int maand = scanner.nextInt(); // Opslaan van de verjaardag verjaardagen.add(dag + "-" + maand + " " + naam); System.out.println("Verjaardag opgeslagen!"); break; case 2: System.out.println("Welke verjaardag wil je verwijderen?"); scanner.nextLine(); // Leeg de newline String teVerwijderenNaam = scanner.nextLine(); if (verjaardagen.removeIf(verjaardag -> verjaardag.contains(teVerwijderenNaam))) { System.out.println("Verjaardag verwijderd!"); } else { System.out.println("Verjaardag niet gevonden."); } break; case 3: System.out.println("Alle verjaardagen zien:"); for (String verjaardag : verjaardagen) { System.out.println(verjaardag); } break; case 4: System.out.println("Applicatie afgesloten."); scanner.close(); System.exit(0); default: System.out.println("Ongeldige keuze. Probeer opnieuw."); break; } } } }
yasirkel/verjaardags-kalender
kalender.java
664
// Leeg de newline
line_comment
nl
import java.util.ArrayList; import java.util.Scanner; public class kalender { public static void main(String[] args) { ArrayList<String> verjaardagen = new ArrayList<>(); Scanner scanner = new Scanner(System.in); while (true) { System.out.println("Verjaardagskalender 0.1"); System.out.println("Kies een optie:"); System.out.println("1. Verjaardag toevoegen"); System.out.println("2. Verjaardag verwijderen"); System.out.println("3. Alle verjaardagen zien"); System.out.println("4. Afsluiten"); int keuze = scanner.nextInt(); switch (keuze) { case 1: System.out.println("Wie is er jarig?"); scanner.nextLine(); // Leeg de newline String naam = scanner.nextLine(); System.out.println("Op welke dag?"); int dag = scanner.nextInt(); System.out.println("Van welke maand?"); int maand = scanner.nextInt(); // Opslaan van de verjaardag verjaardagen.add(dag + "-" + maand + " " + naam); System.out.println("Verjaardag opgeslagen!"); break; case 2: System.out.println("Welke verjaardag wil je verwijderen?"); scanner.nextLine(); // Leeg de<SUF> String teVerwijderenNaam = scanner.nextLine(); if (verjaardagen.removeIf(verjaardag -> verjaardag.contains(teVerwijderenNaam))) { System.out.println("Verjaardag verwijderd!"); } else { System.out.println("Verjaardag niet gevonden."); } break; case 3: System.out.println("Alle verjaardagen zien:"); for (String verjaardag : verjaardagen) { System.out.println(verjaardag); } break; case 4: System.out.println("Applicatie afgesloten."); scanner.close(); System.exit(0); default: System.out.println("Ongeldige keuze. Probeer opnieuw."); break; } } } }
7737_50
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.menu; import org.mozilla.gecko.AppConstants; import org.mozilla.gecko.R; import org.mozilla.gecko.util.ThreadUtils; import org.mozilla.gecko.util.ThreadUtils.AssertBehavior; import org.mozilla.gecko.widget.GeckoActionProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GeckoMenu extends ListView implements Menu, AdapterView.OnItemClickListener, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; /** * Controls whether off-UI-thread method calls in this class cause an * exception or just logging. */ private static final AssertBehavior THREAD_ASSERT_BEHAVIOR = AppConstants.RELEASE_BUILD ? AssertBehavior.NONE : AssertBehavior.THROW; /* * A callback for a menu item click/long click event. */ public static interface Callback { // Called when a menu item is clicked, with the actual menu item as the argument. public boolean onMenuItemClick(MenuItem item); // Called when a menu item is long-clicked, with the actual menu item as the argument. public boolean onMenuItemLongClick(MenuItem item); } /* * An interface for a presenter to show the menu. * Either an Activity or a View can be a presenter, that can watch for events * and show/hide menu. */ public static interface MenuPresenter { // Open the menu. public void openMenu(); // Show the actual view containing the menu items. This can either be a parent or sub-menu. public void showMenu(View menu); // Close the menu. public void closeMenu(); } /* * An interface for a presenter of action-items. * Either an Activity or a View can be a presenter, that can watch for events * and add/remove action-items. If not ActionItemBarPresenter, the menu uses a * DefaultActionItemBar, that shows the action-items as a header over list-view. */ public static interface ActionItemBarPresenter { // Add an action-item. public boolean addActionItem(View actionItem); // Remove an action-item. public void removeActionItem(View actionItem); } protected static final int NO_ID = 0; // List of all menu items. private List<GeckoMenuItem> mItems; // Map of "always" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mPrimaryActionItems; // Map of "ifRoom" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mSecondaryActionItems; // Reference to a callback for menu events. private Callback mCallback; // Reference to menu presenter. private MenuPresenter mMenuPresenter; // Reference to "always" action-items bar in action-bar. private ActionItemBarPresenter mPrimaryActionItemBar; // Reference to "ifRoom" action-items bar in action-bar. private final ActionItemBarPresenter mSecondaryActionItemBar; // Adapter to hold the list of menu items. private MenuItemsAdapter mAdapter; // Show/hide icons in the list. /* inner-access */ boolean mShowIcons; public GeckoMenu(Context context) { this(context, null); } public GeckoMenu(Context context, AttributeSet attrs) { this(context, attrs, R.attr.geckoMenuListViewStyle); } public GeckoMenu(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // Attach an adapter. mAdapter = new MenuItemsAdapter(); setAdapter(mAdapter); setOnItemClickListener(this); mItems = new ArrayList<GeckoMenuItem>(); mPrimaryActionItems = new HashMap<GeckoMenuItem, View>(); mSecondaryActionItems = new HashMap<GeckoMenuItem, View>(); mPrimaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_action_bar, null); mSecondaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_secondary_action_bar, null); } private static void assertOnUiThread() { ThreadUtils.assertOnUiThread(THREAD_ASSERT_BEHAVIOR); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); mAdapter.addMenuItem(menuItem); mItems.add(menuItem); } private boolean addActionItem(final GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); final View actionView = menuItem.getActionView(); final int actionEnum = menuItem.getActionEnum(); boolean added = false; if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } if (added = mPrimaryActionItemBar.addActionItem(actionView)) { mPrimaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } else if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_IF_ROOM) { if (mSecondaryActionItems.size() == 0) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } if (added = mSecondaryActionItemBar.addActionItem(actionView)) { mSecondaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } // Set the listeners. if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionBar) actionView).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { handleMenuItemLongClick(menuItem); return true; } }); } else if (actionView instanceof MenuItemActionView) { ((MenuItemActionView) actionView).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionView) actionView).setMenuItemLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { handleMenuItemLongClick(menuItem); return true; } }); } return added; } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { MenuItem menuItem = add(groupId, itemId, order, title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { MenuItem menuItem = add(groupId, itemId, order, titleRes); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(CharSequence title) { MenuItem menuItem = add(title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int titleRes) { MenuItem menuItem = add(titleRes); return addSubMenu(menuItem); } private SubMenu addSubMenu(MenuItem menuItem) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setMenuItem(menuItem); subMenu.setCallback(mCallback); subMenu.setMenuPresenter(mMenuPresenter); ((GeckoMenuItem) menuItem).setSubMenu(subMenu); return subMenu; } private void removePrimaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } private void removeSecondaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } @Override public void clear() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu sub = menuItem.getSubMenu(); if (sub == null) { continue; } try { sub.clear(); } catch (Exception ex) { Log.e(LOGTAG, "Couldn't clear submenu.", ex); } } } mAdapter.clear(); mItems.clear(); /* * Reinflating the menu will re-add any action items to the toolbar, so * remove the old ones. This also ensures that any text associated with * these is switched to the correct locale. */ if (mPrimaryActionItemBar != null) { for (View item : mPrimaryActionItems.values()) { mPrimaryActionItemBar.removeActionItem(item); } } mPrimaryActionItems.clear(); if (mSecondaryActionItemBar != null) { for (View item : mSecondaryActionItems.values()) { mSecondaryActionItemBar.removeActionItem(item); } } mSecondaryActionItems.clear(); // Remove the view, too -- the first addActionItem will re-add it, // and this is simpler than changing that logic. if (mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } removeSecondaryActionBarView(); } @Override public void close() { if (mMenuPresenter != null) mMenuPresenter.closeMenu(); } private void showMenu(View viewForMenu) { if (mMenuPresenter != null) mMenuPresenter.showMenu(viewForMenu); } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { return menuItem; } else if (menuItem.hasSubMenu()) { if (!menuItem.hasActionProvider()) { SubMenu subMenu = menuItem.getSubMenu(); MenuItem item = subMenu.findItem(id); if (item != null) return item; } } } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible() && !mPrimaryActionItems.containsKey(menuItem) && !mSecondaryActionItems.containsKey(menuItem)) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { assertOnUiThread(); GeckoMenuItem item = (GeckoMenuItem) findItem(id); if (item == null) return; // Remove it from any sub-menu. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu subMenu = menuItem.getSubMenu(); if (subMenu != null && subMenu.findItem(id) != null) { subMenu.removeItem(id); return; } } } // Remove it from own menu. if (mPrimaryActionItems.containsKey(item)) { if (mPrimaryActionItemBar != null) mPrimaryActionItemBar.removeActionItem(mPrimaryActionItems.get(item)); mPrimaryActionItems.remove(item); mItems.remove(item); if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } return; } if (mSecondaryActionItems.containsKey(item)) { if (mSecondaryActionItemBar != null) mSecondaryActionItemBar.removeActionItem(mSecondaryActionItems.get(item)); mSecondaryActionItems.remove(item); mItems.remove(item); if (mSecondaryActionItems.size() == 0) { removeSecondaryActionBarView(); } return; } mAdapter.removeMenuItem(item); mItems.remove(item); } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mPrimaryActionItemBar != null) && (mSecondaryActionItemBar != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item) { removeItem(item.getItemId()); if (item.isActionItem() && addActionItem(item)) { return; } addItem(item); } public void onItemChanged(GeckoMenuItem item) { assertOnUiThread(); if (item.isActionItem()) { final View actionView; if (item.getActionEnum() == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { actionView = mPrimaryActionItems.get(item); } else { actionView = mSecondaryActionItems.get(item); } if (actionView != null) { // The update could be coming from the background thread. // Post a runnable on the UI thread of the view for it to update. final GeckoMenuItem menuItem = item; actionView.post(new Runnable() { @Override public void run() { if (menuItem.isVisible()) { actionView.setVisibility(View.VISIBLE); if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).initialize(menuItem); } else { ((MenuItemActionView) actionView).initialize(menuItem); } } else { actionView.setVisibility(View.GONE); } } }); } } else { mAdapter.notifyDataSetChanged(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // We might be showing headers. Account them while using the position. position -= getHeaderViewsCount(); GeckoMenuItem item = mAdapter.getItem(position); handleMenuItemClick(item); } /* inner-access */ void handleMenuItemClick(GeckoMenuItem item) { if (!item.isEnabled()) return; if (item.invoke()) { close(); } else if (item.hasSubMenu()) { // Refresh the submenu for the provider. GeckoActionProvider provider = item.getGeckoActionProvider(); if (provider != null) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setShowIcons(true); provider.onPrepareSubMenu(subMenu); item.setSubMenu(subMenu); } // Show the submenu. GeckoSubMenu subMenu = (GeckoSubMenu) item.getSubMenu(); showMenu(subMenu); } else { close(); mCallback.onMenuItemClick(item); } } /* inner-access */ void handleMenuItemLongClick(GeckoMenuItem item) { if(!item.isEnabled()) { return; } if(mCallback != null) { mCallback.onMenuItemLongClick(item); } } public Callback getCallback() { return mCallback; } public MenuPresenter getMenuPresenter() { return mMenuPresenter; } public void setCallback(Callback callback) { mCallback = callback; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setCallback(mCallback); } } } public void setMenuPresenter(MenuPresenter presenter) { mMenuPresenter = presenter; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setMenuPresenter(mMenuPresenter); } } } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mPrimaryActionItemBar = presenter; } public void setShowIcons(boolean show) { if (mShowIcons != show) { mShowIcons = show; mAdapter.notifyDataSetChanged(); } } // Action Items are added to the header view by default. // URL bar can register itself as a presenter, in case it has a different place to show them. public static class DefaultActionItemBar extends LinearLayout implements ActionItemBarPresenter { private final int mRowHeight; private float mWeightSum; public DefaultActionItemBar(Context context) { this(context, null); } public DefaultActionItemBar(Context context, AttributeSet attrs) { super(context, attrs); mRowHeight = getResources().getDimensionPixelSize(R.dimen.menu_item_row_height); } @Override public boolean addActionItem(View actionItem) { ViewGroup.LayoutParams actualParams = actionItem.getLayoutParams(); LinearLayout.LayoutParams params; if (actualParams != null) { params = new LinearLayout.LayoutParams(actionItem.getLayoutParams()); params.width = 0; } else { params = new LinearLayout.LayoutParams(0, mRowHeight); } if (actionItem instanceof MenuItemActionView) { params.weight = ((MenuItemActionView) actionItem).getChildCount(); } else { params.weight = 1.0f; } mWeightSum += params.weight; actionItem.setLayoutParams(params); addView(actionItem); setWeightSum(mWeightSum); return true; } @Override public void removeActionItem(View actionItem) { if (indexOfChild(actionItem) != -1) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) actionItem.getLayoutParams(); mWeightSum -= params.weight; removeView(actionItem); } } } // Adapter to bind menu items to the list. private class MenuItemsAdapter extends BaseAdapter { private static final int VIEW_TYPE_DEFAULT = 0; private static final int VIEW_TYPE_ACTION_MODE = 1; private List<GeckoMenuItem> mItems; public MenuItemsAdapter() { mItems = new ArrayList<GeckoMenuItem>(); } @Override public int getCount() { if (mItems == null) return 0; int visibleCount = 0; for (GeckoMenuItem item : mItems) { if (item.isVisible()) visibleCount++; } return visibleCount; } @Override public GeckoMenuItem getItem(int position) { for (GeckoMenuItem item : mItems) { if (item.isVisible()) { position--; if (position < 0) return item; } } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { GeckoMenuItem item = getItem(position); GeckoMenuItem.Layout view = null; // Try to re-use the view. if (convertView == null && getItemViewType(position) == VIEW_TYPE_DEFAULT) { view = new MenuItemDefault(parent.getContext(), null); } else { view = (GeckoMenuItem.Layout) convertView; } if (view == null || view instanceof MenuItemActionView) { // Always get from the menu item. // This will ensure that the default activity is refreshed. view = (MenuItemActionView) item.getActionView(); // ListView will not perform an item click if the row has a focusable view in it. // Hence, forward the click event on the menu item in the action-view to the ListView. final View actionView = (View) view; final int pos = position; final long id = getItemId(position); ((MenuItemActionView) view).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GeckoMenu listView = GeckoMenu.this; listView.performItemClick(actionView, pos + listView.getHeaderViewsCount(), id); } }); } // Initialize the view. view.setShowIcon(mShowIcons); view.initialize(item); return (View) view; } @Override public int getItemViewType(int position) { return getItem(position).getGeckoActionProvider() == null ? VIEW_TYPE_DEFAULT : VIEW_TYPE_ACTION_MODE; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return false; } @Override public boolean areAllItemsEnabled() { // Setting this to true is a workaround to fix disappearing // dividers in the menu (bug 963249). return true; } @Override public boolean isEnabled(int position) { return getItem(position).isEnabled(); } public void addMenuItem(GeckoMenuItem menuItem) { if (mItems.contains(menuItem)) return; // Insert it in proper order. int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); notifyDataSetChanged(); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); notifyDataSetChanged(); } public void removeMenuItem(GeckoMenuItem menuItem) { // Remove it from the list. mItems.remove(menuItem); notifyDataSetChanged(); } public void clear() { mItems.clear(); notifyDataSetChanged(); } public GeckoMenuItem getMenuItem(int id) { for (GeckoMenuItem item : mItems) { if (item.getItemId() == id) return item; } return null; } } }
yask123/gecko-dev
mobile/android/base/menu/GeckoMenu.java
7,137
// Insert it in proper order.
line_comment
nl
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.menu; import org.mozilla.gecko.AppConstants; import org.mozilla.gecko.R; import org.mozilla.gecko.util.ThreadUtils; import org.mozilla.gecko.util.ThreadUtils.AssertBehavior; import org.mozilla.gecko.widget.GeckoActionProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GeckoMenu extends ListView implements Menu, AdapterView.OnItemClickListener, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; /** * Controls whether off-UI-thread method calls in this class cause an * exception or just logging. */ private static final AssertBehavior THREAD_ASSERT_BEHAVIOR = AppConstants.RELEASE_BUILD ? AssertBehavior.NONE : AssertBehavior.THROW; /* * A callback for a menu item click/long click event. */ public static interface Callback { // Called when a menu item is clicked, with the actual menu item as the argument. public boolean onMenuItemClick(MenuItem item); // Called when a menu item is long-clicked, with the actual menu item as the argument. public boolean onMenuItemLongClick(MenuItem item); } /* * An interface for a presenter to show the menu. * Either an Activity or a View can be a presenter, that can watch for events * and show/hide menu. */ public static interface MenuPresenter { // Open the menu. public void openMenu(); // Show the actual view containing the menu items. This can either be a parent or sub-menu. public void showMenu(View menu); // Close the menu. public void closeMenu(); } /* * An interface for a presenter of action-items. * Either an Activity or a View can be a presenter, that can watch for events * and add/remove action-items. If not ActionItemBarPresenter, the menu uses a * DefaultActionItemBar, that shows the action-items as a header over list-view. */ public static interface ActionItemBarPresenter { // Add an action-item. public boolean addActionItem(View actionItem); // Remove an action-item. public void removeActionItem(View actionItem); } protected static final int NO_ID = 0; // List of all menu items. private List<GeckoMenuItem> mItems; // Map of "always" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mPrimaryActionItems; // Map of "ifRoom" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mSecondaryActionItems; // Reference to a callback for menu events. private Callback mCallback; // Reference to menu presenter. private MenuPresenter mMenuPresenter; // Reference to "always" action-items bar in action-bar. private ActionItemBarPresenter mPrimaryActionItemBar; // Reference to "ifRoom" action-items bar in action-bar. private final ActionItemBarPresenter mSecondaryActionItemBar; // Adapter to hold the list of menu items. private MenuItemsAdapter mAdapter; // Show/hide icons in the list. /* inner-access */ boolean mShowIcons; public GeckoMenu(Context context) { this(context, null); } public GeckoMenu(Context context, AttributeSet attrs) { this(context, attrs, R.attr.geckoMenuListViewStyle); } public GeckoMenu(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // Attach an adapter. mAdapter = new MenuItemsAdapter(); setAdapter(mAdapter); setOnItemClickListener(this); mItems = new ArrayList<GeckoMenuItem>(); mPrimaryActionItems = new HashMap<GeckoMenuItem, View>(); mSecondaryActionItems = new HashMap<GeckoMenuItem, View>(); mPrimaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_action_bar, null); mSecondaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_secondary_action_bar, null); } private static void assertOnUiThread() { ThreadUtils.assertOnUiThread(THREAD_ASSERT_BEHAVIOR); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); mAdapter.addMenuItem(menuItem); mItems.add(menuItem); } private boolean addActionItem(final GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); final View actionView = menuItem.getActionView(); final int actionEnum = menuItem.getActionEnum(); boolean added = false; if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } if (added = mPrimaryActionItemBar.addActionItem(actionView)) { mPrimaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } else if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_IF_ROOM) { if (mSecondaryActionItems.size() == 0) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } if (added = mSecondaryActionItemBar.addActionItem(actionView)) { mSecondaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } // Set the listeners. if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionBar) actionView).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { handleMenuItemLongClick(menuItem); return true; } }); } else if (actionView instanceof MenuItemActionView) { ((MenuItemActionView) actionView).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionView) actionView).setMenuItemLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { handleMenuItemLongClick(menuItem); return true; } }); } return added; } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { MenuItem menuItem = add(groupId, itemId, order, title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { MenuItem menuItem = add(groupId, itemId, order, titleRes); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(CharSequence title) { MenuItem menuItem = add(title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int titleRes) { MenuItem menuItem = add(titleRes); return addSubMenu(menuItem); } private SubMenu addSubMenu(MenuItem menuItem) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setMenuItem(menuItem); subMenu.setCallback(mCallback); subMenu.setMenuPresenter(mMenuPresenter); ((GeckoMenuItem) menuItem).setSubMenu(subMenu); return subMenu; } private void removePrimaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } private void removeSecondaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } @Override public void clear() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu sub = menuItem.getSubMenu(); if (sub == null) { continue; } try { sub.clear(); } catch (Exception ex) { Log.e(LOGTAG, "Couldn't clear submenu.", ex); } } } mAdapter.clear(); mItems.clear(); /* * Reinflating the menu will re-add any action items to the toolbar, so * remove the old ones. This also ensures that any text associated with * these is switched to the correct locale. */ if (mPrimaryActionItemBar != null) { for (View item : mPrimaryActionItems.values()) { mPrimaryActionItemBar.removeActionItem(item); } } mPrimaryActionItems.clear(); if (mSecondaryActionItemBar != null) { for (View item : mSecondaryActionItems.values()) { mSecondaryActionItemBar.removeActionItem(item); } } mSecondaryActionItems.clear(); // Remove the view, too -- the first addActionItem will re-add it, // and this is simpler than changing that logic. if (mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } removeSecondaryActionBarView(); } @Override public void close() { if (mMenuPresenter != null) mMenuPresenter.closeMenu(); } private void showMenu(View viewForMenu) { if (mMenuPresenter != null) mMenuPresenter.showMenu(viewForMenu); } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { return menuItem; } else if (menuItem.hasSubMenu()) { if (!menuItem.hasActionProvider()) { SubMenu subMenu = menuItem.getSubMenu(); MenuItem item = subMenu.findItem(id); if (item != null) return item; } } } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible() && !mPrimaryActionItems.containsKey(menuItem) && !mSecondaryActionItems.containsKey(menuItem)) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { assertOnUiThread(); GeckoMenuItem item = (GeckoMenuItem) findItem(id); if (item == null) return; // Remove it from any sub-menu. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu subMenu = menuItem.getSubMenu(); if (subMenu != null && subMenu.findItem(id) != null) { subMenu.removeItem(id); return; } } } // Remove it from own menu. if (mPrimaryActionItems.containsKey(item)) { if (mPrimaryActionItemBar != null) mPrimaryActionItemBar.removeActionItem(mPrimaryActionItems.get(item)); mPrimaryActionItems.remove(item); mItems.remove(item); if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } return; } if (mSecondaryActionItems.containsKey(item)) { if (mSecondaryActionItemBar != null) mSecondaryActionItemBar.removeActionItem(mSecondaryActionItems.get(item)); mSecondaryActionItems.remove(item); mItems.remove(item); if (mSecondaryActionItems.size() == 0) { removeSecondaryActionBarView(); } return; } mAdapter.removeMenuItem(item); mItems.remove(item); } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mPrimaryActionItemBar != null) && (mSecondaryActionItemBar != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item) { removeItem(item.getItemId()); if (item.isActionItem() && addActionItem(item)) { return; } addItem(item); } public void onItemChanged(GeckoMenuItem item) { assertOnUiThread(); if (item.isActionItem()) { final View actionView; if (item.getActionEnum() == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { actionView = mPrimaryActionItems.get(item); } else { actionView = mSecondaryActionItems.get(item); } if (actionView != null) { // The update could be coming from the background thread. // Post a runnable on the UI thread of the view for it to update. final GeckoMenuItem menuItem = item; actionView.post(new Runnable() { @Override public void run() { if (menuItem.isVisible()) { actionView.setVisibility(View.VISIBLE); if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).initialize(menuItem); } else { ((MenuItemActionView) actionView).initialize(menuItem); } } else { actionView.setVisibility(View.GONE); } } }); } } else { mAdapter.notifyDataSetChanged(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // We might be showing headers. Account them while using the position. position -= getHeaderViewsCount(); GeckoMenuItem item = mAdapter.getItem(position); handleMenuItemClick(item); } /* inner-access */ void handleMenuItemClick(GeckoMenuItem item) { if (!item.isEnabled()) return; if (item.invoke()) { close(); } else if (item.hasSubMenu()) { // Refresh the submenu for the provider. GeckoActionProvider provider = item.getGeckoActionProvider(); if (provider != null) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setShowIcons(true); provider.onPrepareSubMenu(subMenu); item.setSubMenu(subMenu); } // Show the submenu. GeckoSubMenu subMenu = (GeckoSubMenu) item.getSubMenu(); showMenu(subMenu); } else { close(); mCallback.onMenuItemClick(item); } } /* inner-access */ void handleMenuItemLongClick(GeckoMenuItem item) { if(!item.isEnabled()) { return; } if(mCallback != null) { mCallback.onMenuItemLongClick(item); } } public Callback getCallback() { return mCallback; } public MenuPresenter getMenuPresenter() { return mMenuPresenter; } public void setCallback(Callback callback) { mCallback = callback; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setCallback(mCallback); } } } public void setMenuPresenter(MenuPresenter presenter) { mMenuPresenter = presenter; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setMenuPresenter(mMenuPresenter); } } } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mPrimaryActionItemBar = presenter; } public void setShowIcons(boolean show) { if (mShowIcons != show) { mShowIcons = show; mAdapter.notifyDataSetChanged(); } } // Action Items are added to the header view by default. // URL bar can register itself as a presenter, in case it has a different place to show them. public static class DefaultActionItemBar extends LinearLayout implements ActionItemBarPresenter { private final int mRowHeight; private float mWeightSum; public DefaultActionItemBar(Context context) { this(context, null); } public DefaultActionItemBar(Context context, AttributeSet attrs) { super(context, attrs); mRowHeight = getResources().getDimensionPixelSize(R.dimen.menu_item_row_height); } @Override public boolean addActionItem(View actionItem) { ViewGroup.LayoutParams actualParams = actionItem.getLayoutParams(); LinearLayout.LayoutParams params; if (actualParams != null) { params = new LinearLayout.LayoutParams(actionItem.getLayoutParams()); params.width = 0; } else { params = new LinearLayout.LayoutParams(0, mRowHeight); } if (actionItem instanceof MenuItemActionView) { params.weight = ((MenuItemActionView) actionItem).getChildCount(); } else { params.weight = 1.0f; } mWeightSum += params.weight; actionItem.setLayoutParams(params); addView(actionItem); setWeightSum(mWeightSum); return true; } @Override public void removeActionItem(View actionItem) { if (indexOfChild(actionItem) != -1) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) actionItem.getLayoutParams(); mWeightSum -= params.weight; removeView(actionItem); } } } // Adapter to bind menu items to the list. private class MenuItemsAdapter extends BaseAdapter { private static final int VIEW_TYPE_DEFAULT = 0; private static final int VIEW_TYPE_ACTION_MODE = 1; private List<GeckoMenuItem> mItems; public MenuItemsAdapter() { mItems = new ArrayList<GeckoMenuItem>(); } @Override public int getCount() { if (mItems == null) return 0; int visibleCount = 0; for (GeckoMenuItem item : mItems) { if (item.isVisible()) visibleCount++; } return visibleCount; } @Override public GeckoMenuItem getItem(int position) { for (GeckoMenuItem item : mItems) { if (item.isVisible()) { position--; if (position < 0) return item; } } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { GeckoMenuItem item = getItem(position); GeckoMenuItem.Layout view = null; // Try to re-use the view. if (convertView == null && getItemViewType(position) == VIEW_TYPE_DEFAULT) { view = new MenuItemDefault(parent.getContext(), null); } else { view = (GeckoMenuItem.Layout) convertView; } if (view == null || view instanceof MenuItemActionView) { // Always get from the menu item. // This will ensure that the default activity is refreshed. view = (MenuItemActionView) item.getActionView(); // ListView will not perform an item click if the row has a focusable view in it. // Hence, forward the click event on the menu item in the action-view to the ListView. final View actionView = (View) view; final int pos = position; final long id = getItemId(position); ((MenuItemActionView) view).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GeckoMenu listView = GeckoMenu.this; listView.performItemClick(actionView, pos + listView.getHeaderViewsCount(), id); } }); } // Initialize the view. view.setShowIcon(mShowIcons); view.initialize(item); return (View) view; } @Override public int getItemViewType(int position) { return getItem(position).getGeckoActionProvider() == null ? VIEW_TYPE_DEFAULT : VIEW_TYPE_ACTION_MODE; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return false; } @Override public boolean areAllItemsEnabled() { // Setting this to true is a workaround to fix disappearing // dividers in the menu (bug 963249). return true; } @Override public boolean isEnabled(int position) { return getItem(position).isEnabled(); } public void addMenuItem(GeckoMenuItem menuItem) { if (mItems.contains(menuItem)) return; // Insert it<SUF> int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); notifyDataSetChanged(); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); notifyDataSetChanged(); } public void removeMenuItem(GeckoMenuItem menuItem) { // Remove it from the list. mItems.remove(menuItem); notifyDataSetChanged(); } public void clear() { mItems.clear(); notifyDataSetChanged(); } public GeckoMenuItem getMenuItem(int id) { for (GeckoMenuItem item : mItems) { if (item.getItemId() == id) return item; } return null; } } }
12568_14
/* * Copyright (c) 2004-2020 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL 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. * * YAWL 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 YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.wsif; import org.yawlfoundation.yawl.engine.interfce.AuthenticationConfig; import org.apache.wsif.*; import org.apache.wsif.providers.ProviderUtils; import org.apache.wsif.providers.soap.apachesoap.WSIFDynamicProvider_ApacheSOAP; import org.apache.wsif.util.WSIFPluggableProviders; import org.apache.wsif.util.WSIFUtils; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import javax.wsdl.*; import javax.xml.namespace.QName; import java.util.*; /** * @author Sanjiva Weerawarana * @author Alekander Slominski * @author Lachlan Aldred */ public class WSIFInvoker { public static HashMap invokeMethod(String wsdlLocation, String portName, String operationName, Element inputDataDoc, AuthenticationConfig authconfig) { System.out.println("XMLOutputter = " + new XMLOutputter(Format.getPrettyFormat()).outputString(inputDataDoc)); System.out.println("wsdl location = " + wsdlLocation); System.out.println("port name = " + portName); System.out.println("operation name = " + operationName); List<String> argsV = new ArrayList<String>(); for (Element element : inputDataDoc.getChildren()) { argsV.add(element.getText()); } String[] args = new String[argsV.size()]; argsV.toArray(args); return invokeMethod( wsdlLocation, operationName, null, null, portName, null, args, 0, authconfig); } public static HashMap invokeMethod(String wsdlLocation, String operationName, String inputName, String outputName, String portName, String protocol, String[] args, int argShift, AuthenticationConfig authconfig) { for (String arg : args) { System.out.println("argValue: " + arg); } HashMap map = new HashMap(); try { String serviceNS = null; String serviceName = null; String portTypeNS = null; String portTypeName = null; // The default SOAP provider is the Apache AXIS provider. If soap was specified // then change the Apache SOAP provider if ("soap".equals(protocol)) { WSIFPluggableProviders.overrideDefaultProvider( "http://schemas.xmlsoap.org/wsdl/soap/", new WSIFDynamicProvider_ApacheSOAP()); } System.out.println("Reading WSDL document from '" + wsdlLocation + "'"); Definition wsdlDefinition = null; if (authconfig == null) { return null; } String userName = authconfig.getUserName(); String password = authconfig.getPassword(); String proxyHost = authconfig.getProxyHost(); String proxyPort = authconfig.getProxyPort(); if (userName != null && userName.length() > 0 && password != null && password.length() > 0 && proxyHost != null && password.length() > 0 && proxyPort != null && proxyPort.length() > 0) { System.getProperties().put("http.proxyHost", proxyHost); System.getProperties().put("http.proxyPort", proxyPort); java.net.PasswordAuthentication pa = new java.net.PasswordAuthentication( userName, password.toCharArray()); wsdlDefinition = WSIFUtils.readWSDLThroughAuthProxy(wsdlLocation, pa); } else { wsdlDefinition = WSIFUtils.readWSDL(null, wsdlLocation); } System.out.println("Preparing WSIF dynamic invocation"); Service service = WSIFUtils.selectService(wsdlDefinition, serviceNS, serviceName); Map portTypes = WSIFUtils.getAllItems(wsdlDefinition, "PortType"); // Really there should be a way to specify the portType // for now just try to find one with the portName if (portTypes.size() > 1 && portName != null) { for (Iterator i = portTypes.keySet().iterator(); i.hasNext();) { QName qn = (QName) i.next(); System.out.println("qn.getLocalPart() = " + qn.getLocalPart()); if (portName.equals(qn.getLocalPart())) { portTypeName = qn.getLocalPart(); portTypeNS = qn.getNamespaceURI(); System.out.println("portTypeName = " + portTypeName); System.out.println("portTypeNS = " + portTypeNS); break; } } } PortType portType = WSIFUtils.selectPortType(wsdlDefinition, portTypeNS, portTypeName); WSIFServiceFactory factory = WSIFServiceFactory.newInstance(); WSIFService dpf = factory.getService(wsdlDefinition, service, portType); WSIFMessage ctx = dpf.getContext(); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_USER, authconfig.getUserName()); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_PSWD, authconfig.getPassword()); dpf.setContext(ctx); WSIFPort port = null; if (portName == null) { port = dpf.getPort(); } else { port = dpf.getPort(portName); } if (inputName == null && outputName == null) { // retrieve list of operations List operationList = portType.getOperations(); // try to find input and output names for the operation specified boolean found = false; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException( "Operation '" + operationName + "' is overloaded. " + "Please specify the operation in the form " + "'operationName:inputMessageName:outputMesssageName'" + " to distinguish it"); } found = true; Input opInput = op.getInput(); inputName = (opInput.getName() == null) ? null : opInput.getName(); Output opOutput = op.getOutput(); outputName = (opOutput.getName() == null) ? null : opOutput.getName(); } } WSIFOperation operation = port.createOperation(operationName, inputName, outputName); WSIFMessage input = operation.createInputMessage(); WSIFMessage output = operation.createOutputMessage(); WSIFMessage fault = operation.createFaultMessage(); // retrieve list of names and types for input and names for output List operationList = portType.getOperations(); // find portType operation to prepare in/oout message w/ parts boolean found = false; String[] outNames = new String[0]; Class[] outTypes = new Class[0]; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException("overloaded operations are not supported in this sample"); } found = true; //System.err.println("op = "+op); Input opInput = op.getInput(); // first determine list of arguments String[] inNames = new String[0]; Class[] inTypes = new Class[0]; if (opInput != null) { List parts = opInput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name, wsdlDefinition); int count = parts.size(); inNames = new String[count]; inTypes = new Class[count]; retrieveSignature(parts, inNames, inTypes); } // now prepare out parameters for (int pos = 0; pos < inNames.length; ++pos) { String arg = args[pos + argShift]; Object value = null; Class c = inTypes[pos]; if (c.equals(String.class)) { value = arg; } else if (c.equals(Double.TYPE)) { value = new Double(arg); } else if (c.equals(Float.TYPE)) { value = new Float(arg); } else if (c.equals(Integer.TYPE)) { value = new Integer(arg); } else if (c.equals(Boolean.TYPE)) { value = Boolean.valueOf(arg); } else { throw new RuntimeException("not know how to convert '" + arg + "' into " + c); } input.setObjectPart(inNames[pos], value); } Output opOutput = op.getOutput(); if (opOutput != null) { List parts = opOutput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name + "Response", wsdlDefinition); int count = parts.size(); outNames = new String[count]; outTypes = new Class[count]; retrieveSignature(parts, outNames, outTypes); } } if (!found) { throw new RuntimeException( "no operation " + operationName + " was found in port type " + portType.getQName()); } System.out.println("Executing operation " + operationName); operation.executeRequestResponseOperation(input, output, fault); for (int pos = 0; pos < outNames.length; ++pos) { String name = outNames[pos]; map.put(name, output.getObjectPart(name)); } System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); } catch (WSDLException e) { e.printStackTrace(); System.out.println("" + "\n\n" + "#########################################################################\n" + "################### Warning From YAWL Engine ###################\n" + "#########################################################################\n" + "#### \n" + "#### \n" + "#### Engine failed to read the WSDL file needed to invoke \n" + "#### the service. This is either because: \n" + "#### a) The authenication settings are not correct. \n" + "#### This can be checked by pointing a browser to \n" + "#### http://localhost:8080/yawlWSInvoker and \n" + "#### following the on screen instructions. \n" + "#### b) The WSDL at " + wsdlLocation + " is currently\n" + "#### unavailable. \n" + "#### \n" + "#### \n" + "#########################################################################\n" + "#########################################################################\n" + "#########################################################################\n" + "\n\n"); } catch (WSIFException e) { e.printStackTrace(); } return map; } private static void retrieveSignature( List parts, String[] names, Class[] types) { // get parts in correct order for (int i = 0; i < names.length; ++i) { Part part = (Part) parts.get(i); names[i] = part.getName(); QName partType = part.getTypeName(); if (partType == null) { partType = part.getElementName(); } if (partType == null) { throw new RuntimeException( "part " + names[i] + " must have type name declared"); } // only limited number of types is supported // cheerfully ignoring schema namespace ... String s = partType.getLocalPart(); if ("string".equals(s)) { types[i] = String.class; } else if ("double".equals(s) || "decimal".equals(s)) { types[i] = Double.TYPE; } else if ("float".equals(s)) { types[i] = Float.TYPE; } else if ("int".equals(s)) { types[i] = Integer.TYPE; } else if ("boolean".equals(s)) { types[i] = Boolean.TYPE; } else { throw new RuntimeException( "part type " + partType + " not supported in this sample"); } } } /** * Unwraps the top level part if this a wrapped DocLit message. */ private static void unWrapIfWrappedDocLit(List parts, String operationName, Definition def) throws WSIFException { Part p = ProviderUtils.getWrapperPart(parts, operationName); if (p != null) { List unWrappedParts = ProviderUtils.unWrapPart(p, def); if (unWrappedParts != null && unWrappedParts.size() > 0) { parts.remove(p); parts.addAll(unWrappedParts); } } } }
yawlfoundation/yawl
src/org/yawlfoundation/yawl/wsif/WSIFInvoker.java
3,906
// get parts in correct order
line_comment
nl
/* * Copyright (c) 2004-2020 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL 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. * * YAWL 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 YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.wsif; import org.yawlfoundation.yawl.engine.interfce.AuthenticationConfig; import org.apache.wsif.*; import org.apache.wsif.providers.ProviderUtils; import org.apache.wsif.providers.soap.apachesoap.WSIFDynamicProvider_ApacheSOAP; import org.apache.wsif.util.WSIFPluggableProviders; import org.apache.wsif.util.WSIFUtils; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import javax.wsdl.*; import javax.xml.namespace.QName; import java.util.*; /** * @author Sanjiva Weerawarana * @author Alekander Slominski * @author Lachlan Aldred */ public class WSIFInvoker { public static HashMap invokeMethod(String wsdlLocation, String portName, String operationName, Element inputDataDoc, AuthenticationConfig authconfig) { System.out.println("XMLOutputter = " + new XMLOutputter(Format.getPrettyFormat()).outputString(inputDataDoc)); System.out.println("wsdl location = " + wsdlLocation); System.out.println("port name = " + portName); System.out.println("operation name = " + operationName); List<String> argsV = new ArrayList<String>(); for (Element element : inputDataDoc.getChildren()) { argsV.add(element.getText()); } String[] args = new String[argsV.size()]; argsV.toArray(args); return invokeMethod( wsdlLocation, operationName, null, null, portName, null, args, 0, authconfig); } public static HashMap invokeMethod(String wsdlLocation, String operationName, String inputName, String outputName, String portName, String protocol, String[] args, int argShift, AuthenticationConfig authconfig) { for (String arg : args) { System.out.println("argValue: " + arg); } HashMap map = new HashMap(); try { String serviceNS = null; String serviceName = null; String portTypeNS = null; String portTypeName = null; // The default SOAP provider is the Apache AXIS provider. If soap was specified // then change the Apache SOAP provider if ("soap".equals(protocol)) { WSIFPluggableProviders.overrideDefaultProvider( "http://schemas.xmlsoap.org/wsdl/soap/", new WSIFDynamicProvider_ApacheSOAP()); } System.out.println("Reading WSDL document from '" + wsdlLocation + "'"); Definition wsdlDefinition = null; if (authconfig == null) { return null; } String userName = authconfig.getUserName(); String password = authconfig.getPassword(); String proxyHost = authconfig.getProxyHost(); String proxyPort = authconfig.getProxyPort(); if (userName != null && userName.length() > 0 && password != null && password.length() > 0 && proxyHost != null && password.length() > 0 && proxyPort != null && proxyPort.length() > 0) { System.getProperties().put("http.proxyHost", proxyHost); System.getProperties().put("http.proxyPort", proxyPort); java.net.PasswordAuthentication pa = new java.net.PasswordAuthentication( userName, password.toCharArray()); wsdlDefinition = WSIFUtils.readWSDLThroughAuthProxy(wsdlLocation, pa); } else { wsdlDefinition = WSIFUtils.readWSDL(null, wsdlLocation); } System.out.println("Preparing WSIF dynamic invocation"); Service service = WSIFUtils.selectService(wsdlDefinition, serviceNS, serviceName); Map portTypes = WSIFUtils.getAllItems(wsdlDefinition, "PortType"); // Really there should be a way to specify the portType // for now just try to find one with the portName if (portTypes.size() > 1 && portName != null) { for (Iterator i = portTypes.keySet().iterator(); i.hasNext();) { QName qn = (QName) i.next(); System.out.println("qn.getLocalPart() = " + qn.getLocalPart()); if (portName.equals(qn.getLocalPart())) { portTypeName = qn.getLocalPart(); portTypeNS = qn.getNamespaceURI(); System.out.println("portTypeName = " + portTypeName); System.out.println("portTypeNS = " + portTypeNS); break; } } } PortType portType = WSIFUtils.selectPortType(wsdlDefinition, portTypeNS, portTypeName); WSIFServiceFactory factory = WSIFServiceFactory.newInstance(); WSIFService dpf = factory.getService(wsdlDefinition, service, portType); WSIFMessage ctx = dpf.getContext(); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_USER, authconfig.getUserName()); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_PSWD, authconfig.getPassword()); dpf.setContext(ctx); WSIFPort port = null; if (portName == null) { port = dpf.getPort(); } else { port = dpf.getPort(portName); } if (inputName == null && outputName == null) { // retrieve list of operations List operationList = portType.getOperations(); // try to find input and output names for the operation specified boolean found = false; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException( "Operation '" + operationName + "' is overloaded. " + "Please specify the operation in the form " + "'operationName:inputMessageName:outputMesssageName'" + " to distinguish it"); } found = true; Input opInput = op.getInput(); inputName = (opInput.getName() == null) ? null : opInput.getName(); Output opOutput = op.getOutput(); outputName = (opOutput.getName() == null) ? null : opOutput.getName(); } } WSIFOperation operation = port.createOperation(operationName, inputName, outputName); WSIFMessage input = operation.createInputMessage(); WSIFMessage output = operation.createOutputMessage(); WSIFMessage fault = operation.createFaultMessage(); // retrieve list of names and types for input and names for output List operationList = portType.getOperations(); // find portType operation to prepare in/oout message w/ parts boolean found = false; String[] outNames = new String[0]; Class[] outTypes = new Class[0]; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException("overloaded operations are not supported in this sample"); } found = true; //System.err.println("op = "+op); Input opInput = op.getInput(); // first determine list of arguments String[] inNames = new String[0]; Class[] inTypes = new Class[0]; if (opInput != null) { List parts = opInput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name, wsdlDefinition); int count = parts.size(); inNames = new String[count]; inTypes = new Class[count]; retrieveSignature(parts, inNames, inTypes); } // now prepare out parameters for (int pos = 0; pos < inNames.length; ++pos) { String arg = args[pos + argShift]; Object value = null; Class c = inTypes[pos]; if (c.equals(String.class)) { value = arg; } else if (c.equals(Double.TYPE)) { value = new Double(arg); } else if (c.equals(Float.TYPE)) { value = new Float(arg); } else if (c.equals(Integer.TYPE)) { value = new Integer(arg); } else if (c.equals(Boolean.TYPE)) { value = Boolean.valueOf(arg); } else { throw new RuntimeException("not know how to convert '" + arg + "' into " + c); } input.setObjectPart(inNames[pos], value); } Output opOutput = op.getOutput(); if (opOutput != null) { List parts = opOutput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name + "Response", wsdlDefinition); int count = parts.size(); outNames = new String[count]; outTypes = new Class[count]; retrieveSignature(parts, outNames, outTypes); } } if (!found) { throw new RuntimeException( "no operation " + operationName + " was found in port type " + portType.getQName()); } System.out.println("Executing operation " + operationName); operation.executeRequestResponseOperation(input, output, fault); for (int pos = 0; pos < outNames.length; ++pos) { String name = outNames[pos]; map.put(name, output.getObjectPart(name)); } System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); } catch (WSDLException e) { e.printStackTrace(); System.out.println("" + "\n\n" + "#########################################################################\n" + "################### Warning From YAWL Engine ###################\n" + "#########################################################################\n" + "#### \n" + "#### \n" + "#### Engine failed to read the WSDL file needed to invoke \n" + "#### the service. This is either because: \n" + "#### a) The authenication settings are not correct. \n" + "#### This can be checked by pointing a browser to \n" + "#### http://localhost:8080/yawlWSInvoker and \n" + "#### following the on screen instructions. \n" + "#### b) The WSDL at " + wsdlLocation + " is currently\n" + "#### unavailable. \n" + "#### \n" + "#### \n" + "#########################################################################\n" + "#########################################################################\n" + "#########################################################################\n" + "\n\n"); } catch (WSIFException e) { e.printStackTrace(); } return map; } private static void retrieveSignature( List parts, String[] names, Class[] types) { // get parts<SUF> for (int i = 0; i < names.length; ++i) { Part part = (Part) parts.get(i); names[i] = part.getName(); QName partType = part.getTypeName(); if (partType == null) { partType = part.getElementName(); } if (partType == null) { throw new RuntimeException( "part " + names[i] + " must have type name declared"); } // only limited number of types is supported // cheerfully ignoring schema namespace ... String s = partType.getLocalPart(); if ("string".equals(s)) { types[i] = String.class; } else if ("double".equals(s) || "decimal".equals(s)) { types[i] = Double.TYPE; } else if ("float".equals(s)) { types[i] = Float.TYPE; } else if ("int".equals(s)) { types[i] = Integer.TYPE; } else if ("boolean".equals(s)) { types[i] = Boolean.TYPE; } else { throw new RuntimeException( "part type " + partType + " not supported in this sample"); } } } /** * Unwraps the top level part if this a wrapped DocLit message. */ private static void unWrapIfWrappedDocLit(List parts, String operationName, Definition def) throws WSIFException { Part p = ProviderUtils.getWrapperPart(parts, operationName); if (p != null) { List unWrappedParts = ProviderUtils.unWrapPart(p, def); if (unWrappedParts != null && unWrappedParts.size() > 0) { parts.remove(p); parts.addAll(unWrappedParts); } } } }
83731_15
package org.apache.lucene.analysis.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. */ import java.util.Map; /** * * A stemmer for Dutch words. The algorithm is an implementation of * the <a href="http://snowball.tartarus.org/algorithms/dutch/stemmer.html">dutch stemming</a> * algorithm in Martin Porter's snowball project. * * @author Edwin de Jonge (ejne at cbs.nl) */ public class DutchStemmer { /** * Buffer for the terms while stemming them. */ private StringBuffer sb = new StringBuffer(); private boolean _removedE; private Map _stemDict; private int _R1; private int _R2; //TODO convert to internal /* * Stemms the given term to an unique <tt>discriminator</tt>. * * @param term The term that should be stemmed. * @return Discriminator for <tt>term</tt> */ public String stem(String term) { term = term.toLowerCase(); if (!isStemmable(term)) return term; if (_stemDict != null && _stemDict.containsKey(term)) if (_stemDict.get(term) instanceof String) return (String) _stemDict.get(term); else return null; // Reset the StringBuffer. sb.delete(0, sb.length()); sb.insert(0, term); // Stemming starts here... substitute(sb); storeYandI(sb); _R1 = getRIndex(sb, 0); _R1 = Math.max(3, _R1); step1(sb); step2(sb); _R2 = getRIndex(sb, _R1); step3a(sb); step3b(sb); step4(sb); reStoreYandI(sb); return sb.toString(); } private boolean enEnding(StringBuffer sb) { String[] enend = new String[]{"ene", "en"}; for (int i = 0; i < enend.length; i++) { String end = enend[i]; String s = sb.toString(); int index = s.length() - end.length(); if (s.endsWith(end) && index >= _R1 && isValidEnEnding(sb, index - 1) ) { sb.delete(index, index + end.length()); unDouble(sb, index); return true; } } return false; } private void step1(StringBuffer sb) { if (_R1 >= sb.length()) return; String s = sb.toString(); int lengthR1 = sb.length() - _R1; int index; if (s.endsWith("heden")) { sb.replace(_R1, lengthR1 + _R1, sb.substring(_R1, lengthR1 + _R1).replaceAll("heden", "heid")); return; } if (enEnding(sb)) return; if (s.endsWith("se") && (index = s.length() - 2) >= _R1 && isValidSEnding(sb, index - 1) ) { sb.delete(index, index + 2); return; } if (s.endsWith("s") && (index = s.length() - 1) >= _R1 && isValidSEnding(sb, index - 1)) { sb.delete(index, index + 1); } } /** * Delete suffix e if in R1 and * preceded by a non-vowel, and then undouble the ending * * @param sb String being stemmed */ private void step2(StringBuffer sb) { _removedE = false; if (_R1 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 1; if (index >= _R1 && s.endsWith("e") && !isVowel(sb.charAt(index - 1))) { sb.delete(index, index + 1); unDouble(sb); _removedE = true; } } /** * Delete "heid" * * @param sb String being stemmed */ private void step3a(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 4; if (s.endsWith("heid") && index >= _R2 && sb.charAt(index - 1) != 'c') { sb.delete(index, index + 4); //remove heid enEnding(sb); } } /** * <p>A d-suffix, or derivational suffix, enables a new word, * often with a different grammatical category, or with a different * sense, to be built from another word. Whether a d-suffix can be * attached is discovered not from the rules of grammar, but by * referring to a dictionary. So in English, ness can be added to * certain adjectives to form corresponding nouns (littleness, * kindness, foolishness ...) but not to all adjectives * (not for example, to big, cruel, wise ...) d-suffixes can be * used to change meaning, often in rather exotic ways.</p> * Remove "ing", "end", "ig", "lijk", "baar" and "bar" * * @param sb String being stemmed */ private void step3b(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = 0; if ((s.endsWith("end") || s.endsWith("ing")) && (index = s.length() - 3) >= _R2) { sb.delete(index, index + 3); if (sb.charAt(index - 2) == 'i' && sb.charAt(index - 1) == 'g') { if (sb.charAt(index - 3) != 'e' & index - 2 >= _R2) { index -= 2; sb.delete(index, index + 2); } } else { unDouble(sb, index); } return; } if (s.endsWith("ig") && (index = s.length() - 2) >= _R2 ) { if (sb.charAt(index - 1) != 'e') sb.delete(index, index + 2); return; } if (s.endsWith("lijk") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); step2(sb); return; } if (s.endsWith("baar") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); return; } if (s.endsWith("bar") && (index = s.length() - 3) >= _R2 ) { if (_removedE) sb.delete(index, index + 3); return; } } /** * undouble vowel * If the words ends CVD, where C is a non-vowel, D is a non-vowel other than I, and V is double a, e, o or u, remove one of the vowels from V (for example, maan -> man, brood -> brod). * * @param sb String being stemmed */ private void step4(StringBuffer sb) { if (sb.length() < 4) return; String end = sb.substring(sb.length() - 4, sb.length()); char c = end.charAt(0); char v1 = end.charAt(1); char v2 = end.charAt(2); char d = end.charAt(3); if (v1 == v2 && d != 'I' && v1 != 'i' && isVowel(v1) && !isVowel(d) && !isVowel(c)) { sb.delete(sb.length() - 2, sb.length() - 1); } } /** * Checks if a term could be stemmed. * * @return true if, and only if, the given term consists in letters. */ private boolean isStemmable(String term) { for (int c = 0; c < term.length(); c++) { if (!Character.isLetter(term.charAt(c))) return false; } return true; } /** * Substitute ä, ë, ï, ö, ü, á , é, í, ó, ú */ private void substitute(StringBuffer buffer) { for (int i = 0; i < buffer.length(); i++) { switch (buffer.charAt(i)) { case 'ä': case 'á': { buffer.setCharAt(i, 'a'); break; } case 'ë': case 'é': { buffer.setCharAt(i, 'e'); break; } case 'ü': case 'ú': { buffer.setCharAt(i, 'u'); break; } case 'ï': case 'i': { buffer.setCharAt(i, 'i'); break; } case 'ö': case 'ó': { buffer.setCharAt(i, 'o'); break; } } } } /*private boolean isValidSEnding(StringBuffer sb) { return isValidSEnding(sb, sb.length() - 1); }*/ private boolean isValidSEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c) || c == 'j') return false; return true; } /*private boolean isValidEnEnding(StringBuffer sb) { return isValidEnEnding(sb, sb.length() - 1); }*/ private boolean isValidEnEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c)) return false; if (c < 3) return false; // ends with "gem"? if (c == 'm' && sb.charAt(index - 2) == 'g' && sb.charAt(index - 1) == 'e') return false; return true; } private void unDouble(StringBuffer sb) { unDouble(sb, sb.length()); } private void unDouble(StringBuffer sb, int endIndex) { String s = sb.substring(0, endIndex); if (s.endsWith("kk") || s.endsWith("tt") || s.endsWith("dd") || s.endsWith("nn") || s.endsWith("mm") || s.endsWith("ff")) { sb.delete(endIndex - 1, endIndex); } } private int getRIndex(StringBuffer sb, int start) { if (start == 0) start = 1; int i = start; for (; i < sb.length(); i++) { //first non-vowel preceded by a vowel if (!isVowel(sb.charAt(i)) && isVowel(sb.charAt(i - 1))) { return i + 1; } } return i + 1; } private void storeYandI(StringBuffer sb) { if (sb.charAt(0) == 'y') sb.setCharAt(0, 'Y'); int last = sb.length() - 1; for (int i = 1; i < last; i++) { switch (sb.charAt(i)) { case 'i': { if (isVowel(sb.charAt(i - 1)) && isVowel(sb.charAt(i + 1)) ) sb.setCharAt(i, 'I'); break; } case 'y': { if (isVowel(sb.charAt(i - 1))) sb.setCharAt(i, 'Y'); break; } } } if (last > 0 && sb.charAt(last) == 'y' && isVowel(sb.charAt(last - 1))) sb.setCharAt(last, 'Y'); } private void reStoreYandI(StringBuffer sb) { String tmp = sb.toString(); sb.delete(0, sb.length()); sb.insert(0, tmp.replaceAll("I", "i").replaceAll("Y", "y")); } private boolean isVowel(char c) { switch (c) { case 'e': case 'a': case 'o': case 'i': case 'u': case 'y': case 'è': { return true; } } return false; } void setStemDictionary(Map dict) { _stemDict = dict; } }
ybv/lucene
contrib/analyzers/src/java/org/apache/lucene/analysis/nl/DutchStemmer.java
3,790
// ends with "gem"?
line_comment
nl
package org.apache.lucene.analysis.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. */ import java.util.Map; /** * * A stemmer for Dutch words. The algorithm is an implementation of * the <a href="http://snowball.tartarus.org/algorithms/dutch/stemmer.html">dutch stemming</a> * algorithm in Martin Porter's snowball project. * * @author Edwin de Jonge (ejne at cbs.nl) */ public class DutchStemmer { /** * Buffer for the terms while stemming them. */ private StringBuffer sb = new StringBuffer(); private boolean _removedE; private Map _stemDict; private int _R1; private int _R2; //TODO convert to internal /* * Stemms the given term to an unique <tt>discriminator</tt>. * * @param term The term that should be stemmed. * @return Discriminator for <tt>term</tt> */ public String stem(String term) { term = term.toLowerCase(); if (!isStemmable(term)) return term; if (_stemDict != null && _stemDict.containsKey(term)) if (_stemDict.get(term) instanceof String) return (String) _stemDict.get(term); else return null; // Reset the StringBuffer. sb.delete(0, sb.length()); sb.insert(0, term); // Stemming starts here... substitute(sb); storeYandI(sb); _R1 = getRIndex(sb, 0); _R1 = Math.max(3, _R1); step1(sb); step2(sb); _R2 = getRIndex(sb, _R1); step3a(sb); step3b(sb); step4(sb); reStoreYandI(sb); return sb.toString(); } private boolean enEnding(StringBuffer sb) { String[] enend = new String[]{"ene", "en"}; for (int i = 0; i < enend.length; i++) { String end = enend[i]; String s = sb.toString(); int index = s.length() - end.length(); if (s.endsWith(end) && index >= _R1 && isValidEnEnding(sb, index - 1) ) { sb.delete(index, index + end.length()); unDouble(sb, index); return true; } } return false; } private void step1(StringBuffer sb) { if (_R1 >= sb.length()) return; String s = sb.toString(); int lengthR1 = sb.length() - _R1; int index; if (s.endsWith("heden")) { sb.replace(_R1, lengthR1 + _R1, sb.substring(_R1, lengthR1 + _R1).replaceAll("heden", "heid")); return; } if (enEnding(sb)) return; if (s.endsWith("se") && (index = s.length() - 2) >= _R1 && isValidSEnding(sb, index - 1) ) { sb.delete(index, index + 2); return; } if (s.endsWith("s") && (index = s.length() - 1) >= _R1 && isValidSEnding(sb, index - 1)) { sb.delete(index, index + 1); } } /** * Delete suffix e if in R1 and * preceded by a non-vowel, and then undouble the ending * * @param sb String being stemmed */ private void step2(StringBuffer sb) { _removedE = false; if (_R1 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 1; if (index >= _R1 && s.endsWith("e") && !isVowel(sb.charAt(index - 1))) { sb.delete(index, index + 1); unDouble(sb); _removedE = true; } } /** * Delete "heid" * * @param sb String being stemmed */ private void step3a(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 4; if (s.endsWith("heid") && index >= _R2 && sb.charAt(index - 1) != 'c') { sb.delete(index, index + 4); //remove heid enEnding(sb); } } /** * <p>A d-suffix, or derivational suffix, enables a new word, * often with a different grammatical category, or with a different * sense, to be built from another word. Whether a d-suffix can be * attached is discovered not from the rules of grammar, but by * referring to a dictionary. So in English, ness can be added to * certain adjectives to form corresponding nouns (littleness, * kindness, foolishness ...) but not to all adjectives * (not for example, to big, cruel, wise ...) d-suffixes can be * used to change meaning, often in rather exotic ways.</p> * Remove "ing", "end", "ig", "lijk", "baar" and "bar" * * @param sb String being stemmed */ private void step3b(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = 0; if ((s.endsWith("end") || s.endsWith("ing")) && (index = s.length() - 3) >= _R2) { sb.delete(index, index + 3); if (sb.charAt(index - 2) == 'i' && sb.charAt(index - 1) == 'g') { if (sb.charAt(index - 3) != 'e' & index - 2 >= _R2) { index -= 2; sb.delete(index, index + 2); } } else { unDouble(sb, index); } return; } if (s.endsWith("ig") && (index = s.length() - 2) >= _R2 ) { if (sb.charAt(index - 1) != 'e') sb.delete(index, index + 2); return; } if (s.endsWith("lijk") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); step2(sb); return; } if (s.endsWith("baar") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); return; } if (s.endsWith("bar") && (index = s.length() - 3) >= _R2 ) { if (_removedE) sb.delete(index, index + 3); return; } } /** * undouble vowel * If the words ends CVD, where C is a non-vowel, D is a non-vowel other than I, and V is double a, e, o or u, remove one of the vowels from V (for example, maan -> man, brood -> brod). * * @param sb String being stemmed */ private void step4(StringBuffer sb) { if (sb.length() < 4) return; String end = sb.substring(sb.length() - 4, sb.length()); char c = end.charAt(0); char v1 = end.charAt(1); char v2 = end.charAt(2); char d = end.charAt(3); if (v1 == v2 && d != 'I' && v1 != 'i' && isVowel(v1) && !isVowel(d) && !isVowel(c)) { sb.delete(sb.length() - 2, sb.length() - 1); } } /** * Checks if a term could be stemmed. * * @return true if, and only if, the given term consists in letters. */ private boolean isStemmable(String term) { for (int c = 0; c < term.length(); c++) { if (!Character.isLetter(term.charAt(c))) return false; } return true; } /** * Substitute ä, ë, ï, ö, ü, á , é, í, ó, ú */ private void substitute(StringBuffer buffer) { for (int i = 0; i < buffer.length(); i++) { switch (buffer.charAt(i)) { case 'ä': case 'á': { buffer.setCharAt(i, 'a'); break; } case 'ë': case 'é': { buffer.setCharAt(i, 'e'); break; } case 'ü': case 'ú': { buffer.setCharAt(i, 'u'); break; } case 'ï': case 'i': { buffer.setCharAt(i, 'i'); break; } case 'ö': case 'ó': { buffer.setCharAt(i, 'o'); break; } } } } /*private boolean isValidSEnding(StringBuffer sb) { return isValidSEnding(sb, sb.length() - 1); }*/ private boolean isValidSEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c) || c == 'j') return false; return true; } /*private boolean isValidEnEnding(StringBuffer sb) { return isValidEnEnding(sb, sb.length() - 1); }*/ private boolean isValidEnEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c)) return false; if (c < 3) return false; // ends with<SUF> if (c == 'm' && sb.charAt(index - 2) == 'g' && sb.charAt(index - 1) == 'e') return false; return true; } private void unDouble(StringBuffer sb) { unDouble(sb, sb.length()); } private void unDouble(StringBuffer sb, int endIndex) { String s = sb.substring(0, endIndex); if (s.endsWith("kk") || s.endsWith("tt") || s.endsWith("dd") || s.endsWith("nn") || s.endsWith("mm") || s.endsWith("ff")) { sb.delete(endIndex - 1, endIndex); } } private int getRIndex(StringBuffer sb, int start) { if (start == 0) start = 1; int i = start; for (; i < sb.length(); i++) { //first non-vowel preceded by a vowel if (!isVowel(sb.charAt(i)) && isVowel(sb.charAt(i - 1))) { return i + 1; } } return i + 1; } private void storeYandI(StringBuffer sb) { if (sb.charAt(0) == 'y') sb.setCharAt(0, 'Y'); int last = sb.length() - 1; for (int i = 1; i < last; i++) { switch (sb.charAt(i)) { case 'i': { if (isVowel(sb.charAt(i - 1)) && isVowel(sb.charAt(i + 1)) ) sb.setCharAt(i, 'I'); break; } case 'y': { if (isVowel(sb.charAt(i - 1))) sb.setCharAt(i, 'Y'); break; } } } if (last > 0 && sb.charAt(last) == 'y' && isVowel(sb.charAt(last - 1))) sb.setCharAt(last, 'Y'); } private void reStoreYandI(StringBuffer sb) { String tmp = sb.toString(); sb.delete(0, sb.length()); sb.insert(0, tmp.replaceAll("I", "i").replaceAll("Y", "y")); } private boolean isVowel(char c) { switch (c) { case 'e': case 'a': case 'o': case 'i': case 'u': case 'y': case 'è': { return true; } } return false; } void setStemDictionary(Map dict) { _stemDict = dict; } }
96302_3
package main.java.gameObjects.model.brick; /** * Brick Types that can be used * @author Emily * */ public enum BrickType { /** * Clay Brick */ CLAY, /** * Steek Brick */ STEEL, /** * Cement Brick */ CEMENT, /** * Vibranium Brick */ VIBRANIUM, /** * Special Brick */ SPECIAL, /** * Health Brick */ HEALTH, }
yenxuan1381/brick-breaker
src/main/java/gameObjects/model/brick/BrickType.java
177
/** * Cement Brick */
block_comment
nl
package main.java.gameObjects.model.brick; /** * Brick Types that can be used * @author Emily * */ public enum BrickType { /** * Clay Brick */ CLAY, /** * Steek Brick */ STEEL, /** * Cement Brick <SUF>*/ CEMENT, /** * Vibranium Brick */ VIBRANIUM, /** * Special Brick */ SPECIAL, /** * Health Brick */ HEALTH, }
106585_30
// 参考:https://www.geeksforgeeks.org/bitwise-operators-in-java/ // Java program to illustrate // bitwise operators public class operators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise and // 0101 & 0111=0101 = 5 System.out.println("a&b = " + (a & b)); // bitwise or // 0101 | 0111=0111 = 7 System.out.println("a|b = " + (a | b)); // bitwise xor // 0101 ^ 0111=0010 = 2 System.out.println("a^b = " + (a ^ b)); // bitwise not // ~0101=1010 // will give 2's complement of 1010 = -6 System.out.println("~a = " + ~a); // can also be combined with // assignment operator to provide shorthand // assignment // a=a&b a &= b; System.out.println("a= " + a); // left shift operator // 0000 0101<<2 =0001 0100(20) // similar to 5*(2^2) System.out.println("a<<2 = " + (a << 2)); // right shift operator // 0000 0101 >> 2 =0000 0001(1) // similar to 5/(2^2) System.out.println("a>>2 = " + (a >> 2)); // unsigned right shift operator System.out.println("a>>>2 = " + (a >>> 2)); } } class Solution { // 实现 changToOne(num, K), 将 num 的二进制的第 K 位设置为 1 // changToOne(2, 1) -> 3,2 的二进制为 10,将其第一位设为 1 得到 3 public int changToOne(int num, int K) { int bit = 1; bit = bit << k-1; return num | bit; } // 实现 changToZero(num, K), 将 num 的二进制的第 K 位设置为 0 // changToOne(2, 2) -> 0,2 的二进制为 10,将其第二位设为 0 得到 0 public int changToZero(int num, int K) { int bit = 1; bit = bit << k-1; bit = ~bit; return num & bit; } // 实现 reverseK(num, K), 将 num 的二进制的第 K 位取反 // reverseK(2, 1) -> 3,2 的二进制为 10,将其第一位取反得到 3 public int reverseK(int num, int K) { int bit = 1; bit = bit << k-1; return num ^ bit; } // 实现 cal(num),计算 num 的二进制中 1 的数量 // cal(2) -> 1,2 的二进制为 10,1 的数量为 1 public int cal(int num) { int res = 0; while (num != 0) { if ((num & 1) == 1) res++; num = num >> 1; } return res; } // 实现 check(num),判断 num 是否是 2 的非负整数次幂 // check(8) -> True // check(7) -> False public boolean check(int num) { // if (num <= 0) return false; // if (num == 1 || num%2 == 0) return true; // return false; num &= (num-1); return num == 0; } // 实现 delete(num),删除 num 最低有效位 // delete(2) -> 0,2 的二进制为 10,删除最低有效位得到 0 // delete(5) -> 4,5 的二进制为 101,删除最低有效位得到 4 public int delete(int num) { // int bit = 1; // while ((num & bit) == 0) bit = bit << 1; // return num ^ bit; return num & (num-1); } // 实现 loo(num),遍历 num 的所有非空子集合, // loo(5) -> [1, 4, 5],5 的二进制为 101,其非空子集合为 [001, 100, 101] public Set<Integer> loo(int num) { Set<Integer> res = new HashSet<>(); int i = 0; while (++i <= num) { if ((i & num) == i) res.add(i); } return res; } } // 求一个数的二进制的最高有效位(即最高的 1 在哪) int n = (int) (Math.log(num) / Math.log(2)); // 计算一个整数的二进制表示有几个 1 int num = 3; int bitCnt = Integer.bitCount(num);
yihaoye/data-structure-and-algorithm-study-notes
Tool Sets/Bitwise.java
1,324
// int bit = 1;
line_comment
nl
// 参考:https://www.geeksforgeeks.org/bitwise-operators-in-java/ // Java program to illustrate // bitwise operators public class operators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise and // 0101 & 0111=0101 = 5 System.out.println("a&b = " + (a & b)); // bitwise or // 0101 | 0111=0111 = 7 System.out.println("a|b = " + (a | b)); // bitwise xor // 0101 ^ 0111=0010 = 2 System.out.println("a^b = " + (a ^ b)); // bitwise not // ~0101=1010 // will give 2's complement of 1010 = -6 System.out.println("~a = " + ~a); // can also be combined with // assignment operator to provide shorthand // assignment // a=a&b a &= b; System.out.println("a= " + a); // left shift operator // 0000 0101<<2 =0001 0100(20) // similar to 5*(2^2) System.out.println("a<<2 = " + (a << 2)); // right shift operator // 0000 0101 >> 2 =0000 0001(1) // similar to 5/(2^2) System.out.println("a>>2 = " + (a >> 2)); // unsigned right shift operator System.out.println("a>>>2 = " + (a >>> 2)); } } class Solution { // 实现 changToOne(num, K), 将 num 的二进制的第 K 位设置为 1 // changToOne(2, 1) -> 3,2 的二进制为 10,将其第一位设为 1 得到 3 public int changToOne(int num, int K) { int bit = 1; bit = bit << k-1; return num | bit; } // 实现 changToZero(num, K), 将 num 的二进制的第 K 位设置为 0 // changToOne(2, 2) -> 0,2 的二进制为 10,将其第二位设为 0 得到 0 public int changToZero(int num, int K) { int bit = 1; bit = bit << k-1; bit = ~bit; return num & bit; } // 实现 reverseK(num, K), 将 num 的二进制的第 K 位取反 // reverseK(2, 1) -> 3,2 的二进制为 10,将其第一位取反得到 3 public int reverseK(int num, int K) { int bit = 1; bit = bit << k-1; return num ^ bit; } // 实现 cal(num),计算 num 的二进制中 1 的数量 // cal(2) -> 1,2 的二进制为 10,1 的数量为 1 public int cal(int num) { int res = 0; while (num != 0) { if ((num & 1) == 1) res++; num = num >> 1; } return res; } // 实现 check(num),判断 num 是否是 2 的非负整数次幂 // check(8) -> True // check(7) -> False public boolean check(int num) { // if (num <= 0) return false; // if (num == 1 || num%2 == 0) return true; // return false; num &= (num-1); return num == 0; } // 实现 delete(num),删除 num 最低有效位 // delete(2) -> 0,2 的二进制为 10,删除最低有效位得到 0 // delete(5) -> 4,5 的二进制为 101,删除最低有效位得到 4 public int delete(int num) { // int bit<SUF> // while ((num & bit) == 0) bit = bit << 1; // return num ^ bit; return num & (num-1); } // 实现 loo(num),遍历 num 的所有非空子集合, // loo(5) -> [1, 4, 5],5 的二进制为 101,其非空子集合为 [001, 100, 101] public Set<Integer> loo(int num) { Set<Integer> res = new HashSet<>(); int i = 0; while (++i <= num) { if ((i & num) == i) res.add(i); } return res; } } // 求一个数的二进制的最高有效位(即最高的 1 在哪) int n = (int) (Math.log(num) / Math.log(2)); // 计算一个整数的二进制表示有几个 1 int num = 3; int bitCnt = Integer.bitCount(num);
109270_2
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.deals; public final class R { public static final class attr { } public static final class dimen { public static final int Detail_horizontal_margin=0x7f050004; public static final int Detail_vertical_margin=0x7f050005; /** Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f05000d; public static final int coupon_horizontal_margin=0x7f050002; public static final int coupon_vertical_margin=0x7f050003; public static final int favor_vertical_margin=0x7f050007; public static final int fbtwitter_horizontal_margin=0x7f050009; public static final int fbtwitter_vertical_margin=0x7f05000a; public static final int messagebox_horizontal_margin=0x7f05000b; public static final int messagebox_vertical_margin=0x7f05000c; public static final int redeem_text_vertical_margin=0x7f050008; public static final int redeem_vertical_margin=0x7f050006; /** Default screen margins, per the Android Design guidelines. */ public static final int tiles_horizontal_margin=0x7f050000; public static final int tiles_vertical_margin=0x7f050001; } public static final class drawable { public static final int back=0x7f020000; public static final int background=0x7f020001; public static final int box=0x7f020002; public static final int box_signin_email=0x7f020003; public static final int btn_fb=0x7f020004; public static final int btn_fb_normal=0x7f020005; public static final int btn_fb_pressed=0x7f020006; public static final int couponcapitano=0x7f020007; public static final int couponcastile=0x7f020008; public static final int couponrexall=0x7f020009; public static final int couponsushiworld=0x7f02000a; public static final int coupontopsushi=0x7f02000b; public static final int detailsbutton=0x7f02000c; public static final int facebookbutton=0x7f02000d; public static final int favicon=0x7f02000e; public static final int favouritebutton=0x7f02000f; public static final int fbiconoff=0x7f020010; public static final int fbiconon=0x7f020011; public static final int ic_launcher=0x7f020012; public static final int logo=0x7f020013; public static final int messageboxgray=0x7f020014; public static final int navigationbar=0x7f020015; public static final int redeembutton=0x7f020016; public static final int redeemgreenicon=0x7f020017; public static final int removefavbutton=0x7f020018; public static final int search=0x7f020019; public static final int splash=0x7f02001a; public static final int takephotobutton=0x7f02001b; public static final int textbox=0x7f02001c; public static final int tile10=0x7f02001d; public static final int twitterbutton=0x7f02001e; public static final int twittericonoff=0x7f02001f; public static final int twittericonon=0x7f020020; } public static final class id { public static final int TextLayout=0x7f090005; public static final int action_settings=0x7f090043; public static final int bBack=0x7f090001; public static final int bFavor=0x7f09000f; public static final int bRedeem=0x7f09000a; public static final int bSearch=0x7f09002b; public static final int bStore=0x7f09000d; public static final int bar=0x7f090000; public static final int browser=0x7f090002; public static final int btnFbSignIn=0x7f090011; public static final int btnLoginTweet=0x7f090032; public static final int btnSearch=0x7f090036; public static final int btnTweet=0x7f090035; public static final int buttonLayout=0x7f090008; public static final int cbFacebook=0x7f090025; public static final int cbFbAutoLogin=0x7f090012; public static final int cbTwitter=0x7f090024; public static final int detailFavorLayout=0x7f09000b; public static final int detailLayout=0x7f09000c; public static final int etEmail=0x7f090010; public static final int etMessageBox=0x7f090028; public static final int etSearch=0x7f090015; public static final int etTweet=0x7f090034; public static final int favorLayout=0x7f09000e; public static final int highlight=0x7f09003a; public static final int hyphen=0x7f09003d; public static final int ivPhoto=0x7f090022; public static final int ivRedeemButton=0x7f090023; public static final int ivStore=0x7f090003; public static final int ivTakePhoto=0x7f09002a; public static final int ivTwitterUserImg=0x7f09003f; public static final int ivc=0x7f090004; public static final int layoutTwitter=0x7f090033; public static final int lvEvents=0x7f090038; public static final int lvTweets=0x7f090037; public static final int redeemLayout=0x7f090009; public static final int spDate=0x7f090013; public static final int t1=0x7f090016; public static final int t10=0x7f09001f; public static final int t11=0x7f090020; public static final int t12=0x7f090021; public static final int t13=0x7f09002c; public static final int t14=0x7f09002d; public static final int t15=0x7f09002e; public static final int t16=0x7f09002f; public static final int t17=0x7f090030; public static final int t18=0x7f090031; public static final int t2=0x7f090017; public static final int t3=0x7f090018; public static final int t4=0x7f090019; public static final int t5=0x7f09001a; public static final int t6=0x7f09001b; public static final int t7=0x7f09001c; public static final int t8=0x7f09001d; public static final int t9=0x7f09001e; public static final int tvDetail=0x7f090007; public static final int tvEndTime_event=0x7f09003e; public static final int tvHeader_event=0x7f090039; public static final int tvMainDis=0x7f090006; public static final int tvRedeem=0x7f090026; public static final int tvStartTime_event=0x7f09003c; public static final int tvTitle_event=0x7f09003b; public static final int tvTwitterDate=0x7f090041; public static final int tvTwitterTweet=0x7f090042; public static final int tvTwitterUser=0x7f090040; public static final int tvUnderCamera=0x7f090027; public static final int tvUnderMessageBox=0x7f090029; public static final int viewPager=0x7f090014; } public static final class layout { public static final int activity_browser=0x7f030000; public static final int activity_coupon=0x7f030001; public static final int activity_login=0x7f030002; public static final int activity_scheduler=0x7f030003; public static final int activity_search_favor=0x7f030004; public static final int activity_share=0x7f030005; public static final int activity_splash=0x7f030006; public static final int activity_tiles=0x7f030007; public static final int activity_twitterfeed=0x7f030008; public static final int fragment_day=0x7f030009; public static final int item_list_event=0x7f03000a; public static final int item_list_tweet=0x7f03000b; public static final int item_spinner=0x7f03000c; } public static final class menu { public static final int splash=0x7f080000; } public static final class raw { public static final int coupons=0x7f040000; public static final int jsondealsfile=0x7f040001; public static final int show=0x7f040002; public static final int tiles=0x7f040003; } public static final class string { public static final int Details=0x7f060004; public static final int action_settings=0x7f060001; public static final int app_id=0x7f060006; public static final int app_name=0x7f060000; public static final int hello_world=0x7f060002; public static final int link=0x7f060003; public static final int reedem_offer=0x7f060005; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f070000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f070001; } }
yixiu17/Dealshype
gen/com/example/deals/R.java
3,004
/** Default screen margins, per the Android Design guidelines. */
block_comment
nl
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.deals; public final class R { public static final class attr { } public static final class dimen { public static final int Detail_horizontal_margin=0x7f050004; public static final int Detail_vertical_margin=0x7f050005; /** Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f05000d; public static final int coupon_horizontal_margin=0x7f050002; public static final int coupon_vertical_margin=0x7f050003; public static final int favor_vertical_margin=0x7f050007; public static final int fbtwitter_horizontal_margin=0x7f050009; public static final int fbtwitter_vertical_margin=0x7f05000a; public static final int messagebox_horizontal_margin=0x7f05000b; public static final int messagebox_vertical_margin=0x7f05000c; public static final int redeem_text_vertical_margin=0x7f050008; public static final int redeem_vertical_margin=0x7f050006; /** Default screen margins,<SUF>*/ public static final int tiles_horizontal_margin=0x7f050000; public static final int tiles_vertical_margin=0x7f050001; } public static final class drawable { public static final int back=0x7f020000; public static final int background=0x7f020001; public static final int box=0x7f020002; public static final int box_signin_email=0x7f020003; public static final int btn_fb=0x7f020004; public static final int btn_fb_normal=0x7f020005; public static final int btn_fb_pressed=0x7f020006; public static final int couponcapitano=0x7f020007; public static final int couponcastile=0x7f020008; public static final int couponrexall=0x7f020009; public static final int couponsushiworld=0x7f02000a; public static final int coupontopsushi=0x7f02000b; public static final int detailsbutton=0x7f02000c; public static final int facebookbutton=0x7f02000d; public static final int favicon=0x7f02000e; public static final int favouritebutton=0x7f02000f; public static final int fbiconoff=0x7f020010; public static final int fbiconon=0x7f020011; public static final int ic_launcher=0x7f020012; public static final int logo=0x7f020013; public static final int messageboxgray=0x7f020014; public static final int navigationbar=0x7f020015; public static final int redeembutton=0x7f020016; public static final int redeemgreenicon=0x7f020017; public static final int removefavbutton=0x7f020018; public static final int search=0x7f020019; public static final int splash=0x7f02001a; public static final int takephotobutton=0x7f02001b; public static final int textbox=0x7f02001c; public static final int tile10=0x7f02001d; public static final int twitterbutton=0x7f02001e; public static final int twittericonoff=0x7f02001f; public static final int twittericonon=0x7f020020; } public static final class id { public static final int TextLayout=0x7f090005; public static final int action_settings=0x7f090043; public static final int bBack=0x7f090001; public static final int bFavor=0x7f09000f; public static final int bRedeem=0x7f09000a; public static final int bSearch=0x7f09002b; public static final int bStore=0x7f09000d; public static final int bar=0x7f090000; public static final int browser=0x7f090002; public static final int btnFbSignIn=0x7f090011; public static final int btnLoginTweet=0x7f090032; public static final int btnSearch=0x7f090036; public static final int btnTweet=0x7f090035; public static final int buttonLayout=0x7f090008; public static final int cbFacebook=0x7f090025; public static final int cbFbAutoLogin=0x7f090012; public static final int cbTwitter=0x7f090024; public static final int detailFavorLayout=0x7f09000b; public static final int detailLayout=0x7f09000c; public static final int etEmail=0x7f090010; public static final int etMessageBox=0x7f090028; public static final int etSearch=0x7f090015; public static final int etTweet=0x7f090034; public static final int favorLayout=0x7f09000e; public static final int highlight=0x7f09003a; public static final int hyphen=0x7f09003d; public static final int ivPhoto=0x7f090022; public static final int ivRedeemButton=0x7f090023; public static final int ivStore=0x7f090003; public static final int ivTakePhoto=0x7f09002a; public static final int ivTwitterUserImg=0x7f09003f; public static final int ivc=0x7f090004; public static final int layoutTwitter=0x7f090033; public static final int lvEvents=0x7f090038; public static final int lvTweets=0x7f090037; public static final int redeemLayout=0x7f090009; public static final int spDate=0x7f090013; public static final int t1=0x7f090016; public static final int t10=0x7f09001f; public static final int t11=0x7f090020; public static final int t12=0x7f090021; public static final int t13=0x7f09002c; public static final int t14=0x7f09002d; public static final int t15=0x7f09002e; public static final int t16=0x7f09002f; public static final int t17=0x7f090030; public static final int t18=0x7f090031; public static final int t2=0x7f090017; public static final int t3=0x7f090018; public static final int t4=0x7f090019; public static final int t5=0x7f09001a; public static final int t6=0x7f09001b; public static final int t7=0x7f09001c; public static final int t8=0x7f09001d; public static final int t9=0x7f09001e; public static final int tvDetail=0x7f090007; public static final int tvEndTime_event=0x7f09003e; public static final int tvHeader_event=0x7f090039; public static final int tvMainDis=0x7f090006; public static final int tvRedeem=0x7f090026; public static final int tvStartTime_event=0x7f09003c; public static final int tvTitle_event=0x7f09003b; public static final int tvTwitterDate=0x7f090041; public static final int tvTwitterTweet=0x7f090042; public static final int tvTwitterUser=0x7f090040; public static final int tvUnderCamera=0x7f090027; public static final int tvUnderMessageBox=0x7f090029; public static final int viewPager=0x7f090014; } public static final class layout { public static final int activity_browser=0x7f030000; public static final int activity_coupon=0x7f030001; public static final int activity_login=0x7f030002; public static final int activity_scheduler=0x7f030003; public static final int activity_search_favor=0x7f030004; public static final int activity_share=0x7f030005; public static final int activity_splash=0x7f030006; public static final int activity_tiles=0x7f030007; public static final int activity_twitterfeed=0x7f030008; public static final int fragment_day=0x7f030009; public static final int item_list_event=0x7f03000a; public static final int item_list_tweet=0x7f03000b; public static final int item_spinner=0x7f03000c; } public static final class menu { public static final int splash=0x7f080000; } public static final class raw { public static final int coupons=0x7f040000; public static final int jsondealsfile=0x7f040001; public static final int show=0x7f040002; public static final int tiles=0x7f040003; } public static final class string { public static final int Details=0x7f060004; public static final int action_settings=0x7f060001; public static final int app_id=0x7f060006; public static final int app_name=0x7f060000; public static final int hello_world=0x7f060002; public static final int link=0x7f060003; public static final int reedem_offer=0x7f060005; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f070000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f070001; } }
204782_3
import java.util.Scanner; public class Battleship { public static Scanner reader = new Scanner(System.in); public static void main(String[] args) { System.out.println("JAVA BATTLESHIP - ** Yuval Marcus **"); System.out.println("\nPlayer SETUP:"); Player userPlayer = new Player(); setup(userPlayer); System.out.println("Computer SETUP...DONE...PRESS ENTER TO CONTINUE..."); reader.nextLine(); reader.nextLine(); Player computer = new Player(); setupComputer(computer); System.out.println("\nCOMPUTER GRID (FOR DEBUG)..."); computer.playerGrid.printShips(); String result = ""; while(true) { System.out.println(result); System.out.println("\nUSER MAKE GUESS:"); result = askForGuess(userPlayer, computer); if (userPlayer.playerGrid.hasLost()) { System.out.println("COMP HIT!...USER LOSES"); break; } else if (computer.playerGrid.hasLost()) { System.out.println("HIT!...COMPUTER LOSES"); break; } System.out.println("\nCOMPUTER IS MAKING GUESS..."); compMakeGuess(computer, userPlayer); } } private static void compMakeGuess(Player comp, Player user) { Randomizer rand = new Randomizer(); int row = rand.nextInt(0, 9); int col = rand.nextInt(0, 9); // While computer already guessed this posiiton, make a new random guess while (comp.oppGrid.alreadyGuessed(row, col)) { row = rand.nextInt(0, 9); col = rand.nextInt(0, 9); } if (user.playerGrid.hasShip(row, col)) { comp.oppGrid.markHit(row, col); user.playerGrid.markHit(row, col); System.out.println("COMP HIT AT " + convertIntToLetter(row) + convertCompColToRegular(col)); } else { comp.oppGrid.markMiss(row, col); user.playerGrid.markMiss(row, col); System.out.println("COMP MISS AT " + convertIntToLetter(row) + convertCompColToRegular(col)); } System.out.println("\nYOUR BOARD...PRESS ENTER TO CONTINUE..."); reader.nextLine(); user.playerGrid.printCombined(); System.out.println("PRESS ENTER TO CONTINUE..."); reader.nextLine(); } private static String askForGuess(Player p, Player opp) { System.out.println("Viewing My Guesses:"); p.oppGrid.printStatus(); int row = -1; int col = -1; String oldRow = "Z"; int oldCol = -1; while(true) { System.out.print("Type in row (A-J): "); String userInputRow = reader.next(); userInputRow = userInputRow.toUpperCase(); oldRow = userInputRow; row = convertLetterToInt(userInputRow); System.out.print("Type in column (1-10): "); col = reader.nextInt(); oldCol = col; col = convertUserColToProCol(col); //System.out.println("DEBUG: " + row + col); if (col >= 0 && col <= 9 && row != -1) break; System.out.println("Invalid location!"); } if (opp.playerGrid.hasShip(row, col)) { p.oppGrid.markHit(row, col); opp.playerGrid.markHit(row, col); return "** USER HIT AT " + oldRow + oldCol + " **"; } else { p.oppGrid.markMiss(row, col); opp.playerGrid.markMiss(row, col); return "** USER MISS AT " + oldRow + oldCol + " **"; } } private static void setup(Player p) { p.playerGrid.printShips(); System.out.println(); int counter = 1; int normCounter = 0; while (p.numOfShipsLeft() > 0) { for (Ship s: p.ships) { System.out.println("\nShip #" + counter + ": Length-" + s.getLength()); int row = -1; int col = -1; int dir = -1; while(true) { System.out.print("Type in row (A-J): "); String userInputRow = reader.next(); userInputRow = userInputRow.toUpperCase(); row = convertLetterToInt(userInputRow); System.out.print("Type in column (1-10): "); col = reader.nextInt(); col = convertUserColToProCol(col); System.out.print("Type in direction (0-H, 1-V): "); dir = reader.nextInt(); //System.out.println("DEBUG: " + row + col + dir); if (col >= 0 && col <= 9 && row != -1 && dir != -1) // Check valid input { if (!hasErrors(row, col, dir, p, normCounter)) // Check if errors will produce (out of bounds) { break; } } System.out.println("Invalid location!"); } //System.out.println("FURTHER DEBUG: row = " + row + "; col = " + col); p.ships[normCounter].setLocation(row, col); p.ships[normCounter].setDirection(dir); p.playerGrid.addShip(p.ships[normCounter]); p.playerGrid.printShips(); System.out.println(); System.out.println("You have " + p.numOfShipsLeft() + " remaining ships to place."); normCounter++; counter++; } } } private static void setupComputer(Player p) { System.out.println(); int counter = 1; int normCounter = 0; Randomizer rand = new Randomizer(); while (p.numOfShipsLeft() > 0) { for (Ship s: p.ships) { int row = rand.nextInt(0, 9); int col = rand.nextInt(0, 9); int dir = rand.nextInt(0, 1); //System.out.println("DEBUG: row-" + row + "; col-" + col + "; dir-" + dir); while (hasErrorsComp(row, col, dir, p, normCounter)) // while the random nums make error, start again { row = rand.nextInt(0, 9); col = rand.nextInt(0, 9); dir = rand.nextInt(0, 1); //System.out.println("AGAIN-DEBUG: row-" + row + "; col-" + col + "; dir-" + dir); } //System.out.println("FURTHER DEBUG: row = " + row + "; col = " + col); p.ships[normCounter].setLocation(row, col); p.ships[normCounter].setDirection(dir); p.playerGrid.addShip(p.ships[normCounter]); normCounter++; counter++; } } } private static boolean hasErrors(int row, int col, int dir, Player p, int count) { //System.out.println("DEBUG: count arg is " + count); int length = p.ships[count].getLength(); // Check if off grid - Horizontal if (dir == 0) { int checker = length + col; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { System.out.println("SHIP DOES NOT FIT"); return true; } } // Check if off grid - Vertical if (dir == 1) // VERTICAL { int checker = length + row; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { System.out.println("SHIP DOES NOT FIT"); return true; } } // Check if overlapping with another ship if (dir == 0) // Hortizontal { // For each location a ship occupies, check if ship is already there for (int i = col; i < col+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(row, i)) { System.out.println("THERE IS ALREADY A SHIP AT THAT LOCATION"); return true; } } } else if (dir == 1) // Vertical { // For each location a ship occupies, check if ship is already there for (int i = row; i < row+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(i, col)) { System.out.println("THERE IS ALREADY A SHIP AT THAT LOCATION"); return true; } } } return false; } private static boolean hasErrorsComp(int row, int col, int dir, Player p, int count) { //System.out.println("DEBUG: count arg is " + count); int length = p.ships[count].getLength(); // Check if off grid - Horizontal if (dir == 0) { int checker = length + col; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { return true; } } // Check if off grid - Vertical if (dir == 1) // VERTICAL { int checker = length + row; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { return true; } } // Check if overlapping with another ship if (dir == 0) // Hortizontal { // For each location a ship occupies, check if ship is already there for (int i = col; i < col+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(row, i)) { return true; } } } else if (dir == 1) // Vertical { // For each location a ship occupies, check if ship is already there for (int i = row; i < row+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(i, col)) { return true; } } } return false; } /*HELPER METHODS*/ private static int convertLetterToInt(String val) { int toReturn = -1; switch (val) { case "A": toReturn = 0; break; case "B": toReturn = 1; break; case "C": toReturn = 2; break; case "D": toReturn = 3; break; case "E": toReturn = 4; break; case "F": toReturn = 5; break; case "G": toReturn = 6; break; case "H": toReturn = 7; break; case "I": toReturn = 8; break; case "J": toReturn = 9; break; default: toReturn = -1; break; } return toReturn; } private static String convertIntToLetter(int val) { String toReturn = "Z"; switch (val) { case 0: toReturn = "A"; break; case 1: toReturn = "B"; break; case 2: toReturn = "C"; break; case 3: toReturn = "D"; break; case 4: toReturn = "E"; break; case 5: toReturn = "F"; break; case 6: toReturn = "G"; break; case 7: toReturn = "H"; break; case 8: toReturn = "I"; break; case 9: toReturn = "J"; break; default: toReturn = "Z"; break; } return toReturn; } private static int convertUserColToProCol(int val) { int toReturn = -1; switch (val) { case 1: toReturn = 0; break; case 2: toReturn = 1; break; case 3: toReturn = 2; break; case 4: toReturn = 3; break; case 5: toReturn = 4; break; case 6: toReturn = 5; break; case 7: toReturn = 6; break; case 8: toReturn = 7; break; case 9: toReturn = 8; break; case 10: toReturn = 9; break; default: toReturn = -1; break; } return toReturn; } private static int convertCompColToRegular(int val) { int toReturn = -1; switch (val) { case 0: toReturn = 1; break; case 1: toReturn = 2; break; case 2: toReturn = 3; break; case 3: toReturn = 4; break; case 4: toReturn = 5; break; case 5: toReturn = 6; break; case 6: toReturn = 7; break; case 7: toReturn = 8; break; case 8: toReturn = 9; break; case 9: toReturn = 10; break; default: toReturn = -1; break; } return toReturn; } }
ymarcus93/Java-Battleship
Battleship.java
4,187
// Check valid input
line_comment
nl
import java.util.Scanner; public class Battleship { public static Scanner reader = new Scanner(System.in); public static void main(String[] args) { System.out.println("JAVA BATTLESHIP - ** Yuval Marcus **"); System.out.println("\nPlayer SETUP:"); Player userPlayer = new Player(); setup(userPlayer); System.out.println("Computer SETUP...DONE...PRESS ENTER TO CONTINUE..."); reader.nextLine(); reader.nextLine(); Player computer = new Player(); setupComputer(computer); System.out.println("\nCOMPUTER GRID (FOR DEBUG)..."); computer.playerGrid.printShips(); String result = ""; while(true) { System.out.println(result); System.out.println("\nUSER MAKE GUESS:"); result = askForGuess(userPlayer, computer); if (userPlayer.playerGrid.hasLost()) { System.out.println("COMP HIT!...USER LOSES"); break; } else if (computer.playerGrid.hasLost()) { System.out.println("HIT!...COMPUTER LOSES"); break; } System.out.println("\nCOMPUTER IS MAKING GUESS..."); compMakeGuess(computer, userPlayer); } } private static void compMakeGuess(Player comp, Player user) { Randomizer rand = new Randomizer(); int row = rand.nextInt(0, 9); int col = rand.nextInt(0, 9); // While computer already guessed this posiiton, make a new random guess while (comp.oppGrid.alreadyGuessed(row, col)) { row = rand.nextInt(0, 9); col = rand.nextInt(0, 9); } if (user.playerGrid.hasShip(row, col)) { comp.oppGrid.markHit(row, col); user.playerGrid.markHit(row, col); System.out.println("COMP HIT AT " + convertIntToLetter(row) + convertCompColToRegular(col)); } else { comp.oppGrid.markMiss(row, col); user.playerGrid.markMiss(row, col); System.out.println("COMP MISS AT " + convertIntToLetter(row) + convertCompColToRegular(col)); } System.out.println("\nYOUR BOARD...PRESS ENTER TO CONTINUE..."); reader.nextLine(); user.playerGrid.printCombined(); System.out.println("PRESS ENTER TO CONTINUE..."); reader.nextLine(); } private static String askForGuess(Player p, Player opp) { System.out.println("Viewing My Guesses:"); p.oppGrid.printStatus(); int row = -1; int col = -1; String oldRow = "Z"; int oldCol = -1; while(true) { System.out.print("Type in row (A-J): "); String userInputRow = reader.next(); userInputRow = userInputRow.toUpperCase(); oldRow = userInputRow; row = convertLetterToInt(userInputRow); System.out.print("Type in column (1-10): "); col = reader.nextInt(); oldCol = col; col = convertUserColToProCol(col); //System.out.println("DEBUG: " + row + col); if (col >= 0 && col <= 9 && row != -1) break; System.out.println("Invalid location!"); } if (opp.playerGrid.hasShip(row, col)) { p.oppGrid.markHit(row, col); opp.playerGrid.markHit(row, col); return "** USER HIT AT " + oldRow + oldCol + " **"; } else { p.oppGrid.markMiss(row, col); opp.playerGrid.markMiss(row, col); return "** USER MISS AT " + oldRow + oldCol + " **"; } } private static void setup(Player p) { p.playerGrid.printShips(); System.out.println(); int counter = 1; int normCounter = 0; while (p.numOfShipsLeft() > 0) { for (Ship s: p.ships) { System.out.println("\nShip #" + counter + ": Length-" + s.getLength()); int row = -1; int col = -1; int dir = -1; while(true) { System.out.print("Type in row (A-J): "); String userInputRow = reader.next(); userInputRow = userInputRow.toUpperCase(); row = convertLetterToInt(userInputRow); System.out.print("Type in column (1-10): "); col = reader.nextInt(); col = convertUserColToProCol(col); System.out.print("Type in direction (0-H, 1-V): "); dir = reader.nextInt(); //System.out.println("DEBUG: " + row + col + dir); if (col >= 0 && col <= 9 && row != -1 && dir != -1) // Check valid<SUF> { if (!hasErrors(row, col, dir, p, normCounter)) // Check if errors will produce (out of bounds) { break; } } System.out.println("Invalid location!"); } //System.out.println("FURTHER DEBUG: row = " + row + "; col = " + col); p.ships[normCounter].setLocation(row, col); p.ships[normCounter].setDirection(dir); p.playerGrid.addShip(p.ships[normCounter]); p.playerGrid.printShips(); System.out.println(); System.out.println("You have " + p.numOfShipsLeft() + " remaining ships to place."); normCounter++; counter++; } } } private static void setupComputer(Player p) { System.out.println(); int counter = 1; int normCounter = 0; Randomizer rand = new Randomizer(); while (p.numOfShipsLeft() > 0) { for (Ship s: p.ships) { int row = rand.nextInt(0, 9); int col = rand.nextInt(0, 9); int dir = rand.nextInt(0, 1); //System.out.println("DEBUG: row-" + row + "; col-" + col + "; dir-" + dir); while (hasErrorsComp(row, col, dir, p, normCounter)) // while the random nums make error, start again { row = rand.nextInt(0, 9); col = rand.nextInt(0, 9); dir = rand.nextInt(0, 1); //System.out.println("AGAIN-DEBUG: row-" + row + "; col-" + col + "; dir-" + dir); } //System.out.println("FURTHER DEBUG: row = " + row + "; col = " + col); p.ships[normCounter].setLocation(row, col); p.ships[normCounter].setDirection(dir); p.playerGrid.addShip(p.ships[normCounter]); normCounter++; counter++; } } } private static boolean hasErrors(int row, int col, int dir, Player p, int count) { //System.out.println("DEBUG: count arg is " + count); int length = p.ships[count].getLength(); // Check if off grid - Horizontal if (dir == 0) { int checker = length + col; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { System.out.println("SHIP DOES NOT FIT"); return true; } } // Check if off grid - Vertical if (dir == 1) // VERTICAL { int checker = length + row; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { System.out.println("SHIP DOES NOT FIT"); return true; } } // Check if overlapping with another ship if (dir == 0) // Hortizontal { // For each location a ship occupies, check if ship is already there for (int i = col; i < col+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(row, i)) { System.out.println("THERE IS ALREADY A SHIP AT THAT LOCATION"); return true; } } } else if (dir == 1) // Vertical { // For each location a ship occupies, check if ship is already there for (int i = row; i < row+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(i, col)) { System.out.println("THERE IS ALREADY A SHIP AT THAT LOCATION"); return true; } } } return false; } private static boolean hasErrorsComp(int row, int col, int dir, Player p, int count) { //System.out.println("DEBUG: count arg is " + count); int length = p.ships[count].getLength(); // Check if off grid - Horizontal if (dir == 0) { int checker = length + col; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { return true; } } // Check if off grid - Vertical if (dir == 1) // VERTICAL { int checker = length + row; //System.out.println("DEBUG: checker is " + checker); if (checker > 10) { return true; } } // Check if overlapping with another ship if (dir == 0) // Hortizontal { // For each location a ship occupies, check if ship is already there for (int i = col; i < col+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(row, i)) { return true; } } } else if (dir == 1) // Vertical { // For each location a ship occupies, check if ship is already there for (int i = row; i < row+length; i++) { //System.out.println("DEBUG: row = " + row + "; col = " + i); if(p.playerGrid.hasShip(i, col)) { return true; } } } return false; } /*HELPER METHODS*/ private static int convertLetterToInt(String val) { int toReturn = -1; switch (val) { case "A": toReturn = 0; break; case "B": toReturn = 1; break; case "C": toReturn = 2; break; case "D": toReturn = 3; break; case "E": toReturn = 4; break; case "F": toReturn = 5; break; case "G": toReturn = 6; break; case "H": toReturn = 7; break; case "I": toReturn = 8; break; case "J": toReturn = 9; break; default: toReturn = -1; break; } return toReturn; } private static String convertIntToLetter(int val) { String toReturn = "Z"; switch (val) { case 0: toReturn = "A"; break; case 1: toReturn = "B"; break; case 2: toReturn = "C"; break; case 3: toReturn = "D"; break; case 4: toReturn = "E"; break; case 5: toReturn = "F"; break; case 6: toReturn = "G"; break; case 7: toReturn = "H"; break; case 8: toReturn = "I"; break; case 9: toReturn = "J"; break; default: toReturn = "Z"; break; } return toReturn; } private static int convertUserColToProCol(int val) { int toReturn = -1; switch (val) { case 1: toReturn = 0; break; case 2: toReturn = 1; break; case 3: toReturn = 2; break; case 4: toReturn = 3; break; case 5: toReturn = 4; break; case 6: toReturn = 5; break; case 7: toReturn = 6; break; case 8: toReturn = 7; break; case 9: toReturn = 8; break; case 10: toReturn = 9; break; default: toReturn = -1; break; } return toReturn; } private static int convertCompColToRegular(int val) { int toReturn = -1; switch (val) { case 0: toReturn = 1; break; case 1: toReturn = 2; break; case 2: toReturn = 3; break; case 3: toReturn = 4; break; case 4: toReturn = 5; break; case 5: toReturn = 6; break; case 6: toReturn = 7; break; case 7: toReturn = 8; break; case 8: toReturn = 9; break; case 9: toReturn = 10; break; default: toReturn = -1; break; } return toReturn; } }
161649_11
/* * DragSortRecycler * * Added drag and drop functionality to your RecyclerView * * * Copyright 2014 Emile Belanger. * * 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.yoavst.quickapps.tools; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.support.annotation.Nullable; import java.lang.reflect.Modifier; public class DragSortRecycler extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener { final String TAG = "DragSortRecycler"; final boolean DEBUG = false; private int dragHandleWidth = 0; private int selectedDragItemPos = -1; private int fingerAnchorY; private int fingerY; private int fingerOffsetInViewY; private float autoScrollWindow = 0.1f; private float autoScrollSpeed = 0.5f; private BitmapDrawable floatingItem; private Rect floatingItemStatingBounds; private Rect floatingItemBounds; private float floatingItemAlpha = 0.5f; private int floatingItemBgColor = 0; private int viewHandleId = -1; OnItemMovedListener moveInterface; private boolean isDragging; @Nullable OnDragStateChangedListener dragStateChangedListener; public interface OnItemMovedListener { public void onItemMoved(int from, int to); } public interface OnDragStateChangedListener { public void onDragStart(); public void onDragStop(); } private void debugLog(String log) { if (DEBUG) Log.d(TAG, log); } public RecyclerView.OnScrollListener getScrollListener() { return scrollListener; } /* * Set the item move interface */ public void setOnItemMovedListener(OnItemMovedListener swif) { moveInterface = swif; } public void setViewHandleId(int id) { viewHandleId = id; } public void setLeftDragArea(int w) { dragHandleWidth = w; } public void setFloatingAlpha(float a) { floatingItemAlpha = a; } public void setFloatingBgColor(int c) { floatingItemBgColor = c; } /* Set the window at top and bottom of list, must be between 0 and 0.5 For example 0.1 uses the top and bottom 10% of the lists for scrolling */ public void setAutoScrollWindow(float w) { autoScrollWindow = w; } /* Set the autoscroll speed, default is 0.5 */ public void setAutoScrollSpeed(float speed) { autoScrollSpeed = speed; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView rv, RecyclerView.State state) { super.getItemOffsets(outRect, view, rv, state); debugLog("getItemOffsets"); debugLog("View top = " + view.getTop()); if (selectedDragItemPos != -1) { int itemPos = rv.getChildPosition(view); debugLog("itemPos =" + itemPos); if(!canDragOver(itemPos)) { return; } //Movement of finger float totalMovement = fingerY-fingerAnchorY; if (itemPos == selectedDragItemPos) { view.setVisibility(View.INVISIBLE); } else { //Make view visible incase invisible view.setVisibility(View.VISIBLE); //Find middle of the floatingItem float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; //Moving down the list //These will auto-animate if the device continually sends touch motion events // if (totalMovment>0) { if ((itemPos > selectedDragItemPos) && (view.getTop() < floatMiddleY)) { float amountUp = (floatMiddleY - view.getTop()) / (float)view.getHeight(); // amountUp *= 0.5f; if (amountUp > 1) amountUp = 1; outRect.top = -(int)(floatingItemBounds.height()*amountUp); outRect.bottom = (int)(floatingItemBounds.height()*amountUp); } }//Moving up the list // else if (totalMovment < 0) { if((itemPos < selectedDragItemPos) && (view.getBottom() > floatMiddleY)) { float amountDown = ((float)view.getBottom() - floatMiddleY) / (float)view.getHeight(); // amountDown *= 0.5f; if (amountDown > 1) amountDown = 1; outRect.top = (int)(floatingItemBounds.height()*amountDown); outRect.bottom = -(int)(floatingItemBounds.height()*amountDown); } } } } else { outRect.top = 0; outRect.bottom = 0; //Make view visible incase invisible view.setVisibility(View.VISIBLE); } } /** * Find the new position by scanning through the items on * screen and finding the positional relationship. * This *seems* to work, another method would be to use * getItemOffsets, but I think that could miss items?.. */ private int getNewPostion(RecyclerView rv) { int itemsOnScreen = rv.getLayoutManager().getChildCount(); float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; int above=0; int below = Integer.MAX_VALUE; for (int n=0;n < itemsOnScreen;n++) //Scan though items on screen, however they may not { // be in order! View view = rv.getLayoutManager().getChildAt(n); if (view.getVisibility() != View.VISIBLE) continue; int itemPos = rv.getChildPosition(view); if (itemPos == selectedDragItemPos) //Don't check against itself! continue; float viewMiddleY = view.getTop() + view.getHeight()/2; if (floatMiddleY > viewMiddleY) //Is above this item { if (itemPos > above) above = itemPos; } else if (floatMiddleY <= viewMiddleY) //Is below this item { if (itemPos < below) below = itemPos; } } debugLog("above = " + above + " below = " + below); if (below != Integer.MAX_VALUE) { if (below < selectedDragItemPos) //Need to count itself below++; return below - 1; } else { if (above < selectedDragItemPos) above++; return above; } } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onInterceptTouchEvent"); //if (e.getAction() == MotionEvent.ACTION_DOWN) { View itemView = rv.findChildViewUnder(e.getX(), e.getY()); if (itemView==null) return false; boolean dragging = false; if ((dragHandleWidth > 0 ) && (e.getX() < dragHandleWidth)) { dragging = true; } else if (viewHandleId != -1) { //Find the handle in the list item View handleView = itemView.findViewById(viewHandleId); if (handleView == null) { Log.e(TAG, "The view ID " + viewHandleId + " was not found in the RecycleView item"); return false; } //View should be visible to drag if(handleView.getVisibility()!=View.VISIBLE) { return false; } //We need to find the relative position of the handle to the parent view //Then we can work out if the touch is within the handle int[] parentItemPos = new int[2]; itemView.getLocationInWindow(parentItemPos); int[] handlePos = new int[2]; handleView.getLocationInWindow(handlePos); int xRel = handlePos[0] - parentItemPos[0]; int yRel = handlePos[1] - parentItemPos[1]; Rect touchBounds = new Rect(itemView.getLeft() + xRel, itemView.getTop() + yRel, itemView.getLeft() + xRel + handleView.getWidth(), itemView.getTop() + yRel + handleView.getHeight() ); if (touchBounds.contains((int)e.getX(), (int)e.getY())) dragging = true; debugLog("parentItemPos = " + parentItemPos[0] + " " + parentItemPos[1]); debugLog("handlePos = " + handlePos[0] + " " + handlePos[1]); } if (dragging) { debugLog("Started Drag"); setIsDragging(true); floatingItem = createFloatingBitmap(itemView); fingerAnchorY = (int)e.getY(); fingerOffsetInViewY = fingerAnchorY - itemView.getTop(); fingerY = fingerAnchorY; selectedDragItemPos = rv.getChildPosition(itemView); debugLog("selectedDragItemPos = " + selectedDragItemPos); return true; } } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onTouchEvent"); if ((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)) { if ((e.getAction() == MotionEvent.ACTION_UP) && selectedDragItemPos != -1) { int newPos = getNewPostion(rv); if (moveInterface != null) moveInterface.onItemMoved(selectedDragItemPos, newPos); } setIsDragging(false); selectedDragItemPos = -1; floatingItem = null; rv.invalidateItemDecorations(); return; } fingerY = (int)e.getY(); if (floatingItem!=null) { floatingItemBounds.top = fingerY - fingerOffsetInViewY; if (floatingItemBounds.top < -floatingItemStatingBounds.height()/2) //Allow half the view out the top floatingItemBounds.top = -floatingItemStatingBounds.height()/2; floatingItemBounds.bottom = floatingItemBounds.top + floatingItemStatingBounds.height(); floatingItem.setBounds(floatingItemBounds); } //Do auto scrolling at end of list float scrollAmount=0; if (fingerY > (rv.getHeight() * (1-autoScrollWindow))) { scrollAmount = (fingerY - (rv.getHeight() * (1-autoScrollWindow))); } else if (fingerY < (rv.getHeight() * autoScrollWindow)) { scrollAmount = (fingerY - (rv.getHeight() * autoScrollWindow)); } debugLog("Scroll: " + scrollAmount); scrollAmount *= autoScrollSpeed; rv.scrollBy(0, (int)scrollAmount); rv.invalidateItemDecorations();// Redraw } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { //FIXME } private void setIsDragging(final boolean dragging) { if(dragging != isDragging) { isDragging = dragging; if(dragStateChangedListener != null) { if (isDragging) { dragStateChangedListener.onDragStart(); } else { dragStateChangedListener.onDragStop(); } } } } public void setOnDragStateChangedListener(final OnDragStateChangedListener dragStateChangedListener) { this.dragStateChangedListener = dragStateChangedListener; } Paint bgColor = new Paint(); @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (floatingItem != null) { floatingItem.setAlpha((int)(255 * floatingItemAlpha)); bgColor.setColor(floatingItemBgColor); c.drawRect(floatingItemBounds,bgColor); floatingItem.draw(c); } } RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); debugLog("Scrolled: " + dx + " " + dy); fingerAnchorY -= dy; } }; /** * * * @param position * @return True if we can drag the item over this position, False if not. */ protected boolean canDragOver(int position) { return true; } private BitmapDrawable createFloatingBitmap(View v) { floatingItemStatingBounds = new Rect(v.getLeft(), v.getTop(),v.getRight(), v.getBottom()); floatingItemBounds = new Rect(floatingItemStatingBounds); Bitmap bitmap = Bitmap.createBitmap(floatingItemStatingBounds.width(), floatingItemStatingBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); BitmapDrawable retDrawable = new BitmapDrawable(v.getResources(), bitmap); retDrawable.setBounds(floatingItemBounds); return retDrawable; } }
yoavst/quickapps
app/src/main/java/com/yoavst/quickapps/tools/DragSortRecycler.java
4,075
// else if (totalMovment < 0)
line_comment
nl
/* * DragSortRecycler * * Added drag and drop functionality to your RecyclerView * * * Copyright 2014 Emile Belanger. * * 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.yoavst.quickapps.tools; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.support.annotation.Nullable; import java.lang.reflect.Modifier; public class DragSortRecycler extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener { final String TAG = "DragSortRecycler"; final boolean DEBUG = false; private int dragHandleWidth = 0; private int selectedDragItemPos = -1; private int fingerAnchorY; private int fingerY; private int fingerOffsetInViewY; private float autoScrollWindow = 0.1f; private float autoScrollSpeed = 0.5f; private BitmapDrawable floatingItem; private Rect floatingItemStatingBounds; private Rect floatingItemBounds; private float floatingItemAlpha = 0.5f; private int floatingItemBgColor = 0; private int viewHandleId = -1; OnItemMovedListener moveInterface; private boolean isDragging; @Nullable OnDragStateChangedListener dragStateChangedListener; public interface OnItemMovedListener { public void onItemMoved(int from, int to); } public interface OnDragStateChangedListener { public void onDragStart(); public void onDragStop(); } private void debugLog(String log) { if (DEBUG) Log.d(TAG, log); } public RecyclerView.OnScrollListener getScrollListener() { return scrollListener; } /* * Set the item move interface */ public void setOnItemMovedListener(OnItemMovedListener swif) { moveInterface = swif; } public void setViewHandleId(int id) { viewHandleId = id; } public void setLeftDragArea(int w) { dragHandleWidth = w; } public void setFloatingAlpha(float a) { floatingItemAlpha = a; } public void setFloatingBgColor(int c) { floatingItemBgColor = c; } /* Set the window at top and bottom of list, must be between 0 and 0.5 For example 0.1 uses the top and bottom 10% of the lists for scrolling */ public void setAutoScrollWindow(float w) { autoScrollWindow = w; } /* Set the autoscroll speed, default is 0.5 */ public void setAutoScrollSpeed(float speed) { autoScrollSpeed = speed; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView rv, RecyclerView.State state) { super.getItemOffsets(outRect, view, rv, state); debugLog("getItemOffsets"); debugLog("View top = " + view.getTop()); if (selectedDragItemPos != -1) { int itemPos = rv.getChildPosition(view); debugLog("itemPos =" + itemPos); if(!canDragOver(itemPos)) { return; } //Movement of finger float totalMovement = fingerY-fingerAnchorY; if (itemPos == selectedDragItemPos) { view.setVisibility(View.INVISIBLE); } else { //Make view visible incase invisible view.setVisibility(View.VISIBLE); //Find middle of the floatingItem float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; //Moving down the list //These will auto-animate if the device continually sends touch motion events // if (totalMovment>0) { if ((itemPos > selectedDragItemPos) && (view.getTop() < floatMiddleY)) { float amountUp = (floatMiddleY - view.getTop()) / (float)view.getHeight(); // amountUp *= 0.5f; if (amountUp > 1) amountUp = 1; outRect.top = -(int)(floatingItemBounds.height()*amountUp); outRect.bottom = (int)(floatingItemBounds.height()*amountUp); } }//Moving up the list // else if<SUF> { if((itemPos < selectedDragItemPos) && (view.getBottom() > floatMiddleY)) { float amountDown = ((float)view.getBottom() - floatMiddleY) / (float)view.getHeight(); // amountDown *= 0.5f; if (amountDown > 1) amountDown = 1; outRect.top = (int)(floatingItemBounds.height()*amountDown); outRect.bottom = -(int)(floatingItemBounds.height()*amountDown); } } } } else { outRect.top = 0; outRect.bottom = 0; //Make view visible incase invisible view.setVisibility(View.VISIBLE); } } /** * Find the new position by scanning through the items on * screen and finding the positional relationship. * This *seems* to work, another method would be to use * getItemOffsets, but I think that could miss items?.. */ private int getNewPostion(RecyclerView rv) { int itemsOnScreen = rv.getLayoutManager().getChildCount(); float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; int above=0; int below = Integer.MAX_VALUE; for (int n=0;n < itemsOnScreen;n++) //Scan though items on screen, however they may not { // be in order! View view = rv.getLayoutManager().getChildAt(n); if (view.getVisibility() != View.VISIBLE) continue; int itemPos = rv.getChildPosition(view); if (itemPos == selectedDragItemPos) //Don't check against itself! continue; float viewMiddleY = view.getTop() + view.getHeight()/2; if (floatMiddleY > viewMiddleY) //Is above this item { if (itemPos > above) above = itemPos; } else if (floatMiddleY <= viewMiddleY) //Is below this item { if (itemPos < below) below = itemPos; } } debugLog("above = " + above + " below = " + below); if (below != Integer.MAX_VALUE) { if (below < selectedDragItemPos) //Need to count itself below++; return below - 1; } else { if (above < selectedDragItemPos) above++; return above; } } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onInterceptTouchEvent"); //if (e.getAction() == MotionEvent.ACTION_DOWN) { View itemView = rv.findChildViewUnder(e.getX(), e.getY()); if (itemView==null) return false; boolean dragging = false; if ((dragHandleWidth > 0 ) && (e.getX() < dragHandleWidth)) { dragging = true; } else if (viewHandleId != -1) { //Find the handle in the list item View handleView = itemView.findViewById(viewHandleId); if (handleView == null) { Log.e(TAG, "The view ID " + viewHandleId + " was not found in the RecycleView item"); return false; } //View should be visible to drag if(handleView.getVisibility()!=View.VISIBLE) { return false; } //We need to find the relative position of the handle to the parent view //Then we can work out if the touch is within the handle int[] parentItemPos = new int[2]; itemView.getLocationInWindow(parentItemPos); int[] handlePos = new int[2]; handleView.getLocationInWindow(handlePos); int xRel = handlePos[0] - parentItemPos[0]; int yRel = handlePos[1] - parentItemPos[1]; Rect touchBounds = new Rect(itemView.getLeft() + xRel, itemView.getTop() + yRel, itemView.getLeft() + xRel + handleView.getWidth(), itemView.getTop() + yRel + handleView.getHeight() ); if (touchBounds.contains((int)e.getX(), (int)e.getY())) dragging = true; debugLog("parentItemPos = " + parentItemPos[0] + " " + parentItemPos[1]); debugLog("handlePos = " + handlePos[0] + " " + handlePos[1]); } if (dragging) { debugLog("Started Drag"); setIsDragging(true); floatingItem = createFloatingBitmap(itemView); fingerAnchorY = (int)e.getY(); fingerOffsetInViewY = fingerAnchorY - itemView.getTop(); fingerY = fingerAnchorY; selectedDragItemPos = rv.getChildPosition(itemView); debugLog("selectedDragItemPos = " + selectedDragItemPos); return true; } } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onTouchEvent"); if ((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)) { if ((e.getAction() == MotionEvent.ACTION_UP) && selectedDragItemPos != -1) { int newPos = getNewPostion(rv); if (moveInterface != null) moveInterface.onItemMoved(selectedDragItemPos, newPos); } setIsDragging(false); selectedDragItemPos = -1; floatingItem = null; rv.invalidateItemDecorations(); return; } fingerY = (int)e.getY(); if (floatingItem!=null) { floatingItemBounds.top = fingerY - fingerOffsetInViewY; if (floatingItemBounds.top < -floatingItemStatingBounds.height()/2) //Allow half the view out the top floatingItemBounds.top = -floatingItemStatingBounds.height()/2; floatingItemBounds.bottom = floatingItemBounds.top + floatingItemStatingBounds.height(); floatingItem.setBounds(floatingItemBounds); } //Do auto scrolling at end of list float scrollAmount=0; if (fingerY > (rv.getHeight() * (1-autoScrollWindow))) { scrollAmount = (fingerY - (rv.getHeight() * (1-autoScrollWindow))); } else if (fingerY < (rv.getHeight() * autoScrollWindow)) { scrollAmount = (fingerY - (rv.getHeight() * autoScrollWindow)); } debugLog("Scroll: " + scrollAmount); scrollAmount *= autoScrollSpeed; rv.scrollBy(0, (int)scrollAmount); rv.invalidateItemDecorations();// Redraw } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { //FIXME } private void setIsDragging(final boolean dragging) { if(dragging != isDragging) { isDragging = dragging; if(dragStateChangedListener != null) { if (isDragging) { dragStateChangedListener.onDragStart(); } else { dragStateChangedListener.onDragStop(); } } } } public void setOnDragStateChangedListener(final OnDragStateChangedListener dragStateChangedListener) { this.dragStateChangedListener = dragStateChangedListener; } Paint bgColor = new Paint(); @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (floatingItem != null) { floatingItem.setAlpha((int)(255 * floatingItemAlpha)); bgColor.setColor(floatingItemBgColor); c.drawRect(floatingItemBounds,bgColor); floatingItem.draw(c); } } RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); debugLog("Scrolled: " + dx + " " + dy); fingerAnchorY -= dy; } }; /** * * * @param position * @return True if we can drag the item over this position, False if not. */ protected boolean canDragOver(int position) { return true; } private BitmapDrawable createFloatingBitmap(View v) { floatingItemStatingBounds = new Rect(v.getLeft(), v.getTop(),v.getRight(), v.getBottom()); floatingItemBounds = new Rect(floatingItemStatingBounds); Bitmap bitmap = Bitmap.createBitmap(floatingItemStatingBounds.width(), floatingItemStatingBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); BitmapDrawable retDrawable = new BitmapDrawable(v.getResources(), bitmap); retDrawable.setBounds(floatingItemBounds); return retDrawable; } }
175725_21
package org.dspace.workflow; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.ResourcePolicy; import org.dspace.content.*; import org.dspace.content.Collection; import org.dspace.core.*; import org.dspace.eperson.EPerson; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.workflow.actions.Action; import org.dspace.workflow.actions.ActionResult; import org.dspace.workflow.actions.WorkflowActionConfig; import org.xml.sax.SAXException; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.sql.SQLException; import java.util.*; /** * Created by IntelliJ IDEA. * User: bram * Date: 2-aug-2010 * Time: 17:32:44 * This class has been adjusted to support the data package, data file dryad data model */ public class WorkflowManager { private static Logger log = Logger.getLogger(WorkflowManager.class); public static WorkflowItem start(Context context, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException, WorkflowConfigurationException, MessagingException, TransformerException, SAXException, ParserConfigurationException, WorkflowException { Item myitem = wsi.getItem(); Collection collection = wsi.getCollection(); Workflow wf = WorkflowFactory.getWorkflow(collection); TableRow row = DatabaseManager.create(context, "workflowitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", wsi.getCollection().getID()); WorkflowItem wfi = new WorkflowItem(context, row); wfi.setMultipleFiles(wsi.hasMultipleFiles()); wfi.setMultipleTitles(wsi.hasMultipleTitles()); wfi.setPublishedBefore(wsi.isPublishedBefore()); wfi.update(); boolean isDataPackage = DryadWorkflowUtils.isDataPackage(wfi); //Only if we are a a datapackage OR have a data package that is already archived are you allowed to activate the first step if(isDataPackage || DryadWorkflowUtils.isDataPackageArchived(context, wfi)){ Step firstStep = wf.getFirstStep(); if(firstStep.isValidStep(context, wfi)){ activateFirstStep(context, wf, firstStep, wfi); } else { //Get our next step, if none is found, archive our item firstStep = wf.getNextStep(context, wfi, firstStep, ActionResult.OUTCOME_COMPLETE); if(firstStep == null){ if(DryadWorkflowUtils.isDataPackage(wfi)){ //We have a data package //First archive the data package archive(context, wfi, true); //We need to find all the items linked to this publication Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, wfi.getItem()); for (Item dataFile : dataFiles) { WorkflowItem wfiDataFile = WorkflowItem.findByItemId(context, dataFile.getID()); archive(context, wfiDataFile, false); } } }else{ activateFirstStep(context, wf, firstStep, wfi); } } } // remove the WorkspaceItem wsi.deleteWrapper(); return wfi; } private static void activateFirstStep(Context context, Workflow wf, Step firstStep, WorkflowItem wfi) throws AuthorizeException, IOException, SQLException, TransformerException, WorkflowException, SAXException, WorkflowConfigurationException, ParserConfigurationException { WorkflowActionConfig firstActionConfig = firstStep.getUserSelectionMethod(); firstActionConfig.getProcessingAction().activate(context, wfi); log.info(LogManager.getHeader(context, "start_workflow", firstActionConfig.getProcessingAction() + " workflow_item_id=" + wfi.getID() + "item_id=" + wfi.getItem().getID() + "collection_id=" + wfi.getCollection().getID())); // record the start of the workflow w/provenance message recordStart(wfi.getItem(), firstActionConfig.getProcessingAction()); //If we don't have a UI activate it if(!firstActionConfig.hasUserInterface()){ ActionResult outcome = firstActionConfig.getProcessingAction().execute(context, wfi, firstStep, null); processOutcome(context, null, wf, firstStep, firstActionConfig, outcome, wfi); } } /* * Executes an action and returns the next. */ public static WorkflowActionConfig doState(Context c, EPerson user, HttpServletRequest request, int workflowItemId, Workflow workflow, WorkflowActionConfig currentActionConfig) throws SQLException, AuthorizeException, IOException, MessagingException, WorkflowConfigurationException, WorkflowException { try { WorkflowItem wi = WorkflowItem.find(c, workflowItemId); Step currentStep = currentActionConfig.getStep(); ActionResult outcome = currentActionConfig.getProcessingAction().execute(c, wi, currentStep, request); return processOutcome(c, user, workflow, currentStep, currentActionConfig, outcome, wi); } catch (WorkflowConfigurationException e) { WorkflowUtils.sendAlert(request, e); throw e; } catch (ParserConfigurationException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); e.printStackTrace(); throw new WorkflowException("An unknown exception occurred while performing action"); } catch (SAXException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); e.printStackTrace(); throw new WorkflowException("An unknown exception occurred while performing action"); } catch (TransformerException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); e.printStackTrace(); throw new WorkflowException("An unknown exception occurred while performing action"); } } public static WorkflowActionConfig processOutcome(Context c, EPerson user, Workflow workflow, Step currentStep, WorkflowActionConfig currentActionConfig, ActionResult currentOutcome, WorkflowItem wfi) throws TransformerException, IOException, SAXException, WorkflowConfigurationException, ParserConfigurationException, AuthorizeException, SQLException, WorkflowException { if(currentOutcome.getType() == ActionResult.TYPE.TYPE_PAGE || currentOutcome.getType() == ActionResult.TYPE.TYPE_ERROR){ //Our outcome is a page or an error, so return our current action return currentActionConfig; }else if(currentOutcome.getType() == ActionResult.TYPE.TYPE_CANCEL || currentOutcome.getType() == ActionResult.TYPE.TYPE_SUBMISSION_PAGE){ //We either pressed the cancel button or got an order to return to the submission page, so don't return an action //By not returning an action we ensure ourselfs that we go back to the submission page return null; }else if (currentOutcome.getType() == ActionResult.TYPE.TYPE_OUTCOME) { //We have completed our action search & retrieve the next action WorkflowActionConfig nextActionConfig = null; if(currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE){ nextActionConfig = currentStep.getNextAction(currentActionConfig); } if (nextActionConfig != null) { nextActionConfig.getProcessingAction().activate(c, wfi); if (nextActionConfig.hasUserInterface()) { //TODO: if user is null, then throw a decent exception ! createOwnedTask(c, wfi, currentStep, nextActionConfig, user); return nextActionConfig; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, currentStep, null); return processOutcome(c, user, workflow, currentStep, nextActionConfig, newOutcome, wfi); } }else { //First add it to our list of finished users, since no more actions remain WorkflowRequirementsManager.addFinishedUser(c, wfi, user); c.turnOffAuthorisationSystem(); //Check if our requirements have been met if((currentStep.isFinished(wfi) && currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE) || currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ //Clear all the metadata that might be saved by this step WorkflowRequirementsManager.clearStepMetadata(wfi); //Remove all the tasks WorkflowManager.deleteAllTasks(c, wfi); Step nextStep = workflow.getNextStep(c, wfi, currentStep, currentOutcome.getResult()); if(nextStep!=null){ //TODO: is generate tasks nog nodig of kan dit mee in activate? //TODO: vorige step zou meegegeven moeten worden om evt rollen te kunnen overnemen nextActionConfig = nextStep.getUserSelectionMethod(); nextActionConfig.getProcessingAction().activate(c, wfi); // nextActionConfig.getProcessingAction().generateTasks(); //Deze kunnen afhangen van de step (rol, min, max, ...). Evt verantwoordelijkheid bij userassignmentaction leggen if (nextActionConfig.hasUserInterface()) { //Since a new step has been started, stop executing actions once one with a user interface is present. c.restoreAuthSystemState(); return null; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, nextStep, null); c.restoreAuthSystemState(); return processOutcome(c, user, workflow, nextStep, nextActionConfig, newOutcome, wfi); } }else{ if(currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ c.restoreAuthSystemState(); throw new WorkflowException("No alternate step was found for outcome: " + currentOutcome.getResult()); } //This is dryad only, if(DryadWorkflowUtils.isDataPackage(wfi)){ //We have a data package //First archive the data package Item archivedDataSet = archive(c, wfi, true); //We need to find all the items linked to this publication Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wfi.getItem()); for (Item dataFile : dataFiles) { WorkflowItem wfiDataFile = WorkflowItem.findByItemId(c, dataFile.getID()); archive(c, wfiDataFile, false); } //Next delete any workspace items still open for this data set WorkspaceItem[] workspaceItems = WorkspaceItem.findByEPerson(c, c.getCurrentUser()); for (WorkspaceItem workspaceItem : workspaceItems) { Item owningDataset = DryadWorkflowUtils.getDataPackage(c, workspaceItem.getItem()); if (owningDataset != null && owningDataset.getID() == archivedDataSet.getID()) workspaceItem.deleteAll(); } }else{ //We have a single data file, archive it archive(c, wfi, true); } c.restoreAuthSystemState(); return null; } }else{ //We are done with our actions so go to the submissions page c.restoreAuthSystemState(); return null; } } } //TODO: log & go back to submission, We should not come here //TODO: remove assertion - can be used for testing (will throw assertionexception) assert false; return null; } //TODO: nakijken /** * Commit the contained item to the main archive. The item is associated * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. * * @return the fully archived item. */ public static Item archive(Context c, WorkflowItem wfi, boolean notify) throws SQLException, IOException, AuthorizeException { // FIXME: Check auth Item item = wfi.getItem(); Collection collection = wfi.getCollection(); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wfi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } log.info(LogManager.getHeader(c, "archive_item", "workflow_item_id=" + wfi.getID() + "item_id=" + item.getID() + "collection_id=" + collection.getID())); InstallItem.installItem(c, wfi); if(notify){ //Notify WorkflowEmailManager.notifyOfArchive(c, item); } //Clear any remaining workflow metadata item.clearMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA, Item.ANY, Item.ANY, Item.ANY); item.update(); // Log the event log.info(LogManager.getHeader(c, "install_item", "workflow_item_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME")); return item; } /*********************************** * WORKFLOW TASK MANAGEMENT **********************************/ /** * Deletes all tasks from this workflowflowitem * @param c the dspace context * @param wi the workflow item for whom we are to delete the tasks * @throws SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static void deleteAllTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { deleteAllPooledTasks(c, wi); List<ClaimedTask> allClaimedTasks = ClaimedTask.findByWorkflowId(c,wi.getID()); for(ClaimedTask task: allClaimedTasks){ deleteClaimedTask(c, wi, task); } } public static void deleteAllPooledTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { List<PoolTask> allPooledTasks = PoolTask.find(c, wi); for (PoolTask poolTask : allPooledTasks) { deletePooledTask(c, wi, poolTask); } } /* * Deletes an eperson from the taskpool of a step */ public static void deletePooledTask(Context c, WorkflowItem wi, PoolTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getEpersonID())); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wi.getItem()); for (Item dataFile : dataFiles) { removeUserItemPolicies(c, dataFile, EPerson.find(c, task.getEpersonID())); } } } public static void deleteClaimedTask(Context c, WorkflowItem wi, ClaimedTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getOwnerID())); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wi.getItem()); for (Item dataFile : dataFiles) { removeUserItemPolicies(c, dataFile, EPerson.find(c, task.getOwnerID())); } } } /* * Creates a task pool for a given step */ public static void createPoolTasks(Context context, WorkflowItem wi, EPerson[] epa, Step step, WorkflowActionConfig action) throws SQLException, AuthorizeException { // create a tasklist entry for each eperson for (EPerson anEpa : epa) { PoolTask task = PoolTask.create(context); task.setStepID(step.getId()); task.setWorkflowID(step.getWorkflow().getID()); task.setEpersonID(anEpa.getID()); task.setActionID(action.getId()); task.setWorkflowItemID(wi.getID()); task.update(); //Make sure this user has a task grantUserAllItemPolicies(context, wi.getItem(), anEpa); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, wi.getItem()); for (Item dataFile : dataFiles) { grantUserAllItemPolicies(context, dataFile, anEpa); } } } /* * Claims an action for a given eperson */ public static void createOwnedTask(Context c, WorkflowItem wi, Step step, WorkflowActionConfig action, EPerson e) throws SQLException, AuthorizeException { ClaimedTask task = ClaimedTask.create(c); task.setWorkflowItemID(wi.getID()); task.setStepID(step.getId()); task.setActionID(action.getId()); if(e != null) task.setOwnerID(e.getID()); task.setWorkflowID(step.getWorkflow().getID()); task.update(); if(e != null){ //Make sure this user has a task grantUserAllItemPolicies(c, wi.getItem(), e); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wi.getItem()); for (Item dataFile : dataFiles) { grantUserAllItemPolicies(c, dataFile, e); } } } private static void grantUserAllItemPolicies(Context context, Item item, EPerson epa) throws AuthorizeException, SQLException { //A list of policies the user has for this item List<Integer> userHasPolicies = new ArrayList<Integer>(); List<ResourcePolicy> itempols = AuthorizeManager.getPolicies(context, item); for (ResourcePolicy resourcePolicy : itempols) { if(resourcePolicy.getEPersonID() == epa.getID()){ //The user has already got this policy so it it to the list userHasPolicies.add(resourcePolicy.getAction()); } } //Make sure we don't add duplicate policies if(!userHasPolicies.contains(Constants.READ)) addPolicyToItem(context, item, Constants.READ, epa); if(!userHasPolicies.contains(Constants.WRITE)) addPolicyToItem(context, item, Constants.WRITE, epa); if(!userHasPolicies.contains(Constants.DELETE)) addPolicyToItem(context, item, Constants.DELETE, epa); if(!userHasPolicies.contains(Constants.ADD)) addPolicyToItem(context, item, Constants.ADD, epa); } private static void addPolicyToItem(Context context, Item item, int type, EPerson epa) throws AuthorizeException, SQLException { AuthorizeManager.addPolicy(context ,item, type, epa); Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { AuthorizeManager.addPolicy(context ,bundle, type, epa); Bitstream[] bits = bundle.getBitstreams(); for (Bitstream bit : bits) { AuthorizeManager.addPolicy(context, bit, type, epa); } } } private static void removeUserItemPolicies(Context context, Item item, EPerson e) throws SQLException, AuthorizeException { //Also remove any lingering authorizations from this user removePoliciesFromDso(context, item, e); //Remove the bundle rights Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { removePoliciesFromDso(context, bundle, e); Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { removePoliciesFromDso(context, bitstream, e); } } } private static void removePoliciesFromDso(Context context, DSpaceObject item, EPerson e) throws SQLException, AuthorizeException { List<ResourcePolicy> policies = AuthorizeManager.getPolicies(context, item); AuthorizeManager.removeAllPolicies(context, item); for (ResourcePolicy resourcePolicy : policies) { if( resourcePolicy.getEPerson() ==null || resourcePolicy.getEPersonID() != e.getID()){ if(resourcePolicy.getEPerson() != null) AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getEPerson()); else AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getGroup()); } } } /** * rejects an item - rejection means undoing a submit - WorkspaceItem is * created, and the WorkflowItem is removed, user is emailed * rejection_message. * * @param c * Context * @param wi * WorkflowItem to operate on * @param e * EPerson doing the operation * @param action the action which triggered this reject * @param rejection_message * message to email to user * @return the workspace item that is created * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static WorkspaceItem rejectWorkflowItem(Context c, WorkflowItem wi, EPerson e, Action action, String rejection_message, boolean sendMail) throws SQLException, AuthorizeException, IOException { // authorize a DSpaceActions.REJECT // stop workflow deleteAllTasks(c, wi); //Also clear all info for this step WorkflowRequirementsManager.clearStepMetadata(wi); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } // rejection provenance Item myitem = wi.getItem(); // Get current date String now = DCDate.getCurrent().toString(); org.dspace.content.Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, myitem); if(dataFiles!=null){ for(Item dataFile:dataFiles) { if(dataFile.getMetadata("internal", "workflow", "submitted", Item.ANY).length == 0){ //A newly (re-)submitted publication dataFile.addMetadata("internal", "workflow", "submitted", null, Boolean.TRUE.toString()); myitem.update(); } } } // Here's what happened if(action != null){ // Get user's name + email address String usersName = getEPersonName(e); String provDescription = action.getProvenanceStartId() + " Rejected by " + usersName + ", reason: " + rejection_message + " on " + now + " (GMT) "; // Add to item as a DC field myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provDescription); } myitem.update(); // convert into personal workspace WorkspaceItem wsi = returnToWorkspace(c, wi); if(sendMail){ // notify that it's been rejected WorkflowEmailManager.notifyOfReject(c, wi, e, rejection_message); } log.info(LogManager.getHeader(c, "reject_workflow", "workflow_item_id=" + wi.getID() + "item_id=" + wi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "eperson_id=" + (e == null ? "" : e.getID()))); return wsi; } /** * Return the workflow item to the workspace of the submitter. The workflow * item is removed, and a workspace item created. * * @param c * Context * @param wfi * WorkflowItem to be 'dismantled' * @return the workspace item * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { Item myitem = wfi.getItem(); Collection myCollection = wfi.getCollection(); // FIXME: How should this interact with the workflow system? // FIXME: Remove license // FIXME: Provenance statement? // Create the new workspace item row TableRow row = DatabaseManager.create(c, "workspaceitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", myCollection.getID()); DatabaseManager.update(c, row); int wsi_id = row.getIntColumn("workspace_item_id"); WorkspaceItem wi = WorkspaceItem.find(c, wsi_id); wi.setMultipleFiles(wfi.hasMultipleFiles()); wi.setMultipleTitles(wfi.hasMultipleTitles()); wi.setPublishedBefore(wfi.isPublishedBefore()); wi.update(); //myitem.update(); log.info(LogManager.getHeader(c, "return_to_workspace", "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + wi.getID())); // Now remove the workflow object manually from the database DatabaseManager.updateQuery(c, "DELETE FROM WorkflowItem WHERE workflow_id=" + wfi.getID()); return wi; } public static String getEPersonName(EPerson e) throws SQLException { String submitter = e.getFullName(); submitter = submitter + "(" + e.getEmail() + ")"; return submitter; } // Create workflow start provenance message private static void recordStart(Item myitem, Action action) throws SQLException, IOException, AuthorizeException { // get date DCDate now = DCDate.getCurrent(); // Create provenance description String provmessage = ""; if (myitem.getSubmitter() != null) { provmessage = "Submitted by " + myitem.getSubmitter().getFullName() + " (" + myitem.getSubmitter().getEmail() + ") on " + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } else // null submitter { provmessage = "Submitted by unknown (probably automated) on" + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } // add sizes and checksums of bitstreams provmessage += InstallItem.getBitstreamProvenanceMessage(myitem); // Add message to the DC myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provmessage); myitem.update(); } public static String getMyDSpaceLink() { return ConfigurationManager.getProperty("dspace.url") + "/mydspace"; } // Classes that are not customized by Dryad call this, so it remains for // compatibility public static void notifyOfCuration(Context c, WorkflowItem wi, EPerson[] epa, String taskName, String action, String message) throws SQLException, IOException { WorkflowEmailManager.notifyOfCuration(c, wi, epa, taskName, action, message); } /** * get the title of the item in this workflow * * @param wi the workflow item object */ public static String getItemTitle(WorkflowItem wi) throws SQLException { Item myitem = wi.getItem(); DCValue[] titles = myitem.getDC("title", null, Item.ANY); // only return the first element, or "Untitled" if (titles.length > 0) { return titles[0].value; } else { return I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled "); } } /** * get the name of the eperson who started this workflow * * @param wi the workflow item */ public static String getSubmitterName(WorkflowItem wi) throws SQLException { EPerson e = wi.getSubmitter(); return getEPersonName(e); } }
yonghaoy/dryad-repo
dspace/modules/api/src/main/java/org/dspace/workflow/WorkflowManager.java
8,019
//Deze kunnen afhangen van de step (rol, min, max, ...). Evt verantwoordelijkheid bij userassignmentaction leggen
line_comment
nl
package org.dspace.workflow; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.ResourcePolicy; import org.dspace.content.*; import org.dspace.content.Collection; import org.dspace.core.*; import org.dspace.eperson.EPerson; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.workflow.actions.Action; import org.dspace.workflow.actions.ActionResult; import org.dspace.workflow.actions.WorkflowActionConfig; import org.xml.sax.SAXException; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.sql.SQLException; import java.util.*; /** * Created by IntelliJ IDEA. * User: bram * Date: 2-aug-2010 * Time: 17:32:44 * This class has been adjusted to support the data package, data file dryad data model */ public class WorkflowManager { private static Logger log = Logger.getLogger(WorkflowManager.class); public static WorkflowItem start(Context context, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException, WorkflowConfigurationException, MessagingException, TransformerException, SAXException, ParserConfigurationException, WorkflowException { Item myitem = wsi.getItem(); Collection collection = wsi.getCollection(); Workflow wf = WorkflowFactory.getWorkflow(collection); TableRow row = DatabaseManager.create(context, "workflowitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", wsi.getCollection().getID()); WorkflowItem wfi = new WorkflowItem(context, row); wfi.setMultipleFiles(wsi.hasMultipleFiles()); wfi.setMultipleTitles(wsi.hasMultipleTitles()); wfi.setPublishedBefore(wsi.isPublishedBefore()); wfi.update(); boolean isDataPackage = DryadWorkflowUtils.isDataPackage(wfi); //Only if we are a a datapackage OR have a data package that is already archived are you allowed to activate the first step if(isDataPackage || DryadWorkflowUtils.isDataPackageArchived(context, wfi)){ Step firstStep = wf.getFirstStep(); if(firstStep.isValidStep(context, wfi)){ activateFirstStep(context, wf, firstStep, wfi); } else { //Get our next step, if none is found, archive our item firstStep = wf.getNextStep(context, wfi, firstStep, ActionResult.OUTCOME_COMPLETE); if(firstStep == null){ if(DryadWorkflowUtils.isDataPackage(wfi)){ //We have a data package //First archive the data package archive(context, wfi, true); //We need to find all the items linked to this publication Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, wfi.getItem()); for (Item dataFile : dataFiles) { WorkflowItem wfiDataFile = WorkflowItem.findByItemId(context, dataFile.getID()); archive(context, wfiDataFile, false); } } }else{ activateFirstStep(context, wf, firstStep, wfi); } } } // remove the WorkspaceItem wsi.deleteWrapper(); return wfi; } private static void activateFirstStep(Context context, Workflow wf, Step firstStep, WorkflowItem wfi) throws AuthorizeException, IOException, SQLException, TransformerException, WorkflowException, SAXException, WorkflowConfigurationException, ParserConfigurationException { WorkflowActionConfig firstActionConfig = firstStep.getUserSelectionMethod(); firstActionConfig.getProcessingAction().activate(context, wfi); log.info(LogManager.getHeader(context, "start_workflow", firstActionConfig.getProcessingAction() + " workflow_item_id=" + wfi.getID() + "item_id=" + wfi.getItem().getID() + "collection_id=" + wfi.getCollection().getID())); // record the start of the workflow w/provenance message recordStart(wfi.getItem(), firstActionConfig.getProcessingAction()); //If we don't have a UI activate it if(!firstActionConfig.hasUserInterface()){ ActionResult outcome = firstActionConfig.getProcessingAction().execute(context, wfi, firstStep, null); processOutcome(context, null, wf, firstStep, firstActionConfig, outcome, wfi); } } /* * Executes an action and returns the next. */ public static WorkflowActionConfig doState(Context c, EPerson user, HttpServletRequest request, int workflowItemId, Workflow workflow, WorkflowActionConfig currentActionConfig) throws SQLException, AuthorizeException, IOException, MessagingException, WorkflowConfigurationException, WorkflowException { try { WorkflowItem wi = WorkflowItem.find(c, workflowItemId); Step currentStep = currentActionConfig.getStep(); ActionResult outcome = currentActionConfig.getProcessingAction().execute(c, wi, currentStep, request); return processOutcome(c, user, workflow, currentStep, currentActionConfig, outcome, wi); } catch (WorkflowConfigurationException e) { WorkflowUtils.sendAlert(request, e); throw e; } catch (ParserConfigurationException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); e.printStackTrace(); throw new WorkflowException("An unknown exception occurred while performing action"); } catch (SAXException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); e.printStackTrace(); throw new WorkflowException("An unknown exception occurred while performing action"); } catch (TransformerException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); e.printStackTrace(); throw new WorkflowException("An unknown exception occurred while performing action"); } } public static WorkflowActionConfig processOutcome(Context c, EPerson user, Workflow workflow, Step currentStep, WorkflowActionConfig currentActionConfig, ActionResult currentOutcome, WorkflowItem wfi) throws TransformerException, IOException, SAXException, WorkflowConfigurationException, ParserConfigurationException, AuthorizeException, SQLException, WorkflowException { if(currentOutcome.getType() == ActionResult.TYPE.TYPE_PAGE || currentOutcome.getType() == ActionResult.TYPE.TYPE_ERROR){ //Our outcome is a page or an error, so return our current action return currentActionConfig; }else if(currentOutcome.getType() == ActionResult.TYPE.TYPE_CANCEL || currentOutcome.getType() == ActionResult.TYPE.TYPE_SUBMISSION_PAGE){ //We either pressed the cancel button or got an order to return to the submission page, so don't return an action //By not returning an action we ensure ourselfs that we go back to the submission page return null; }else if (currentOutcome.getType() == ActionResult.TYPE.TYPE_OUTCOME) { //We have completed our action search & retrieve the next action WorkflowActionConfig nextActionConfig = null; if(currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE){ nextActionConfig = currentStep.getNextAction(currentActionConfig); } if (nextActionConfig != null) { nextActionConfig.getProcessingAction().activate(c, wfi); if (nextActionConfig.hasUserInterface()) { //TODO: if user is null, then throw a decent exception ! createOwnedTask(c, wfi, currentStep, nextActionConfig, user); return nextActionConfig; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, currentStep, null); return processOutcome(c, user, workflow, currentStep, nextActionConfig, newOutcome, wfi); } }else { //First add it to our list of finished users, since no more actions remain WorkflowRequirementsManager.addFinishedUser(c, wfi, user); c.turnOffAuthorisationSystem(); //Check if our requirements have been met if((currentStep.isFinished(wfi) && currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE) || currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ //Clear all the metadata that might be saved by this step WorkflowRequirementsManager.clearStepMetadata(wfi); //Remove all the tasks WorkflowManager.deleteAllTasks(c, wfi); Step nextStep = workflow.getNextStep(c, wfi, currentStep, currentOutcome.getResult()); if(nextStep!=null){ //TODO: is generate tasks nog nodig of kan dit mee in activate? //TODO: vorige step zou meegegeven moeten worden om evt rollen te kunnen overnemen nextActionConfig = nextStep.getUserSelectionMethod(); nextActionConfig.getProcessingAction().activate(c, wfi); // nextActionConfig.getProcessingAction().generateTasks(); //Deze kunnen<SUF> if (nextActionConfig.hasUserInterface()) { //Since a new step has been started, stop executing actions once one with a user interface is present. c.restoreAuthSystemState(); return null; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, nextStep, null); c.restoreAuthSystemState(); return processOutcome(c, user, workflow, nextStep, nextActionConfig, newOutcome, wfi); } }else{ if(currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ c.restoreAuthSystemState(); throw new WorkflowException("No alternate step was found for outcome: " + currentOutcome.getResult()); } //This is dryad only, if(DryadWorkflowUtils.isDataPackage(wfi)){ //We have a data package //First archive the data package Item archivedDataSet = archive(c, wfi, true); //We need to find all the items linked to this publication Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wfi.getItem()); for (Item dataFile : dataFiles) { WorkflowItem wfiDataFile = WorkflowItem.findByItemId(c, dataFile.getID()); archive(c, wfiDataFile, false); } //Next delete any workspace items still open for this data set WorkspaceItem[] workspaceItems = WorkspaceItem.findByEPerson(c, c.getCurrentUser()); for (WorkspaceItem workspaceItem : workspaceItems) { Item owningDataset = DryadWorkflowUtils.getDataPackage(c, workspaceItem.getItem()); if (owningDataset != null && owningDataset.getID() == archivedDataSet.getID()) workspaceItem.deleteAll(); } }else{ //We have a single data file, archive it archive(c, wfi, true); } c.restoreAuthSystemState(); return null; } }else{ //We are done with our actions so go to the submissions page c.restoreAuthSystemState(); return null; } } } //TODO: log & go back to submission, We should not come here //TODO: remove assertion - can be used for testing (will throw assertionexception) assert false; return null; } //TODO: nakijken /** * Commit the contained item to the main archive. The item is associated * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. * * @return the fully archived item. */ public static Item archive(Context c, WorkflowItem wfi, boolean notify) throws SQLException, IOException, AuthorizeException { // FIXME: Check auth Item item = wfi.getItem(); Collection collection = wfi.getCollection(); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wfi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } log.info(LogManager.getHeader(c, "archive_item", "workflow_item_id=" + wfi.getID() + "item_id=" + item.getID() + "collection_id=" + collection.getID())); InstallItem.installItem(c, wfi); if(notify){ //Notify WorkflowEmailManager.notifyOfArchive(c, item); } //Clear any remaining workflow metadata item.clearMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA, Item.ANY, Item.ANY, Item.ANY); item.update(); // Log the event log.info(LogManager.getHeader(c, "install_item", "workflow_item_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME")); return item; } /*********************************** * WORKFLOW TASK MANAGEMENT **********************************/ /** * Deletes all tasks from this workflowflowitem * @param c the dspace context * @param wi the workflow item for whom we are to delete the tasks * @throws SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static void deleteAllTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { deleteAllPooledTasks(c, wi); List<ClaimedTask> allClaimedTasks = ClaimedTask.findByWorkflowId(c,wi.getID()); for(ClaimedTask task: allClaimedTasks){ deleteClaimedTask(c, wi, task); } } public static void deleteAllPooledTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { List<PoolTask> allPooledTasks = PoolTask.find(c, wi); for (PoolTask poolTask : allPooledTasks) { deletePooledTask(c, wi, poolTask); } } /* * Deletes an eperson from the taskpool of a step */ public static void deletePooledTask(Context c, WorkflowItem wi, PoolTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getEpersonID())); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wi.getItem()); for (Item dataFile : dataFiles) { removeUserItemPolicies(c, dataFile, EPerson.find(c, task.getEpersonID())); } } } public static void deleteClaimedTask(Context c, WorkflowItem wi, ClaimedTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getOwnerID())); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wi.getItem()); for (Item dataFile : dataFiles) { removeUserItemPolicies(c, dataFile, EPerson.find(c, task.getOwnerID())); } } } /* * Creates a task pool for a given step */ public static void createPoolTasks(Context context, WorkflowItem wi, EPerson[] epa, Step step, WorkflowActionConfig action) throws SQLException, AuthorizeException { // create a tasklist entry for each eperson for (EPerson anEpa : epa) { PoolTask task = PoolTask.create(context); task.setStepID(step.getId()); task.setWorkflowID(step.getWorkflow().getID()); task.setEpersonID(anEpa.getID()); task.setActionID(action.getId()); task.setWorkflowItemID(wi.getID()); task.update(); //Make sure this user has a task grantUserAllItemPolicies(context, wi.getItem(), anEpa); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, wi.getItem()); for (Item dataFile : dataFiles) { grantUserAllItemPolicies(context, dataFile, anEpa); } } } /* * Claims an action for a given eperson */ public static void createOwnedTask(Context c, WorkflowItem wi, Step step, WorkflowActionConfig action, EPerson e) throws SQLException, AuthorizeException { ClaimedTask task = ClaimedTask.create(c); task.setWorkflowItemID(wi.getID()); task.setStepID(step.getId()); task.setActionID(action.getId()); if(e != null) task.setOwnerID(e.getID()); task.setWorkflowID(step.getWorkflow().getID()); task.update(); if(e != null){ //Make sure this user has a task grantUserAllItemPolicies(c, wi.getItem(), e); //Also make sure that the user gets policies on our data files Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, wi.getItem()); for (Item dataFile : dataFiles) { grantUserAllItemPolicies(c, dataFile, e); } } } private static void grantUserAllItemPolicies(Context context, Item item, EPerson epa) throws AuthorizeException, SQLException { //A list of policies the user has for this item List<Integer> userHasPolicies = new ArrayList<Integer>(); List<ResourcePolicy> itempols = AuthorizeManager.getPolicies(context, item); for (ResourcePolicy resourcePolicy : itempols) { if(resourcePolicy.getEPersonID() == epa.getID()){ //The user has already got this policy so it it to the list userHasPolicies.add(resourcePolicy.getAction()); } } //Make sure we don't add duplicate policies if(!userHasPolicies.contains(Constants.READ)) addPolicyToItem(context, item, Constants.READ, epa); if(!userHasPolicies.contains(Constants.WRITE)) addPolicyToItem(context, item, Constants.WRITE, epa); if(!userHasPolicies.contains(Constants.DELETE)) addPolicyToItem(context, item, Constants.DELETE, epa); if(!userHasPolicies.contains(Constants.ADD)) addPolicyToItem(context, item, Constants.ADD, epa); } private static void addPolicyToItem(Context context, Item item, int type, EPerson epa) throws AuthorizeException, SQLException { AuthorizeManager.addPolicy(context ,item, type, epa); Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { AuthorizeManager.addPolicy(context ,bundle, type, epa); Bitstream[] bits = bundle.getBitstreams(); for (Bitstream bit : bits) { AuthorizeManager.addPolicy(context, bit, type, epa); } } } private static void removeUserItemPolicies(Context context, Item item, EPerson e) throws SQLException, AuthorizeException { //Also remove any lingering authorizations from this user removePoliciesFromDso(context, item, e); //Remove the bundle rights Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { removePoliciesFromDso(context, bundle, e); Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { removePoliciesFromDso(context, bitstream, e); } } } private static void removePoliciesFromDso(Context context, DSpaceObject item, EPerson e) throws SQLException, AuthorizeException { List<ResourcePolicy> policies = AuthorizeManager.getPolicies(context, item); AuthorizeManager.removeAllPolicies(context, item); for (ResourcePolicy resourcePolicy : policies) { if( resourcePolicy.getEPerson() ==null || resourcePolicy.getEPersonID() != e.getID()){ if(resourcePolicy.getEPerson() != null) AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getEPerson()); else AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getGroup()); } } } /** * rejects an item - rejection means undoing a submit - WorkspaceItem is * created, and the WorkflowItem is removed, user is emailed * rejection_message. * * @param c * Context * @param wi * WorkflowItem to operate on * @param e * EPerson doing the operation * @param action the action which triggered this reject * @param rejection_message * message to email to user * @return the workspace item that is created * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static WorkspaceItem rejectWorkflowItem(Context c, WorkflowItem wi, EPerson e, Action action, String rejection_message, boolean sendMail) throws SQLException, AuthorizeException, IOException { // authorize a DSpaceActions.REJECT // stop workflow deleteAllTasks(c, wi); //Also clear all info for this step WorkflowRequirementsManager.clearStepMetadata(wi); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } // rejection provenance Item myitem = wi.getItem(); // Get current date String now = DCDate.getCurrent().toString(); org.dspace.content.Item[] dataFiles = DryadWorkflowUtils.getDataFiles(c, myitem); if(dataFiles!=null){ for(Item dataFile:dataFiles) { if(dataFile.getMetadata("internal", "workflow", "submitted", Item.ANY).length == 0){ //A newly (re-)submitted publication dataFile.addMetadata("internal", "workflow", "submitted", null, Boolean.TRUE.toString()); myitem.update(); } } } // Here's what happened if(action != null){ // Get user's name + email address String usersName = getEPersonName(e); String provDescription = action.getProvenanceStartId() + " Rejected by " + usersName + ", reason: " + rejection_message + " on " + now + " (GMT) "; // Add to item as a DC field myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provDescription); } myitem.update(); // convert into personal workspace WorkspaceItem wsi = returnToWorkspace(c, wi); if(sendMail){ // notify that it's been rejected WorkflowEmailManager.notifyOfReject(c, wi, e, rejection_message); } log.info(LogManager.getHeader(c, "reject_workflow", "workflow_item_id=" + wi.getID() + "item_id=" + wi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "eperson_id=" + (e == null ? "" : e.getID()))); return wsi; } /** * Return the workflow item to the workspace of the submitter. The workflow * item is removed, and a workspace item created. * * @param c * Context * @param wfi * WorkflowItem to be 'dismantled' * @return the workspace item * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { Item myitem = wfi.getItem(); Collection myCollection = wfi.getCollection(); // FIXME: How should this interact with the workflow system? // FIXME: Remove license // FIXME: Provenance statement? // Create the new workspace item row TableRow row = DatabaseManager.create(c, "workspaceitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", myCollection.getID()); DatabaseManager.update(c, row); int wsi_id = row.getIntColumn("workspace_item_id"); WorkspaceItem wi = WorkspaceItem.find(c, wsi_id); wi.setMultipleFiles(wfi.hasMultipleFiles()); wi.setMultipleTitles(wfi.hasMultipleTitles()); wi.setPublishedBefore(wfi.isPublishedBefore()); wi.update(); //myitem.update(); log.info(LogManager.getHeader(c, "return_to_workspace", "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + wi.getID())); // Now remove the workflow object manually from the database DatabaseManager.updateQuery(c, "DELETE FROM WorkflowItem WHERE workflow_id=" + wfi.getID()); return wi; } public static String getEPersonName(EPerson e) throws SQLException { String submitter = e.getFullName(); submitter = submitter + "(" + e.getEmail() + ")"; return submitter; } // Create workflow start provenance message private static void recordStart(Item myitem, Action action) throws SQLException, IOException, AuthorizeException { // get date DCDate now = DCDate.getCurrent(); // Create provenance description String provmessage = ""; if (myitem.getSubmitter() != null) { provmessage = "Submitted by " + myitem.getSubmitter().getFullName() + " (" + myitem.getSubmitter().getEmail() + ") on " + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } else // null submitter { provmessage = "Submitted by unknown (probably automated) on" + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } // add sizes and checksums of bitstreams provmessage += InstallItem.getBitstreamProvenanceMessage(myitem); // Add message to the DC myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provmessage); myitem.update(); } public static String getMyDSpaceLink() { return ConfigurationManager.getProperty("dspace.url") + "/mydspace"; } // Classes that are not customized by Dryad call this, so it remains for // compatibility public static void notifyOfCuration(Context c, WorkflowItem wi, EPerson[] epa, String taskName, String action, String message) throws SQLException, IOException { WorkflowEmailManager.notifyOfCuration(c, wi, epa, taskName, action, message); } /** * get the title of the item in this workflow * * @param wi the workflow item object */ public static String getItemTitle(WorkflowItem wi) throws SQLException { Item myitem = wi.getItem(); DCValue[] titles = myitem.getDC("title", null, Item.ANY); // only return the first element, or "Untitled" if (titles.length > 0) { return titles[0].value; } else { return I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled "); } } /** * get the name of the eperson who started this workflow * * @param wi the workflow item */ public static String getSubmitterName(WorkflowItem wi) throws SQLException { EPerson e = wi.getSubmitter(); return getEPersonName(e); } }
99635_10
package com.example.AppArt.thaliapp.Calendar.Backend; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.example.AppArt.thaliapp.R; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; /** * Withholds all knowledge of a ThaliaEvent * * @author Frank Gerlings (s4384873), Lisa Kalse (s4338340), Serena Rietbergen (s4182804) */ public class ThaliaEvent implements Comparable<ThaliaEvent>, Parcelable { private final GregorianCalendar startDate = new GregorianCalendar(); private final GregorianCalendar endDate = new GregorianCalendar(); private final String location; private final String description; private final String summary; private final EventCategory category; private final int catIcon; /** * Initialises the Event object given string input. * * @param startDate The starting time of the event in millis * @param endDate The ending time of the event in millis * @param location The location of the event * @param description A large description of the event * @param summary The event in 3 words or fewer */ public ThaliaEvent(Long startDate, Long endDate, String location, String description, String summary) { this.startDate.setTimeInMillis(startDate); this.endDate.setTimeInMillis(endDate); this.location = location; this.description = description; this.summary = summary; this.category = categoryFinder(); this.catIcon = catIconFinder(category); } /***************************************************************** Methods to help initialise *****************************************************************/ /** * Uses the summary and the description of an ThaliaEvent to figure out what * category it is. * * When multiple keywords are found it will use the following order: * LECTURE > PARTY > ALV > WORKSHOP > BORREL > DEFAULT * (e.g. kinderFEESTjesBORREL -> PARTY) * * @return an EventCategory */ private EventCategory categoryFinder() { String eventText = this.summary.concat(this.description); if (eventText.matches("(?i:.*lezing.*)")) { return EventCategory.LECTURE; } else if (eventText.matches("(?i:.*feest.*)") || eventText.matches("(?i:.*party.*)")) { return EventCategory.PARTY; } else if (eventText.matches("(?i:.*alv.*)")){ return EventCategory.ALV; } else if (eventText.matches("(?i:.*workshop.*)")) { return EventCategory.WORKSHOP; } else if (eventText.matches("(?i:.*borrel.*)")) { return EventCategory.BORREL; } else return EventCategory.DEFAULT; } /** * Returns the right drawable according to the category * * @param cat the category of this event * @return A .png file that represents the category of this event */ private int catIconFinder(EventCategory cat) { int catIcon; switch (cat) { case ALV: catIcon = R.drawable.alvicoon; break; case BORREL: catIcon = R.drawable.borrelicoon; break; case LECTURE: catIcon = R.drawable.lezingicoon; break; case PARTY: catIcon = R.drawable.feesticoon; break; case WORKSHOP: catIcon = R.drawable.workshopicoon; break; default: catIcon = R.drawable.overigicoon; } return catIcon; } /***************************************************************** Getters for all attributes *****************************************************************/ public GregorianCalendar getStartDate() { return startDate; } public GregorianCalendar getEndDate() { return endDate; } public String getLocation() { return location; } /** * A possibly broad description of the ThaliaEvent * Can contain HTML * @return possibly very large string */ public String getDescription() { return description; } /** * The ThaliaEvent in less than 5 words * Can contain HTML * @return small String */ public String getSummary() { return summary; } public EventCategory getCategory() { return category; } public int getCatIcon() { return catIcon; } /** * Small composition of ThaliaEvent information * @return summary + "\n" + duration() + "\n" + location */ public String makeSynopsis() { return summary + "\n" + duration() + "\n" + location; } /** * A readable abbreviation of the day * e.g. di 18 aug * * @return dd - dd - mmm */ public String getDateString() { StringBuilder date; date = new StringBuilder(""); date.append(this.startDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault())); date.append(" "); date.append(this.startDate.get(Calendar.DAY_OF_MONTH)); date.append(" "); date.append(this.startDate.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())); return date.toString(); } /***************************************************************** Default Methods *****************************************************************/ /** * A neat stringformat of the beginning and ending times * * @return hh:mm-hh:mm */ public String duration() { StringBuilder sb = new StringBuilder(); sb.append(startDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (startDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(startDate.get(Calendar.MINUTE)); } sb.append(" - "); sb.append(endDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (endDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(endDate.get(Calendar.MINUTE)); } System.out.println("EoF durationfunction: "+sb.toString()); return sb.toString(); } /** * Printmethod, useful when you're debugging * * @return a string of the event */ @Override public String toString() { return ("\nstart = " + startDate + ", end = " + endDate + "\nlocation = " + location + "\ndescription = " + description + "\nsummary = " + summary); } /** * @param another the ThaliaEvent with which you want to compare it * @return The difference in time between the two */ @Override public int compareTo(@NonNull ThaliaEvent another) { return startDate.compareTo(another.startDate); } /***************************************************************** Making it a Parcelable, so it can be passed through with an intent *****************************************************************/ @Override public int describeContents() { return 0; } /** * Pretty much all information about this ThaliaEvent object is being * compressed into a Parcel * * @param dest Destination * @param flags Flags */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startDate.getTimeInMillis()); dest.writeLong(endDate.getTimeInMillis()); dest.writeString(location); dest.writeString(description); dest.writeString(summary); } /** * Reconstructs the ThaliaEvent through a parcel. */ public static final Parcelable.Creator<ThaliaEvent> CREATOR = new Parcelable.Creator<ThaliaEvent>() { // Parcels work FIFO public ThaliaEvent createFromParcel(Parcel parcel) { Long startDate = parcel.readLong(); Long endDate = parcel.readLong(); String location = parcel.readString(); String description = parcel.readString(); String summary = parcel.readString(); return new ThaliaEvent(startDate, endDate, location, description, summary); } public ThaliaEvent[] newArray(int size) { return new ThaliaEvent[size]; } }; }
yorickvP/ThaliAppMap
app/src/main/java/com/example/AppArt/thaliapp/Calendar/Backend/ThaliaEvent.java
2,340
/***************************************************************** Default Methods *****************************************************************/
block_comment
nl
package com.example.AppArt.thaliapp.Calendar.Backend; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.example.AppArt.thaliapp.R; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; /** * Withholds all knowledge of a ThaliaEvent * * @author Frank Gerlings (s4384873), Lisa Kalse (s4338340), Serena Rietbergen (s4182804) */ public class ThaliaEvent implements Comparable<ThaliaEvent>, Parcelable { private final GregorianCalendar startDate = new GregorianCalendar(); private final GregorianCalendar endDate = new GregorianCalendar(); private final String location; private final String description; private final String summary; private final EventCategory category; private final int catIcon; /** * Initialises the Event object given string input. * * @param startDate The starting time of the event in millis * @param endDate The ending time of the event in millis * @param location The location of the event * @param description A large description of the event * @param summary The event in 3 words or fewer */ public ThaliaEvent(Long startDate, Long endDate, String location, String description, String summary) { this.startDate.setTimeInMillis(startDate); this.endDate.setTimeInMillis(endDate); this.location = location; this.description = description; this.summary = summary; this.category = categoryFinder(); this.catIcon = catIconFinder(category); } /***************************************************************** Methods to help initialise *****************************************************************/ /** * Uses the summary and the description of an ThaliaEvent to figure out what * category it is. * * When multiple keywords are found it will use the following order: * LECTURE > PARTY > ALV > WORKSHOP > BORREL > DEFAULT * (e.g. kinderFEESTjesBORREL -> PARTY) * * @return an EventCategory */ private EventCategory categoryFinder() { String eventText = this.summary.concat(this.description); if (eventText.matches("(?i:.*lezing.*)")) { return EventCategory.LECTURE; } else if (eventText.matches("(?i:.*feest.*)") || eventText.matches("(?i:.*party.*)")) { return EventCategory.PARTY; } else if (eventText.matches("(?i:.*alv.*)")){ return EventCategory.ALV; } else if (eventText.matches("(?i:.*workshop.*)")) { return EventCategory.WORKSHOP; } else if (eventText.matches("(?i:.*borrel.*)")) { return EventCategory.BORREL; } else return EventCategory.DEFAULT; } /** * Returns the right drawable according to the category * * @param cat the category of this event * @return A .png file that represents the category of this event */ private int catIconFinder(EventCategory cat) { int catIcon; switch (cat) { case ALV: catIcon = R.drawable.alvicoon; break; case BORREL: catIcon = R.drawable.borrelicoon; break; case LECTURE: catIcon = R.drawable.lezingicoon; break; case PARTY: catIcon = R.drawable.feesticoon; break; case WORKSHOP: catIcon = R.drawable.workshopicoon; break; default: catIcon = R.drawable.overigicoon; } return catIcon; } /***************************************************************** Getters for all attributes *****************************************************************/ public GregorianCalendar getStartDate() { return startDate; } public GregorianCalendar getEndDate() { return endDate; } public String getLocation() { return location; } /** * A possibly broad description of the ThaliaEvent * Can contain HTML * @return possibly very large string */ public String getDescription() { return description; } /** * The ThaliaEvent in less than 5 words * Can contain HTML * @return small String */ public String getSummary() { return summary; } public EventCategory getCategory() { return category; } public int getCatIcon() { return catIcon; } /** * Small composition of ThaliaEvent information * @return summary + "\n" + duration() + "\n" + location */ public String makeSynopsis() { return summary + "\n" + duration() + "\n" + location; } /** * A readable abbreviation of the day * e.g. di 18 aug * * @return dd - dd - mmm */ public String getDateString() { StringBuilder date; date = new StringBuilder(""); date.append(this.startDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault())); date.append(" "); date.append(this.startDate.get(Calendar.DAY_OF_MONTH)); date.append(" "); date.append(this.startDate.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())); return date.toString(); } /***************************************************************** Default Methods <SUF>*/ /** * A neat stringformat of the beginning and ending times * * @return hh:mm-hh:mm */ public String duration() { StringBuilder sb = new StringBuilder(); sb.append(startDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (startDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(startDate.get(Calendar.MINUTE)); } sb.append(" - "); sb.append(endDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (endDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(endDate.get(Calendar.MINUTE)); } System.out.println("EoF durationfunction: "+sb.toString()); return sb.toString(); } /** * Printmethod, useful when you're debugging * * @return a string of the event */ @Override public String toString() { return ("\nstart = " + startDate + ", end = " + endDate + "\nlocation = " + location + "\ndescription = " + description + "\nsummary = " + summary); } /** * @param another the ThaliaEvent with which you want to compare it * @return The difference in time between the two */ @Override public int compareTo(@NonNull ThaliaEvent another) { return startDate.compareTo(another.startDate); } /***************************************************************** Making it a Parcelable, so it can be passed through with an intent *****************************************************************/ @Override public int describeContents() { return 0; } /** * Pretty much all information about this ThaliaEvent object is being * compressed into a Parcel * * @param dest Destination * @param flags Flags */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startDate.getTimeInMillis()); dest.writeLong(endDate.getTimeInMillis()); dest.writeString(location); dest.writeString(description); dest.writeString(summary); } /** * Reconstructs the ThaliaEvent through a parcel. */ public static final Parcelable.Creator<ThaliaEvent> CREATOR = new Parcelable.Creator<ThaliaEvent>() { // Parcels work FIFO public ThaliaEvent createFromParcel(Parcel parcel) { Long startDate = parcel.readLong(); Long endDate = parcel.readLong(); String location = parcel.readString(); String description = parcel.readString(); String summary = parcel.readString(); return new ThaliaEvent(startDate, endDate, location, description, summary); } public ThaliaEvent[] newArray(int size) { return new ThaliaEvent[size]; } }; }
68134_4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package chess_ndl; import java.util.Scanner; /** * * @author newdeviceslab_2 */ public class UserInterface { private final boolean humanColor; private final boolean engineColor; private final Board board; private final Player engine; public UserInterface(boolean player) { humanColor = player; engineColor = !player; board = new Board(); engine = new Player(engineColor, 50, 5, 1); //parameters voor evaluatie-algoritme while (true) { playWhite(); playBlack(); } } private void playWhite() { if (humanColor) { board.movePiece(enterMove(humanColor), true); } else { Move move = engine.decideMove(board); System.out.println(move); //output van engine zit in de toString() van klasse Move board.movePiece(move, true); } System.out.println(board); //voor menselijke gebruiker van dit programma: overbodig voor ndl } private void playBlack() { if (!humanColor) { board.movePiece(enterMove(humanColor), true); } else { Move move = engine.decideMove(board); System.out.println(move); board.movePiece(move, true); } System.out.println(board); } /** * input van gewenste zet wordt hier geformatteerd; * nu in format [startveld][eindveld], bij rokade start- en eindveld van de koning * @param color * @return */ private Move enterMove(boolean color) { Scanner scanner = new Scanner(System.in); Move cand; do { String s = scanner.nextLine(); StringBuilder from = new StringBuilder(); from.append(s.charAt(0)); from.append(s.charAt(1)); StringBuilder to = new StringBuilder(); to.append(s.charAt(2)); to.append(s.charAt(3)); cand = new Move(translateToPoint(from.toString()), translateToPoint(to.toString())); } while (!board.legalMove(cand, color)); return cand; } private Point translateToPoint(String s) { char letter = s.charAt(0); int digit = s.charAt(1) - '0'; return new Point(8 - digit, letter - 'a'); } private String translateToString(Point p) { return null; } }
yorickvP/explosivechess
ndl_chess/UserInterface.java
743
//voor menselijke gebruiker van dit programma: overbodig voor ndl
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package chess_ndl; import java.util.Scanner; /** * * @author newdeviceslab_2 */ public class UserInterface { private final boolean humanColor; private final boolean engineColor; private final Board board; private final Player engine; public UserInterface(boolean player) { humanColor = player; engineColor = !player; board = new Board(); engine = new Player(engineColor, 50, 5, 1); //parameters voor evaluatie-algoritme while (true) { playWhite(); playBlack(); } } private void playWhite() { if (humanColor) { board.movePiece(enterMove(humanColor), true); } else { Move move = engine.decideMove(board); System.out.println(move); //output van engine zit in de toString() van klasse Move board.movePiece(move, true); } System.out.println(board); //voor menselijke<SUF> } private void playBlack() { if (!humanColor) { board.movePiece(enterMove(humanColor), true); } else { Move move = engine.decideMove(board); System.out.println(move); board.movePiece(move, true); } System.out.println(board); } /** * input van gewenste zet wordt hier geformatteerd; * nu in format [startveld][eindveld], bij rokade start- en eindveld van de koning * @param color * @return */ private Move enterMove(boolean color) { Scanner scanner = new Scanner(System.in); Move cand; do { String s = scanner.nextLine(); StringBuilder from = new StringBuilder(); from.append(s.charAt(0)); from.append(s.charAt(1)); StringBuilder to = new StringBuilder(); to.append(s.charAt(2)); to.append(s.charAt(3)); cand = new Move(translateToPoint(from.toString()), translateToPoint(to.toString())); } while (!board.legalMove(cand, color)); return cand; } private Point translateToPoint(String s) { char letter = s.charAt(0); int digit = s.charAt(1) - '0'; return new Point(8 - digit, letter - 'a'); } private String translateToString(Point p) { return null; } }
131545_1
package com.example.jingbin.cloudreader.adapter; import android.content.Context; import android.content.DialogInterface; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions; import com.example.jingbin.cloudreader.R; import com.example.jingbin.cloudreader.app.App; import com.example.jingbin.cloudreader.bean.AndroidBean; import com.example.jingbin.cloudreader.databinding.ItemEverydayOneBinding; import com.example.jingbin.cloudreader.databinding.ItemEverydayThreeBinding; import com.example.jingbin.cloudreader.databinding.ItemEverydayTitleBinding; import com.example.jingbin.cloudreader.databinding.ItemEverydayTwoBinding; import me.jingbin.bymvvm.rxbus.RxBus; import com.example.jingbin.cloudreader.app.RxCodeConstants; import com.example.jingbin.cloudreader.utils.DensityUtil; import com.example.jingbin.cloudreader.utils.DialogBuild; import com.example.jingbin.cloudreader.utils.GlideUtil; import com.example.jingbin.cloudreader.utils.PerfectClickListener; import com.example.jingbin.cloudreader.ui.WebViewActivity; import java.util.ArrayList; import java.util.List; import me.jingbin.bymvvm.adapter.BaseBindingHolder; import me.jingbin.library.adapter.BaseByRecyclerViewAdapter; import me.jingbin.library.adapter.BaseByViewHolder; /** * Created by jingbin on 2016/12/27. */ public class EverydayAdapter extends BaseByRecyclerViewAdapter<ArrayList<AndroidBean>, BaseByViewHolder> { private static final int TYPE_TITLE = 1; // title private static final int TYPE_ONE = 2;// 一张图 private static final int TYPE_TWO = 3;// 二张图 private static final int TYPE_THREE = 4;// 三张图 private int width; public EverydayAdapter() { WindowManager wm = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE); width = wm.getDefaultDisplay().getWidth(); } @Override public int getItemViewType(int position) { if (!TextUtils.isEmpty(getData().get(position).get(0).gettypeTitle())) { return TYPE_TITLE; } else if (getData().get(position).size() == 1) { return TYPE_ONE; } else if (getData().get(position).size() == 2) { return TYPE_TWO; } else if (getData().get(position).size() == 3) { return TYPE_THREE; } return super.getItemViewType(position); } @NonNull @Override public BaseByViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { switch (viewType) { case TYPE_TITLE: return new TitleHolder(parent, R.layout.item_everyday_title); case TYPE_ONE: return new OneHolder(parent, R.layout.item_everyday_one); case TYPE_TWO: return new TwoHolder(parent, R.layout.item_everyday_two); default: return new ThreeHolder(parent, R.layout.item_everyday_three); } } private class TitleHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayTitleBinding> { TitleHolder(ViewGroup parent, int title) { super(parent, title); } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { int index = 0; String title = object.get(0).gettypeTitle(); binding.tvTitleType.setText(title); if ("Android".equals(title)) { index = 0; } else if ("福利".equals(title)) { index = 1; } else if ("iOS".equals(title)) { index = 2; } else if ("休息视频".equals(title)) { index = 2; } else if ("拓展资源".equals(title)) { index = 2; } else if ("瞎推荐".equals(title)) { index = 2; } else if ("前端".equals(title)) { index = 2; } else if ("App".equals(title)) { index = 2; } if (position != 0) { binding.viewLine.setVisibility(View.VISIBLE); } else { binding.viewLine.setVisibility(View.GONE); } final int finalIndex = index; binding.llTitleMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RxBus.getDefault().post(RxCodeConstants.JUMP_TYPE, finalIndex); } }); } } private class OneHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayOneBinding> { OneHolder(ViewGroup parent, int title) { super(parent, title); } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { DensityUtil.setWidthHeight(binding.ivOnePhoto, width, 2.6f); if ("福利".equals(object.get(0).getType())) { binding.tvOnePhotoTitle.setVisibility(View.GONE); binding.ivOnePhoto.setScaleType(ImageView.ScaleType.CENTER_CROP); // ImageLoadUtil.displayEspImage(object.get(0).getUrl(), binding.ivOnePhoto, 1); Glide.with(binding.ivOnePhoto.getContext()) .load(object.get(0).getUrl()) .transition(DrawableTransitionOptions.withCrossFade(1500)) .placeholder(R.drawable.img_two_bi_one) .error(R.drawable.img_two_bi_one) .into(binding.ivOnePhoto); } else { binding.tvOnePhotoTitle.setVisibility(View.VISIBLE); setDes(object, 0, binding.tvOnePhotoTitle); displayRandomImg(1, 0, binding.ivOnePhoto, object); } setOnClick(binding.llOnePhoto, object.get(0)); } } private class TwoHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayTwoBinding> { private int imageWidth; TwoHolder(ViewGroup parent, int title) { super(parent, title); imageWidth = (width - DensityUtil.dip2px(parent.getContext(), 3)) / 2; } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { DensityUtil.setWidthHeight(binding.ivTwoOneOne, imageWidth, 1.75f); DensityUtil.setWidthHeight(binding.ivTwoOneTwo, imageWidth, 1.75f); displayRandomImg(2, 0, binding.ivTwoOneOne, object); displayRandomImg(2, 1, binding.ivTwoOneTwo, object); setDes(object, 0, binding.tvTwoOneOneTitle); setDes(object, 1, binding.tvTwoOneTwoTitle); setOnClick(binding.llTwoOneOne, object.get(0)); setOnClick(binding.llTwoOneTwo, object.get(1)); } } private class ThreeHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayThreeBinding> { private int imageWidth; ThreeHolder(ViewGroup parent, int title) { super(parent, title); imageWidth = (width - DensityUtil.dip2px(parent.getContext(), 6)) / 3; } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { DensityUtil.setWidthHeight(binding.ivThreeOneOne, imageWidth, 1); DensityUtil.setWidthHeight(binding.ivThreeOneTwo, imageWidth, 1); DensityUtil.setWidthHeight(binding.ivThreeOneThree, imageWidth, 1); displayRandomImg(3, 0, binding.ivThreeOneOne, object); displayRandomImg(3, 1, binding.ivThreeOneTwo, object); displayRandomImg(3, 2, binding.ivThreeOneThree, object); setOnClick(binding.llThreeOneOne, object.get(0)); setOnClick(binding.llThreeOneTwo, object.get(1)); setOnClick(binding.llThreeOneThree, object.get(2)); setDes(object, 0, binding.tvThreeOneOneTitle); setDes(object, 1, binding.tvThreeOneTwoTitle); setDes(object, 2, binding.tvThreeOneThreeTitle); } } private void setDes(List<AndroidBean> object, int position, TextView textView) { textView.setText(object.get(position).getDesc()); } private void displayRandomImg(int imgNumber, int position, ImageView imageView, List<AndroidBean> object) { // DebugUtil.error("-----Image_url: "+object.get(position).getImageUrl()); GlideUtil.displayRandom(imgNumber, object.get(position).getImageUrl(), imageView); } private void setOnClick(final LinearLayout linearLayout, final AndroidBean bean) { linearLayout.setOnClickListener(new PerfectClickListener() { @Override protected void onNoDoubleClick(View v) { WebViewActivity.loadUrl(v.getContext(), bean.getUrl(), bean.getDesc()); } }); linearLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String title = TextUtils.isEmpty(bean.getType()) ? bean.getDesc() : bean.getType() + ": " + bean.getDesc(); DialogBuild.showCustom(v, title, "查看详情", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { WebViewActivity.loadUrl(linearLayout.getContext(), bean.getUrl(), bean.getDesc()); } }); return false; } }); } }
youlookwhat/CloudReader
app/src/main/java/com/example/jingbin/cloudreader/adapter/EverydayAdapter.java
2,853
// ImageLoadUtil.displayEspImage(object.get(0).getUrl(), binding.ivOnePhoto, 1);
line_comment
nl
package com.example.jingbin.cloudreader.adapter; import android.content.Context; import android.content.DialogInterface; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions; import com.example.jingbin.cloudreader.R; import com.example.jingbin.cloudreader.app.App; import com.example.jingbin.cloudreader.bean.AndroidBean; import com.example.jingbin.cloudreader.databinding.ItemEverydayOneBinding; import com.example.jingbin.cloudreader.databinding.ItemEverydayThreeBinding; import com.example.jingbin.cloudreader.databinding.ItemEverydayTitleBinding; import com.example.jingbin.cloudreader.databinding.ItemEverydayTwoBinding; import me.jingbin.bymvvm.rxbus.RxBus; import com.example.jingbin.cloudreader.app.RxCodeConstants; import com.example.jingbin.cloudreader.utils.DensityUtil; import com.example.jingbin.cloudreader.utils.DialogBuild; import com.example.jingbin.cloudreader.utils.GlideUtil; import com.example.jingbin.cloudreader.utils.PerfectClickListener; import com.example.jingbin.cloudreader.ui.WebViewActivity; import java.util.ArrayList; import java.util.List; import me.jingbin.bymvvm.adapter.BaseBindingHolder; import me.jingbin.library.adapter.BaseByRecyclerViewAdapter; import me.jingbin.library.adapter.BaseByViewHolder; /** * Created by jingbin on 2016/12/27. */ public class EverydayAdapter extends BaseByRecyclerViewAdapter<ArrayList<AndroidBean>, BaseByViewHolder> { private static final int TYPE_TITLE = 1; // title private static final int TYPE_ONE = 2;// 一张图 private static final int TYPE_TWO = 3;// 二张图 private static final int TYPE_THREE = 4;// 三张图 private int width; public EverydayAdapter() { WindowManager wm = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE); width = wm.getDefaultDisplay().getWidth(); } @Override public int getItemViewType(int position) { if (!TextUtils.isEmpty(getData().get(position).get(0).gettypeTitle())) { return TYPE_TITLE; } else if (getData().get(position).size() == 1) { return TYPE_ONE; } else if (getData().get(position).size() == 2) { return TYPE_TWO; } else if (getData().get(position).size() == 3) { return TYPE_THREE; } return super.getItemViewType(position); } @NonNull @Override public BaseByViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { switch (viewType) { case TYPE_TITLE: return new TitleHolder(parent, R.layout.item_everyday_title); case TYPE_ONE: return new OneHolder(parent, R.layout.item_everyday_one); case TYPE_TWO: return new TwoHolder(parent, R.layout.item_everyday_two); default: return new ThreeHolder(parent, R.layout.item_everyday_three); } } private class TitleHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayTitleBinding> { TitleHolder(ViewGroup parent, int title) { super(parent, title); } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { int index = 0; String title = object.get(0).gettypeTitle(); binding.tvTitleType.setText(title); if ("Android".equals(title)) { index = 0; } else if ("福利".equals(title)) { index = 1; } else if ("iOS".equals(title)) { index = 2; } else if ("休息视频".equals(title)) { index = 2; } else if ("拓展资源".equals(title)) { index = 2; } else if ("瞎推荐".equals(title)) { index = 2; } else if ("前端".equals(title)) { index = 2; } else if ("App".equals(title)) { index = 2; } if (position != 0) { binding.viewLine.setVisibility(View.VISIBLE); } else { binding.viewLine.setVisibility(View.GONE); } final int finalIndex = index; binding.llTitleMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RxBus.getDefault().post(RxCodeConstants.JUMP_TYPE, finalIndex); } }); } } private class OneHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayOneBinding> { OneHolder(ViewGroup parent, int title) { super(parent, title); } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { DensityUtil.setWidthHeight(binding.ivOnePhoto, width, 2.6f); if ("福利".equals(object.get(0).getType())) { binding.tvOnePhotoTitle.setVisibility(View.GONE); binding.ivOnePhoto.setScaleType(ImageView.ScaleType.CENTER_CROP); // ImageLoadUtil.displayEspImage(object.get(0).getUrl(), binding.ivOnePhoto,<SUF> Glide.with(binding.ivOnePhoto.getContext()) .load(object.get(0).getUrl()) .transition(DrawableTransitionOptions.withCrossFade(1500)) .placeholder(R.drawable.img_two_bi_one) .error(R.drawable.img_two_bi_one) .into(binding.ivOnePhoto); } else { binding.tvOnePhotoTitle.setVisibility(View.VISIBLE); setDes(object, 0, binding.tvOnePhotoTitle); displayRandomImg(1, 0, binding.ivOnePhoto, object); } setOnClick(binding.llOnePhoto, object.get(0)); } } private class TwoHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayTwoBinding> { private int imageWidth; TwoHolder(ViewGroup parent, int title) { super(parent, title); imageWidth = (width - DensityUtil.dip2px(parent.getContext(), 3)) / 2; } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { DensityUtil.setWidthHeight(binding.ivTwoOneOne, imageWidth, 1.75f); DensityUtil.setWidthHeight(binding.ivTwoOneTwo, imageWidth, 1.75f); displayRandomImg(2, 0, binding.ivTwoOneOne, object); displayRandomImg(2, 1, binding.ivTwoOneTwo, object); setDes(object, 0, binding.tvTwoOneOneTitle); setDes(object, 1, binding.tvTwoOneTwoTitle); setOnClick(binding.llTwoOneOne, object.get(0)); setOnClick(binding.llTwoOneTwo, object.get(1)); } } private class ThreeHolder extends BaseBindingHolder<List<AndroidBean>, ItemEverydayThreeBinding> { private int imageWidth; ThreeHolder(ViewGroup parent, int title) { super(parent, title); imageWidth = (width - DensityUtil.dip2px(parent.getContext(), 6)) / 3; } @Override protected void onBindingView(BaseBindingHolder holder, List<AndroidBean> object, int position) { DensityUtil.setWidthHeight(binding.ivThreeOneOne, imageWidth, 1); DensityUtil.setWidthHeight(binding.ivThreeOneTwo, imageWidth, 1); DensityUtil.setWidthHeight(binding.ivThreeOneThree, imageWidth, 1); displayRandomImg(3, 0, binding.ivThreeOneOne, object); displayRandomImg(3, 1, binding.ivThreeOneTwo, object); displayRandomImg(3, 2, binding.ivThreeOneThree, object); setOnClick(binding.llThreeOneOne, object.get(0)); setOnClick(binding.llThreeOneTwo, object.get(1)); setOnClick(binding.llThreeOneThree, object.get(2)); setDes(object, 0, binding.tvThreeOneOneTitle); setDes(object, 1, binding.tvThreeOneTwoTitle); setDes(object, 2, binding.tvThreeOneThreeTitle); } } private void setDes(List<AndroidBean> object, int position, TextView textView) { textView.setText(object.get(position).getDesc()); } private void displayRandomImg(int imgNumber, int position, ImageView imageView, List<AndroidBean> object) { // DebugUtil.error("-----Image_url: "+object.get(position).getImageUrl()); GlideUtil.displayRandom(imgNumber, object.get(position).getImageUrl(), imageView); } private void setOnClick(final LinearLayout linearLayout, final AndroidBean bean) { linearLayout.setOnClickListener(new PerfectClickListener() { @Override protected void onNoDoubleClick(View v) { WebViewActivity.loadUrl(v.getContext(), bean.getUrl(), bean.getDesc()); } }); linearLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String title = TextUtils.isEmpty(bean.getType()) ? bean.getDesc() : bean.getType() + ": " + bean.getDesc(); DialogBuild.showCustom(v, title, "查看详情", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { WebViewActivity.loadUrl(linearLayout.getContext(), bean.getUrl(), bean.getDesc()); } }); return false; } }); } }
70640_12
package nu.fw.jeti.plugins.ibb; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.LinkedList; import javax.swing.*; import nu.fw.jeti.backend.roster.Roster; import nu.fw.jeti.jabber.Backend; import nu.fw.jeti.jabber.JID; import nu.fw.jeti.jabber.JIDStatus; import nu.fw.jeti.jabber.elements.InfoQuery; import nu.fw.jeti.util.Base64; import nu.fw.jeti.util.I18N; import nu.fw.jeti.util.Popups; /** * <p>Title: im</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2001</p> * <p>Company: </p> * @author E.S. de Boer * @version 1.0 */ //TODO translate filetransfer warnings, or wait for socks filetransfer? public class GetFileWindow extends JFrame { private JPanel jPanel1 = new JPanel(); private JLabel jLabel1 = new JLabel(); private JTextArea jTextArea1 = new JTextArea(); private JLabel jLabel2 = new JLabel(); private JTextField jTextField1 = new JTextField(); private JPanel jPanel2 = new JPanel(); private JButton btnGetSize = new JButton(); private JPanel jPanel3 = new JPanel(); private JButton btnDownload = new JButton(); private JButton btnCancel = new JButton(); private URL url; private JProgressBar jProgressBar1 = new JProgressBar(); private String id; private JID jid; private Backend backend; //private URLConnection connection = null; private int length; private Draadje draadje; private JLabel lblDownload = new JLabel(); public GetFileWindow(JID jid,Backend backend, IBBExtension ibb) { //JOptionPane.showConfirmDialog(null,"download "+ urlString ) this.id =id; this.jid = jid; this.backend = backend; try { jbInit(); JIDStatus j = Roster.getJIDStatus(jid); if(j!=null)jTextArea1.setText(j.getNick()); else jTextArea1.setText(jid.toString()); //jTextField1.setText(url.toString()); } catch(Exception e) { e.printStackTrace(); } pack(); draadje = new Draadje(this); draadje.start(); addData(ibb.getData()); } private void jbInit() throws Exception { setIconImage(nu.fw.jeti.images.StatusIcons.getImageIcon("jeti").getImage()); getRootPane().setDefaultButton(btnDownload); jLabel1.setPreferredSize(new Dimension(300, 17)); //jLabel1.setText(I18N.gettext("Description")); I18N.setTextAndMnemonic("filetransfer.Description",jLabel1); jTextArea1.setAlignmentX((float) 0.0); jTextArea1.setPreferredSize(new Dimension(300, 17)); jTextArea1.setEditable(false); jLabel2.setPreferredSize(new Dimension(300, 17)); I18N.setTextAndMnemonic("filetransfer.URL",jLabel2); jTextField1.setAlignmentX((float) 0.0); jTextField1.setPreferredSize(new Dimension(300, 21)); jTextField1.setEditable(false); //btnGetSize.setMnemonic('G'); //btnGetSize.setText(I18N.gettext("GetSize")); I18N.setTextAndMnemonic("filetransfer.GetSize",btnGetSize); btnGetSize.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { btnGetSize_actionPerformed(e); } }); //btnDownload.setMnemonic('D'); btnDownload.setText(I18N.gettext("filetransfer.Download")); getRootPane().setDefaultButton(btnDownload); btnDownload.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { btnDownload_actionPerformed(e); } }); //btnCancel.setMnemonic('C'); //btnCancel.setText(I18N.gettext("Cancel")); Action cancelAction = new AbstractAction(I18N.gettext("Cancel")) { public void actionPerformed(ActionEvent e) { btnCancel_actionPerformed(e); } }; btnCancel.setAction(cancelAction); KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); JLayeredPane layeredPane = getLayeredPane(); layeredPane.getActionMap().put("cancel", cancelAction); layeredPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "cancel"); this.setTitle(I18N.gettext("filetransfer.File_Transfer")); jPanel2.setAlignmentX((float) 0.0); jPanel3.setAlignmentX((float) 0.0); jProgressBar1.setAlignmentX((float) 0.0); lblDownload.setToolTipText(""); this.getContentPane().add(jPanel1, BorderLayout.CENTER); jPanel1.setLayout(new BoxLayout(jPanel1,BoxLayout.Y_AXIS)); jPanel1.add(jLabel1, null); jPanel1.add(jTextArea1, null); jPanel1.add(jLabel2, null); jPanel1.add(jTextField1, null); jPanel1.add(jPanel2, null); jPanel2.add(btnGetSize, null); jPanel2.add(lblDownload, null); jPanel1.add(jProgressBar1, null); jPanel1.add(jPanel3, null); jPanel3.add(btnDownload, null); jPanel3.add(btnCancel, null); } void btnGetSize_actionPerformed(ActionEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Thread t = new Thread() { public void run() { //if(connection == null) HttpURLConnection connection = null; { try { connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("HEAD"); //connection.setRequestMethod() } catch (IOException e2) { dispose(); Popups.errorPopup(url.toExternalForm() + " could not be reached","File transfer"); return; } } /* try{ ((HttpURLConnection)connection).setRequestMethod("HEAD"); } catch(ProtocolException e2){e2.printStackTrace();} */ length = connection.getContentLength()/1024; Runnable updateAComponent = new Runnable() { public void run(){ lblDownload.setText(length + " kB " + length / 1024 + " MB"); setCursor(Cursor.getDefaultCursor()); }}; SwingUtilities.invokeLater(updateAComponent); } }; t.start(); } void btnDownload_actionPerformed(ActionEvent e) { //final GetFileWindow w = this; draadje = new Draadje(this); draadje.start(); } void btnCancel_actionPerformed(ActionEvent e) { if(draadje !=null) { draadje.interrupt(); } //backend.sendError("406","Not Acceptable",jid,id); //backend.send(new InfoQuery(to,error ) ) // InfoQueryBuilder iqb = new InfoQueryBuilder(); // iqb.setErrorCode(406); // iqb.setErrorDescription("Not Acceptable"); // iqb.setId(id); // iqb.setTo(jid); // iqb.setType("error"); // backend.send(iqb.build()); backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406)); dispose(); } public void addData(String data) { System.out.println("data added"); draadje.addData(data); } public void stopDownloading() { draadje.stopDownloading(); System.out.println("download complete"); } class Draadje extends Thread { private GetFileWindow getFileWindow; private int bytes=0; private LinkedList queue = new LinkedList(); private volatile boolean isDownloading=true; Draadje(GetFileWindow w) { getFileWindow =w; } public void addData(String data) { synchronized(queue) { queue.addLast(data); queue.notifyAll(); } } public void stopDownloading() { isDownloading = false; synchronized(queue){queue.notifyAll();} } public void run() { JFileChooser fileChooser = new JFileChooser(); int s = fileChooser.showSaveDialog(getFileWindow); if(s != JFileChooser.APPROVE_OPTION) return; //cancel //check if enough space on hd btnDownload.setEnabled(false); btnGetSize.setVisible(false); btnCancel.setText("Abort"); btnCancel.setMnemonic('a'); BufferedOutputStream out=null; try{ try{ out = new BufferedOutputStream (new FileOutputStream(fileChooser.getSelectedFile())); }catch(FileNotFoundException e2) { Popups.errorPopup(fileChooser.getSelectedFile().getAbsolutePath() + " could not be openend in write mode","File transfer"); } if(out!=null) { try{ while(!queue.isEmpty() || isDownloading) { String base64Data; synchronized(queue) { if (queue.isEmpty()) { try { System.out.println("waiting"); queue.wait(); } catch(InterruptedException e) {//bug when thrown? called when interrupted e.printStackTrace(); return; } continue; } base64Data = (String)queue.removeFirst(); System.out.println("data read"); } //System.out.println(base64Data); //System.out.println(Base64.decode2(base64Data)); byte[] data = Base64.decode(base64Data); System.out.println("data converted"); out.write(data, 0, data.length); System.out.println("data written"); //bytes++; if (Thread.interrupted()) throw new InterruptedException(); //yield(); } //download ok //backend.send(new InfoQuery(jid,"result",id,null)); }catch (IOException e2) //te weinig schijruimte { Popups.errorPopup(e2.getMessage() + " while downloading " + url.toExternalForm(),"File transfer"); //download not ok backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406)); } } dispose(); System.out.println("downloaded"); }catch (InterruptedException e3) {} try { if(out!=null)out.close(); }catch (IOException e2){} } } } /* * Overrides for emacs * Local variables: * tab-width: 4 * End: */
youngdev/experiment
JETL/nu/fw/jeti/plugins/ibb/GetFileWindow.java
3,528
//te weinig schijruimte
line_comment
nl
package nu.fw.jeti.plugins.ibb; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.LinkedList; import javax.swing.*; import nu.fw.jeti.backend.roster.Roster; import nu.fw.jeti.jabber.Backend; import nu.fw.jeti.jabber.JID; import nu.fw.jeti.jabber.JIDStatus; import nu.fw.jeti.jabber.elements.InfoQuery; import nu.fw.jeti.util.Base64; import nu.fw.jeti.util.I18N; import nu.fw.jeti.util.Popups; /** * <p>Title: im</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2001</p> * <p>Company: </p> * @author E.S. de Boer * @version 1.0 */ //TODO translate filetransfer warnings, or wait for socks filetransfer? public class GetFileWindow extends JFrame { private JPanel jPanel1 = new JPanel(); private JLabel jLabel1 = new JLabel(); private JTextArea jTextArea1 = new JTextArea(); private JLabel jLabel2 = new JLabel(); private JTextField jTextField1 = new JTextField(); private JPanel jPanel2 = new JPanel(); private JButton btnGetSize = new JButton(); private JPanel jPanel3 = new JPanel(); private JButton btnDownload = new JButton(); private JButton btnCancel = new JButton(); private URL url; private JProgressBar jProgressBar1 = new JProgressBar(); private String id; private JID jid; private Backend backend; //private URLConnection connection = null; private int length; private Draadje draadje; private JLabel lblDownload = new JLabel(); public GetFileWindow(JID jid,Backend backend, IBBExtension ibb) { //JOptionPane.showConfirmDialog(null,"download "+ urlString ) this.id =id; this.jid = jid; this.backend = backend; try { jbInit(); JIDStatus j = Roster.getJIDStatus(jid); if(j!=null)jTextArea1.setText(j.getNick()); else jTextArea1.setText(jid.toString()); //jTextField1.setText(url.toString()); } catch(Exception e) { e.printStackTrace(); } pack(); draadje = new Draadje(this); draadje.start(); addData(ibb.getData()); } private void jbInit() throws Exception { setIconImage(nu.fw.jeti.images.StatusIcons.getImageIcon("jeti").getImage()); getRootPane().setDefaultButton(btnDownload); jLabel1.setPreferredSize(new Dimension(300, 17)); //jLabel1.setText(I18N.gettext("Description")); I18N.setTextAndMnemonic("filetransfer.Description",jLabel1); jTextArea1.setAlignmentX((float) 0.0); jTextArea1.setPreferredSize(new Dimension(300, 17)); jTextArea1.setEditable(false); jLabel2.setPreferredSize(new Dimension(300, 17)); I18N.setTextAndMnemonic("filetransfer.URL",jLabel2); jTextField1.setAlignmentX((float) 0.0); jTextField1.setPreferredSize(new Dimension(300, 21)); jTextField1.setEditable(false); //btnGetSize.setMnemonic('G'); //btnGetSize.setText(I18N.gettext("GetSize")); I18N.setTextAndMnemonic("filetransfer.GetSize",btnGetSize); btnGetSize.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { btnGetSize_actionPerformed(e); } }); //btnDownload.setMnemonic('D'); btnDownload.setText(I18N.gettext("filetransfer.Download")); getRootPane().setDefaultButton(btnDownload); btnDownload.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { btnDownload_actionPerformed(e); } }); //btnCancel.setMnemonic('C'); //btnCancel.setText(I18N.gettext("Cancel")); Action cancelAction = new AbstractAction(I18N.gettext("Cancel")) { public void actionPerformed(ActionEvent e) { btnCancel_actionPerformed(e); } }; btnCancel.setAction(cancelAction); KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); JLayeredPane layeredPane = getLayeredPane(); layeredPane.getActionMap().put("cancel", cancelAction); layeredPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "cancel"); this.setTitle(I18N.gettext("filetransfer.File_Transfer")); jPanel2.setAlignmentX((float) 0.0); jPanel3.setAlignmentX((float) 0.0); jProgressBar1.setAlignmentX((float) 0.0); lblDownload.setToolTipText(""); this.getContentPane().add(jPanel1, BorderLayout.CENTER); jPanel1.setLayout(new BoxLayout(jPanel1,BoxLayout.Y_AXIS)); jPanel1.add(jLabel1, null); jPanel1.add(jTextArea1, null); jPanel1.add(jLabel2, null); jPanel1.add(jTextField1, null); jPanel1.add(jPanel2, null); jPanel2.add(btnGetSize, null); jPanel2.add(lblDownload, null); jPanel1.add(jProgressBar1, null); jPanel1.add(jPanel3, null); jPanel3.add(btnDownload, null); jPanel3.add(btnCancel, null); } void btnGetSize_actionPerformed(ActionEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Thread t = new Thread() { public void run() { //if(connection == null) HttpURLConnection connection = null; { try { connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("HEAD"); //connection.setRequestMethod() } catch (IOException e2) { dispose(); Popups.errorPopup(url.toExternalForm() + " could not be reached","File transfer"); return; } } /* try{ ((HttpURLConnection)connection).setRequestMethod("HEAD"); } catch(ProtocolException e2){e2.printStackTrace();} */ length = connection.getContentLength()/1024; Runnable updateAComponent = new Runnable() { public void run(){ lblDownload.setText(length + " kB " + length / 1024 + " MB"); setCursor(Cursor.getDefaultCursor()); }}; SwingUtilities.invokeLater(updateAComponent); } }; t.start(); } void btnDownload_actionPerformed(ActionEvent e) { //final GetFileWindow w = this; draadje = new Draadje(this); draadje.start(); } void btnCancel_actionPerformed(ActionEvent e) { if(draadje !=null) { draadje.interrupt(); } //backend.sendError("406","Not Acceptable",jid,id); //backend.send(new InfoQuery(to,error ) ) // InfoQueryBuilder iqb = new InfoQueryBuilder(); // iqb.setErrorCode(406); // iqb.setErrorDescription("Not Acceptable"); // iqb.setId(id); // iqb.setTo(jid); // iqb.setType("error"); // backend.send(iqb.build()); backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406)); dispose(); } public void addData(String data) { System.out.println("data added"); draadje.addData(data); } public void stopDownloading() { draadje.stopDownloading(); System.out.println("download complete"); } class Draadje extends Thread { private GetFileWindow getFileWindow; private int bytes=0; private LinkedList queue = new LinkedList(); private volatile boolean isDownloading=true; Draadje(GetFileWindow w) { getFileWindow =w; } public void addData(String data) { synchronized(queue) { queue.addLast(data); queue.notifyAll(); } } public void stopDownloading() { isDownloading = false; synchronized(queue){queue.notifyAll();} } public void run() { JFileChooser fileChooser = new JFileChooser(); int s = fileChooser.showSaveDialog(getFileWindow); if(s != JFileChooser.APPROVE_OPTION) return; //cancel //check if enough space on hd btnDownload.setEnabled(false); btnGetSize.setVisible(false); btnCancel.setText("Abort"); btnCancel.setMnemonic('a'); BufferedOutputStream out=null; try{ try{ out = new BufferedOutputStream (new FileOutputStream(fileChooser.getSelectedFile())); }catch(FileNotFoundException e2) { Popups.errorPopup(fileChooser.getSelectedFile().getAbsolutePath() + " could not be openend in write mode","File transfer"); } if(out!=null) { try{ while(!queue.isEmpty() || isDownloading) { String base64Data; synchronized(queue) { if (queue.isEmpty()) { try { System.out.println("waiting"); queue.wait(); } catch(InterruptedException e) {//bug when thrown? called when interrupted e.printStackTrace(); return; } continue; } base64Data = (String)queue.removeFirst(); System.out.println("data read"); } //System.out.println(base64Data); //System.out.println(Base64.decode2(base64Data)); byte[] data = Base64.decode(base64Data); System.out.println("data converted"); out.write(data, 0, data.length); System.out.println("data written"); //bytes++; if (Thread.interrupted()) throw new InterruptedException(); //yield(); } //download ok //backend.send(new InfoQuery(jid,"result",id,null)); }catch (IOException e2) //te weinig<SUF> { Popups.errorPopup(e2.getMessage() + " while downloading " + url.toExternalForm(),"File transfer"); //download not ok backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406)); } } dispose(); System.out.println("downloaded"); }catch (InterruptedException e3) {} try { if(out!=null)out.close(); }catch (IOException e2){} } } } /* * Overrides for emacs * Local variables: * tab-width: 4 * End: */
75400_9
package tech.ypsilon.bbbot.discord.command; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.events.interaction.ButtonClickEvent; import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent; import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.components.Button; import tech.ypsilon.bbbot.ButterBrot; import tech.ypsilon.bbbot.config.ProfileSubconfig; import tech.ypsilon.bbbot.util.ActionRowUtil; import tech.ypsilon.bbbot.util.EmbedUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; public class ProfileCommand extends SlashCommand { public static final String BTN_DATA_CREATE_MENU = "createProfileSelectionMenu"; public static final String BTN_DATA_CREATE_YEAR = "createYearSelectionMenu"; public static final String BTN_DATA_CREATE_DEGREE = "createTypeSelectionMenu"; public static final String BTN_DATA_PRODUCTIVE = "productiveRoleToggle"; private static final String BTN_DATA_RETURN_MAIN = "returnToProfilSelectionMenu"; private static final String CUSTOM_DELIMITER = "_"; private static final String BTN_DATA_CATEGORY_PREFIX = "courseCategory"; private static final String BTN_DATA_COURSE_PREFIX = "course"; private static final String BTN_DATA_DEGREE_PREFIX = "degree"; private static final String BTN_DATA_YEAR_PREFIX = "year"; private final Map<Long, String> roleIdCourseIdMap; private final Map<String, Role> courseRoleMap; private final Role productivityRole; public ProfileCommand(ButterBrot parent) { super(parent); roleIdCourseIdMap = new ConcurrentHashMap<>(); fillCourseMap(); courseRoleMap = new ConcurrentHashMap<>(); fillRoleMap(); productivityRole = parent.getDiscordController().getHome() .getRoleById(parent.getConfig().getProfile().getProductiveRoleId()); } private void fillCourseMap() { getParent().getConfig().getProfile().getCourseCategories().forEach((categoryId, category) -> // for all categories category.getCourses().forEach((courseId, course) -> // for each course in category roleIdCourseIdMap.put(course.getDiscordRoleId(), categoryId + CUSTOM_DELIMITER + courseId) // add category to map ) ); } private void fillRoleMap() { getParent().getConfig().getProfile().getCourseCategories().forEach((categoryId, category) -> // for all categories category.getCourses().forEach((courseId, course) -> // for each course in category courseRoleMap.put( courseId, getParent().getDiscordController().getHome().getRoleById(course.getDiscordRoleId()) ) ) ); } /** * JDA Command Data information used to register * and search commands. * * @return command data */ @Override public CommandData commandData() { return new CommandData("profile", "Bearbeite dein Server-Rollen-Profil"); } /** * Execute is called by the onSlashCommand event when * this command should be executed * * @param event original event */ @Override public void execute(SlashCommandEvent event) { createMenu(event); } @Override public void handleButtonInteraction(ButtonClickEvent event, String data) { if (data == null || data.isBlank() || event.getMember() == null) { event.getInteraction().replyEmbeds(EmbedUtil.createErrorEmbed().build()).setEphemeral(true).queue(); return; } switch (data.split(CUSTOM_DELIMITER)[0]) { case BTN_DATA_CREATE_MENU: // initial button clicked createMenu(event); break; case BTN_DATA_RETURN_MAIN: // return to main menu event.editMessage(createMainMenu(event.getMember())).queue(); break; case BTN_DATA_CREATE_DEGREE: // open degree menu event.reply(createExpectedDegreeMenu(event.getMember())).setEphemeral(true).queue(); break; case BTN_DATA_CREATE_YEAR: event.reply(createStartYearMenu(event.getMember())).setEphemeral(true).queue(); break; case BTN_DATA_PRODUCTIVE: handleProductivityToggle(event); break; case BTN_DATA_CATEGORY_PREFIX: // category selected String category = data.replaceFirst(BTN_DATA_CATEGORY_PREFIX, "") .replace(CUSTOM_DELIMITER, ""); event.editMessage(createCategoryMenu(event.getMember(), category)).queue(); break; case BTN_DATA_COURSE_PREFIX: // course clicked handleCourseButton(event, data); break; case BTN_DATA_DEGREE_PREFIX: // degree button clicked handleSingleRoleButtonList(event, data, getParent().getConfig().getProfile().getDegreeRoles(), this::createExpectedDegreeMenu); break; case BTN_DATA_YEAR_PREFIX: // year button clicked handleSingleRoleButtonList(event, data, getParent().getConfig().getProfile().getYearRoles(), this::createStartYearMenu); break; default: event.reply("Action not found, please report this Error!").setEphemeral(true).queue(); break; } } private void handleProductivityToggle(ButtonClickEvent event) { Member member = Objects.requireNonNull(event.getMember()); Guild guild = Objects.requireNonNull(event.getGuild()); if (member.getRoles().contains(productivityRole)) { guild.removeRoleFromMember(member, productivityRole).queue(); event.reply("Freizeit-Kanäle werden wieder angezeigt.").setEphemeral(true).queue(); } else { guild.addRoleToMember(member, productivityRole).queue(); event.reply("Freizeit-Kanäle werden **nicht** angezeigt.").setEphemeral(true).queue(); } } private void handleCourseButton(ButtonClickEvent event, String data) { Member member = Objects.requireNonNull(event.getMember()); Guild guild = Objects.requireNonNull(event.getGuild()); event.deferEdit().queue(); // role selected to add/remove String categoryCourseIDs = data.replaceFirst(BTN_DATA_COURSE_PREFIX + CUSTOM_DELIMITER, ""); // This is to avoid cache problems, the Member#getRoles() List is not always up to date! List<Role> roles = new ArrayList<>(member.getRoles()); // add or remove role Role role = courseRoleMap.get(categoryCourseIDs.split(CUSTOM_DELIMITER)[1]); if (event.getMember().getRoles().contains(role)) { guild.removeRoleFromMember(event.getMember(), role).queue(); roles.remove(role); } else { guild.addRoleToMember(event.getMember(), role).queue(); roles.add(role); } event.getHook().editOriginal(createCategoryMenu(categoryCourseIDs.split(CUSTOM_DELIMITER)[0], roles)).queue(); } private void handleSingleRoleButtonList(ButtonClickEvent event, String data, List<ProfileSubconfig.NameEmojiRole> selectionList, Function<List<Role>, Message> messageSupplier) { Guild guild = Objects.requireNonNull(event.getGuild()); Member member = Objects.requireNonNull(event.getMember()); event.deferEdit().queue(); String roleId = data.split(CUSTOM_DELIMITER)[1]; Role selectedRole = Objects.requireNonNull(guild.getRoleById(roleId)); List<Role> copyRoleList = new ArrayList<>(member.getRoles()); if (member.getRoles().contains(selectedRole)) { guild.removeRoleFromMember(member, selectedRole).queue(); copyRoleList.remove(selectedRole); } else { for (Role memberRole : member.getRoles()) { for (ProfileSubconfig.NameEmojiRole degree : selectionList) { if (degree.getDiscordRoleId() == memberRole.getIdLong()) { // remove other roles Role otherDegreeRole = Objects.requireNonNull(guild.getRoleById(degree.getDiscordRoleId())); guild.removeRoleFromMember(member, otherDegreeRole).queue(); copyRoleList.remove(otherDegreeRole); } } } guild.addRoleToMember(member, selectedRole).queue(); copyRoleList.add(selectedRole); } event.getHook().editOriginal(messageSupplier.apply(copyRoleList)).queue(); } private void createMenu(GenericInteractionCreateEvent event) { if (event.getMember() == null) { return; } event.deferReply().setEphemeral(true).queue(); event.getHook().editOriginal(createMainMenu(event.getMember())).queue(); } @Override public void handleSelectionMenu(SelectionMenuEvent event, String data) { super.handleSelectionMenu(event, data); } /** * Returns a string to be displayed in the help-command * * @return the help-string */ @Override public String getHelpDescription() { return "Mit diesem Befehl kann das Menü zur Rollenauswahl angezeigt werden"; } private Message createMainMenu(Member initiator) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du deinen Studiengang bearbeiten!\n") .append("Um einen Studiengang hinzuzufügen oder zu entfernen, klicke auf eine der Kategorien.\n\n") .append("__Aktuell ausgewählte Studiengänge:__\n"); Set<String> selectedCategories = new HashSet<>(); // Set<String> selectedCourses = new HashSet<>(); for (Role role : initiator.getRoles()) { if (roleIdCourseIdMap.containsKey(role.getIdLong())) { String categoryCourseId = roleIdCourseIdMap.get(role.getIdLong()); String courseName = getParent().getConfig().getProfile().getCourseCategories() .get(categoryCourseId.split(CUSTOM_DELIMITER)[0]).getCourses() .get(categoryCourseId.split(CUSTOM_DELIMITER)[1]).getName(); messageBuilder.append("- ").append(courseName).append("\n"); selectedCategories.add(categoryCourseId.split(CUSTOM_DELIMITER)[0]); // selectedCourses.add(categoryCourseId.split(CUSTOM_DELIMITER)[1]); } } messageBuilder.append("\nKlicke einen Knopf um dir die Rolle zuzuweisen."); List<Button> categoryButtons = getParent().getConfig().getProfile() .getCourseCategories() .entrySet() .stream() .map(entry -> { if (selectedCategories.contains(entry.getKey())) { return Button.success( createButtonId(BTN_DATA_CATEGORY_PREFIX + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } else { return Button.primary( createButtonId(BTN_DATA_CATEGORY_PREFIX + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } }).collect(Collectors.toList()); messageBuilder.setActionRows(ActionRowUtil.fillButtons(categoryButtons)); return messageBuilder.build(); } private Message createCategoryMenu(Member initiator, String categoryId) { return createCategoryMenu(categoryId, initiator.getRoles()); } private Message createCategoryMenu(String categoryId, List<Role> roleList) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du dein Menü bearbeiten!\n") .append("Um einen Studiengang hinzuzufügen oder zu entfernen, klicke auf eine der Kategorien.\n\n") .append("__Aktuell ausgewählte Studiengänge:__\n"); // Set<String> selectedCategories = new HashSet<>(); Set<String> selectedCourses = new HashSet<>(); for (Role role : roleList) { if (roleIdCourseIdMap.containsKey(role.getIdLong())) { String categoryCourseId = roleIdCourseIdMap.get(role.getIdLong()); String courseName = getParent().getConfig().getProfile().getCourseCategories() .get(categoryCourseId.split(CUSTOM_DELIMITER)[0]).getCourses() .get(categoryCourseId.split(CUSTOM_DELIMITER)[1]).getName(); messageBuilder.append("- ").append(courseName).append("\n"); // selectedCategories.add(categoryCourseId.split(CUSTOM_DELIMITER)[0]); selectedCourses.add(categoryCourseId.split(CUSTOM_DELIMITER)[1]); } } messageBuilder.append("\nKlicke einen Knopf um dir die Rolle zuzuweisen."); List<Button> categoryButtons = getParent().getConfig().getProfile() .getCourseCategories() .get(categoryId) .getCourses() .entrySet() .stream() .map(entry -> { if (selectedCourses.contains(entry.getKey())) { return Button.success( createButtonId(BTN_DATA_COURSE_PREFIX + CUSTOM_DELIMITER + categoryId + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } else { return Button.primary( createButtonId(BTN_DATA_COURSE_PREFIX + CUSTOM_DELIMITER + categoryId + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } }).collect(Collectors.toList()); categoryButtons.add(Button.danger(createButtonId(BTN_DATA_RETURN_MAIN), "\uD83D\uDD19 Zurück")); messageBuilder.setActionRows(ActionRowUtil.fillButtons(categoryButtons)); return messageBuilder.build(); } private Message createExpectedDegreeMenu(Member initiator) { return createExpectedDegreeMenu(initiator.getRoles()); } private Message createExpectedDegreeMenu(List<Role> roleList) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du auswählen welchen Abschluss ") .append("du aktuell anstrebst. Du kannst maximal eine Rolle auswählen."); List<Button> buttonList = new ArrayList<>(); for (ProfileSubconfig.NameEmojiRole degreeRole : getParent().getConfig().getProfile().getDegreeRoles()) { buildSingleSelectButtons(roleList, buttonList, degreeRole, BTN_DATA_DEGREE_PREFIX); } messageBuilder.setActionRows(ActionRowUtil.fillButtons(buttonList)); return messageBuilder.build(); } private Message createStartYearMenu(Member initiator) { return createStartYearMenu(initiator.getRoles()); } private Message createStartYearMenu(List<Role> roleList) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du auswählen wann du dein Studium ") .append("begonnen hast. Du kannst maximal eine Rolle auswählen."); List<Button> buttonList = new ArrayList<>(); for (ProfileSubconfig.NameEmojiRole degreeRole : getParent().getConfig().getProfile().getYearRoles()) { buildSingleSelectButtons(roleList, buttonList, degreeRole, BTN_DATA_YEAR_PREFIX); } messageBuilder.setActionRows(ActionRowUtil.fillButtons(buttonList)); return messageBuilder.build(); } /** * Generated from IntelliJ "extract from duplicates" feature */ private void buildSingleSelectButtons(List<Role> roleList, List<Button> buttonList, ProfileSubconfig.NameEmojiRole degreeRole, String dataPrefix) { if (roleList.stream().anyMatch(role -> role.getIdLong() == degreeRole.getDiscordRoleId())) { buttonList.add(Button.success( createButtonId(dataPrefix + CUSTOM_DELIMITER + degreeRole.getDiscordRoleId()), degreeRole.getUnicodeEmoji() + " " + degreeRole.getName() )); } else { buttonList.add(Button.primary( createButtonId(dataPrefix + CUSTOM_DELIMITER + degreeRole.getDiscordRoleId()), degreeRole.getUnicodeEmoji() + " " + degreeRole.getName() )); } } }
ypsilondev/butterbrotbot
src/main/java/tech/ypsilon/bbbot/discord/command/ProfileCommand.java
4,900
// open degree menu
line_comment
nl
package tech.ypsilon.bbbot.discord.command; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.events.interaction.ButtonClickEvent; import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent; import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.components.Button; import tech.ypsilon.bbbot.ButterBrot; import tech.ypsilon.bbbot.config.ProfileSubconfig; import tech.ypsilon.bbbot.util.ActionRowUtil; import tech.ypsilon.bbbot.util.EmbedUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; public class ProfileCommand extends SlashCommand { public static final String BTN_DATA_CREATE_MENU = "createProfileSelectionMenu"; public static final String BTN_DATA_CREATE_YEAR = "createYearSelectionMenu"; public static final String BTN_DATA_CREATE_DEGREE = "createTypeSelectionMenu"; public static final String BTN_DATA_PRODUCTIVE = "productiveRoleToggle"; private static final String BTN_DATA_RETURN_MAIN = "returnToProfilSelectionMenu"; private static final String CUSTOM_DELIMITER = "_"; private static final String BTN_DATA_CATEGORY_PREFIX = "courseCategory"; private static final String BTN_DATA_COURSE_PREFIX = "course"; private static final String BTN_DATA_DEGREE_PREFIX = "degree"; private static final String BTN_DATA_YEAR_PREFIX = "year"; private final Map<Long, String> roleIdCourseIdMap; private final Map<String, Role> courseRoleMap; private final Role productivityRole; public ProfileCommand(ButterBrot parent) { super(parent); roleIdCourseIdMap = new ConcurrentHashMap<>(); fillCourseMap(); courseRoleMap = new ConcurrentHashMap<>(); fillRoleMap(); productivityRole = parent.getDiscordController().getHome() .getRoleById(parent.getConfig().getProfile().getProductiveRoleId()); } private void fillCourseMap() { getParent().getConfig().getProfile().getCourseCategories().forEach((categoryId, category) -> // for all categories category.getCourses().forEach((courseId, course) -> // for each course in category roleIdCourseIdMap.put(course.getDiscordRoleId(), categoryId + CUSTOM_DELIMITER + courseId) // add category to map ) ); } private void fillRoleMap() { getParent().getConfig().getProfile().getCourseCategories().forEach((categoryId, category) -> // for all categories category.getCourses().forEach((courseId, course) -> // for each course in category courseRoleMap.put( courseId, getParent().getDiscordController().getHome().getRoleById(course.getDiscordRoleId()) ) ) ); } /** * JDA Command Data information used to register * and search commands. * * @return command data */ @Override public CommandData commandData() { return new CommandData("profile", "Bearbeite dein Server-Rollen-Profil"); } /** * Execute is called by the onSlashCommand event when * this command should be executed * * @param event original event */ @Override public void execute(SlashCommandEvent event) { createMenu(event); } @Override public void handleButtonInteraction(ButtonClickEvent event, String data) { if (data == null || data.isBlank() || event.getMember() == null) { event.getInteraction().replyEmbeds(EmbedUtil.createErrorEmbed().build()).setEphemeral(true).queue(); return; } switch (data.split(CUSTOM_DELIMITER)[0]) { case BTN_DATA_CREATE_MENU: // initial button clicked createMenu(event); break; case BTN_DATA_RETURN_MAIN: // return to main menu event.editMessage(createMainMenu(event.getMember())).queue(); break; case BTN_DATA_CREATE_DEGREE: // open degree<SUF> event.reply(createExpectedDegreeMenu(event.getMember())).setEphemeral(true).queue(); break; case BTN_DATA_CREATE_YEAR: event.reply(createStartYearMenu(event.getMember())).setEphemeral(true).queue(); break; case BTN_DATA_PRODUCTIVE: handleProductivityToggle(event); break; case BTN_DATA_CATEGORY_PREFIX: // category selected String category = data.replaceFirst(BTN_DATA_CATEGORY_PREFIX, "") .replace(CUSTOM_DELIMITER, ""); event.editMessage(createCategoryMenu(event.getMember(), category)).queue(); break; case BTN_DATA_COURSE_PREFIX: // course clicked handleCourseButton(event, data); break; case BTN_DATA_DEGREE_PREFIX: // degree button clicked handleSingleRoleButtonList(event, data, getParent().getConfig().getProfile().getDegreeRoles(), this::createExpectedDegreeMenu); break; case BTN_DATA_YEAR_PREFIX: // year button clicked handleSingleRoleButtonList(event, data, getParent().getConfig().getProfile().getYearRoles(), this::createStartYearMenu); break; default: event.reply("Action not found, please report this Error!").setEphemeral(true).queue(); break; } } private void handleProductivityToggle(ButtonClickEvent event) { Member member = Objects.requireNonNull(event.getMember()); Guild guild = Objects.requireNonNull(event.getGuild()); if (member.getRoles().contains(productivityRole)) { guild.removeRoleFromMember(member, productivityRole).queue(); event.reply("Freizeit-Kanäle werden wieder angezeigt.").setEphemeral(true).queue(); } else { guild.addRoleToMember(member, productivityRole).queue(); event.reply("Freizeit-Kanäle werden **nicht** angezeigt.").setEphemeral(true).queue(); } } private void handleCourseButton(ButtonClickEvent event, String data) { Member member = Objects.requireNonNull(event.getMember()); Guild guild = Objects.requireNonNull(event.getGuild()); event.deferEdit().queue(); // role selected to add/remove String categoryCourseIDs = data.replaceFirst(BTN_DATA_COURSE_PREFIX + CUSTOM_DELIMITER, ""); // This is to avoid cache problems, the Member#getRoles() List is not always up to date! List<Role> roles = new ArrayList<>(member.getRoles()); // add or remove role Role role = courseRoleMap.get(categoryCourseIDs.split(CUSTOM_DELIMITER)[1]); if (event.getMember().getRoles().contains(role)) { guild.removeRoleFromMember(event.getMember(), role).queue(); roles.remove(role); } else { guild.addRoleToMember(event.getMember(), role).queue(); roles.add(role); } event.getHook().editOriginal(createCategoryMenu(categoryCourseIDs.split(CUSTOM_DELIMITER)[0], roles)).queue(); } private void handleSingleRoleButtonList(ButtonClickEvent event, String data, List<ProfileSubconfig.NameEmojiRole> selectionList, Function<List<Role>, Message> messageSupplier) { Guild guild = Objects.requireNonNull(event.getGuild()); Member member = Objects.requireNonNull(event.getMember()); event.deferEdit().queue(); String roleId = data.split(CUSTOM_DELIMITER)[1]; Role selectedRole = Objects.requireNonNull(guild.getRoleById(roleId)); List<Role> copyRoleList = new ArrayList<>(member.getRoles()); if (member.getRoles().contains(selectedRole)) { guild.removeRoleFromMember(member, selectedRole).queue(); copyRoleList.remove(selectedRole); } else { for (Role memberRole : member.getRoles()) { for (ProfileSubconfig.NameEmojiRole degree : selectionList) { if (degree.getDiscordRoleId() == memberRole.getIdLong()) { // remove other roles Role otherDegreeRole = Objects.requireNonNull(guild.getRoleById(degree.getDiscordRoleId())); guild.removeRoleFromMember(member, otherDegreeRole).queue(); copyRoleList.remove(otherDegreeRole); } } } guild.addRoleToMember(member, selectedRole).queue(); copyRoleList.add(selectedRole); } event.getHook().editOriginal(messageSupplier.apply(copyRoleList)).queue(); } private void createMenu(GenericInteractionCreateEvent event) { if (event.getMember() == null) { return; } event.deferReply().setEphemeral(true).queue(); event.getHook().editOriginal(createMainMenu(event.getMember())).queue(); } @Override public void handleSelectionMenu(SelectionMenuEvent event, String data) { super.handleSelectionMenu(event, data); } /** * Returns a string to be displayed in the help-command * * @return the help-string */ @Override public String getHelpDescription() { return "Mit diesem Befehl kann das Menü zur Rollenauswahl angezeigt werden"; } private Message createMainMenu(Member initiator) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du deinen Studiengang bearbeiten!\n") .append("Um einen Studiengang hinzuzufügen oder zu entfernen, klicke auf eine der Kategorien.\n\n") .append("__Aktuell ausgewählte Studiengänge:__\n"); Set<String> selectedCategories = new HashSet<>(); // Set<String> selectedCourses = new HashSet<>(); for (Role role : initiator.getRoles()) { if (roleIdCourseIdMap.containsKey(role.getIdLong())) { String categoryCourseId = roleIdCourseIdMap.get(role.getIdLong()); String courseName = getParent().getConfig().getProfile().getCourseCategories() .get(categoryCourseId.split(CUSTOM_DELIMITER)[0]).getCourses() .get(categoryCourseId.split(CUSTOM_DELIMITER)[1]).getName(); messageBuilder.append("- ").append(courseName).append("\n"); selectedCategories.add(categoryCourseId.split(CUSTOM_DELIMITER)[0]); // selectedCourses.add(categoryCourseId.split(CUSTOM_DELIMITER)[1]); } } messageBuilder.append("\nKlicke einen Knopf um dir die Rolle zuzuweisen."); List<Button> categoryButtons = getParent().getConfig().getProfile() .getCourseCategories() .entrySet() .stream() .map(entry -> { if (selectedCategories.contains(entry.getKey())) { return Button.success( createButtonId(BTN_DATA_CATEGORY_PREFIX + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } else { return Button.primary( createButtonId(BTN_DATA_CATEGORY_PREFIX + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } }).collect(Collectors.toList()); messageBuilder.setActionRows(ActionRowUtil.fillButtons(categoryButtons)); return messageBuilder.build(); } private Message createCategoryMenu(Member initiator, String categoryId) { return createCategoryMenu(categoryId, initiator.getRoles()); } private Message createCategoryMenu(String categoryId, List<Role> roleList) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du dein Menü bearbeiten!\n") .append("Um einen Studiengang hinzuzufügen oder zu entfernen, klicke auf eine der Kategorien.\n\n") .append("__Aktuell ausgewählte Studiengänge:__\n"); // Set<String> selectedCategories = new HashSet<>(); Set<String> selectedCourses = new HashSet<>(); for (Role role : roleList) { if (roleIdCourseIdMap.containsKey(role.getIdLong())) { String categoryCourseId = roleIdCourseIdMap.get(role.getIdLong()); String courseName = getParent().getConfig().getProfile().getCourseCategories() .get(categoryCourseId.split(CUSTOM_DELIMITER)[0]).getCourses() .get(categoryCourseId.split(CUSTOM_DELIMITER)[1]).getName(); messageBuilder.append("- ").append(courseName).append("\n"); // selectedCategories.add(categoryCourseId.split(CUSTOM_DELIMITER)[0]); selectedCourses.add(categoryCourseId.split(CUSTOM_DELIMITER)[1]); } } messageBuilder.append("\nKlicke einen Knopf um dir die Rolle zuzuweisen."); List<Button> categoryButtons = getParent().getConfig().getProfile() .getCourseCategories() .get(categoryId) .getCourses() .entrySet() .stream() .map(entry -> { if (selectedCourses.contains(entry.getKey())) { return Button.success( createButtonId(BTN_DATA_COURSE_PREFIX + CUSTOM_DELIMITER + categoryId + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } else { return Button.primary( createButtonId(BTN_DATA_COURSE_PREFIX + CUSTOM_DELIMITER + categoryId + CUSTOM_DELIMITER + entry.getKey()), entry.getValue().getUnicodeEmoji() + " " + entry.getValue().getName() ); } }).collect(Collectors.toList()); categoryButtons.add(Button.danger(createButtonId(BTN_DATA_RETURN_MAIN), "\uD83D\uDD19 Zurück")); messageBuilder.setActionRows(ActionRowUtil.fillButtons(categoryButtons)); return messageBuilder.build(); } private Message createExpectedDegreeMenu(Member initiator) { return createExpectedDegreeMenu(initiator.getRoles()); } private Message createExpectedDegreeMenu(List<Role> roleList) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du auswählen welchen Abschluss ") .append("du aktuell anstrebst. Du kannst maximal eine Rolle auswählen."); List<Button> buttonList = new ArrayList<>(); for (ProfileSubconfig.NameEmojiRole degreeRole : getParent().getConfig().getProfile().getDegreeRoles()) { buildSingleSelectButtons(roleList, buttonList, degreeRole, BTN_DATA_DEGREE_PREFIX); } messageBuilder.setActionRows(ActionRowUtil.fillButtons(buttonList)); return messageBuilder.build(); } private Message createStartYearMenu(Member initiator) { return createStartYearMenu(initiator.getRoles()); } private Message createStartYearMenu(List<Role> roleList) { MessageBuilder messageBuilder = new MessageBuilder("Hier kannst du auswählen wann du dein Studium ") .append("begonnen hast. Du kannst maximal eine Rolle auswählen."); List<Button> buttonList = new ArrayList<>(); for (ProfileSubconfig.NameEmojiRole degreeRole : getParent().getConfig().getProfile().getYearRoles()) { buildSingleSelectButtons(roleList, buttonList, degreeRole, BTN_DATA_YEAR_PREFIX); } messageBuilder.setActionRows(ActionRowUtil.fillButtons(buttonList)); return messageBuilder.build(); } /** * Generated from IntelliJ "extract from duplicates" feature */ private void buildSingleSelectButtons(List<Role> roleList, List<Button> buttonList, ProfileSubconfig.NameEmojiRole degreeRole, String dataPrefix) { if (roleList.stream().anyMatch(role -> role.getIdLong() == degreeRole.getDiscordRoleId())) { buttonList.add(Button.success( createButtonId(dataPrefix + CUSTOM_DELIMITER + degreeRole.getDiscordRoleId()), degreeRole.getUnicodeEmoji() + " " + degreeRole.getName() )); } else { buttonList.add(Button.primary( createButtonId(dataPrefix + CUSTOM_DELIMITER + degreeRole.getDiscordRoleId()), degreeRole.getUnicodeEmoji() + " " + degreeRole.getName() )); } } }
151635_0
package mthread; public class SynchronizeFbLike { public static void main( String[] args ) { /* Facebook Page: Everest, Current Likes: 500 */ final FacebookLike everestFbPagePiclike = new FacebookLike( 500 ); Thread user1 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user2 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user3 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user4 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; /* User1,2,3,4 hit like button in Everest Facebook Page */ user1.start( ); user2.start( ); user3.start( ); user4.start( ); } }
yrojha4ever/JavaStud
src/mthread/SynchronizeFbLike.java
312
/* Facebook Page: Everest, Current Likes: 500 */
block_comment
nl
package mthread; public class SynchronizeFbLike { public static void main( String[] args ) { /* Facebook Page: Everest,<SUF>*/ final FacebookLike everestFbPagePiclike = new FacebookLike( 500 ); Thread user1 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user2 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user3 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user4 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; /* User1,2,3,4 hit like button in Everest Facebook Page */ user1.start( ); user2.start( ); user3.start( ); user4.start( ); } }
4383_12
import nl.han.ica.oopg.alarm.Alarm; import nl.han.ica.oopg.alarm.IAlarmListener; import nl.han.ica.oopg.objects.AnimatedSpriteObject; import nl.han.ica.oopg.objects.Sprite; import nl.han.ica.oopg.sound.Sound; public abstract class Weapon extends AnimatedSpriteObject implements IAlarmListener { protected ShooterApp world; // Player owner is de speler die het wapen 'vast' heeft // Het wapen kan een projectiel afvuren wat gespawned wordt op de huidige locatie van de speler private Player owner; protected String particlefn; protected Sound weaponSound; protected int[] firingDirection = new int[2]; // [x, y] protected boolean canFire = true; protected boolean autoFire; protected double fireDelay; protected int magSize; protected int damage; protected boolean shootingDelayPassed = true; protected int particleSpeed; protected float particleSpawnLocationX; protected float particleSpawnLocationY; private float weaponSpawnLocationX; private float weaponSpawnLocationY; private float weaponZ; protected float particleOffsetX; protected float particleOffsetY; protected float weaponOffsetX; protected float weaponOffsetY; private int currentFrame; /** Maakt nieuw wapen aan zonder sprite * @param world huidige wereld * @param owner eigenaar wapen */ public Weapon(ShooterApp world, Player owner) { super(new Sprite("media/empty.png"), 2); this.world = world; this.owner = owner; } /** Maakt nieuw wapen aan mét sprite * @param world huidige wereld * @param owner eigenaar wapen * @param weaponfn filename wapensprite */ public Weapon(ShooterApp world, Player owner, String weaponfn) { super(new Sprite(weaponfn), 2); this.world = world; this.owner = owner; } @Override public void update() { updateFiringDirection(); updateWeaponPosition(); setCurrentFrameIndex(currentFrame); } /** * update constant de positie van het wapen gebaseerd op de positie van de speler */ private void updateWeaponPosition() { // wapen naar links if(firingDirection[0] == -1) { currentFrame = 1; weaponZ = owner.getZ() -1; particleSpawnLocationX = owner.getX() - particleOffsetX/4; particleSpawnLocationY = owner.getY() + particleOffsetY; weaponSpawnLocationX = owner.getX() - weaponOffsetX/4; weaponSpawnLocationY = owner.getY() + weaponOffsetY; } // wapen naar rechts of andere richtingen else { currentFrame = 0; weaponZ = owner.getZ() +1; particleSpawnLocationX = owner.getX() + particleOffsetX; particleSpawnLocationY = owner.getY() + particleOffsetY; weaponSpawnLocationX = owner.getX() + weaponOffsetX; weaponSpawnLocationY = owner.getY() + weaponOffsetY; } setX(weaponSpawnLocationX); setY(weaponSpawnLocationY); setZ(weaponZ); } /** * update constant de schietrichting van het wapen gebaseerd op de looprichting van de speler. */ public void updateFiringDirection() { if (!owner.isWalking()) { if (owner.getFacingDirection()[0] == -1) { // Speler kijkt naar links firingDirection[0] = -1; firingDirection[1] = 0; } else { // Speler kijkt niet naar links, dus schiet naar rechts firingDirection[0] = 1; firingDirection[1] = 0; } } else { firingDirection[0] = owner.getFacingDirection()[0]; firingDirection[1] = owner.getFacingDirection()[1]; } } /** * Standaard fire()-functie: moet overschreven worden bij het afvuren van meerdere Particles. */ public void fire() { if (autoFire && canFire) { world.addGameObject(new Particle(world, this, particlefn, particleSpawnLocationX, particleSpawnLocationY, firingDirection, particleSpeed, particleSpeed)); addParticleAlarm(); weaponSound.rewind(); weaponSound.play(); canFire = false; } else if (!autoFire && canFire && shootingDelayPassed) { world.addGameObject(new Particle(world, this, particlefn, particleSpawnLocationX, particleSpawnLocationY, firingDirection, particleSpeed, particleSpeed)); addParticleAlarm(); weaponSound.rewind(); weaponSound.play(); canFire = false; shootingDelayPassed = false; } } public void addParticleAlarm() { Alarm nextParticle = new Alarm("Next particle", fireDelay); nextParticle.addTarget(this); nextParticle.start(); } @Override public void triggerAlarm(String s) { shootingDelayPassed = true; if (autoFire) { canFire = true; } } /** stel in of wapen momenteel kan vuren * @param val true / false */ public void setCanFire(boolean val) { canFire = val; } /** * @return of het wapen autoFire ondersteunt */ public boolean getAutoFire() { return autoFire; } /** * @return de hoeveelheid damage die een wapen doet */ public int getDamage() { return damage; } }
ysbakker/2DShooter
src/Weapon.java
1,595
/** * @return of het wapen autoFire ondersteunt */
block_comment
nl
import nl.han.ica.oopg.alarm.Alarm; import nl.han.ica.oopg.alarm.IAlarmListener; import nl.han.ica.oopg.objects.AnimatedSpriteObject; import nl.han.ica.oopg.objects.Sprite; import nl.han.ica.oopg.sound.Sound; public abstract class Weapon extends AnimatedSpriteObject implements IAlarmListener { protected ShooterApp world; // Player owner is de speler die het wapen 'vast' heeft // Het wapen kan een projectiel afvuren wat gespawned wordt op de huidige locatie van de speler private Player owner; protected String particlefn; protected Sound weaponSound; protected int[] firingDirection = new int[2]; // [x, y] protected boolean canFire = true; protected boolean autoFire; protected double fireDelay; protected int magSize; protected int damage; protected boolean shootingDelayPassed = true; protected int particleSpeed; protected float particleSpawnLocationX; protected float particleSpawnLocationY; private float weaponSpawnLocationX; private float weaponSpawnLocationY; private float weaponZ; protected float particleOffsetX; protected float particleOffsetY; protected float weaponOffsetX; protected float weaponOffsetY; private int currentFrame; /** Maakt nieuw wapen aan zonder sprite * @param world huidige wereld * @param owner eigenaar wapen */ public Weapon(ShooterApp world, Player owner) { super(new Sprite("media/empty.png"), 2); this.world = world; this.owner = owner; } /** Maakt nieuw wapen aan mét sprite * @param world huidige wereld * @param owner eigenaar wapen * @param weaponfn filename wapensprite */ public Weapon(ShooterApp world, Player owner, String weaponfn) { super(new Sprite(weaponfn), 2); this.world = world; this.owner = owner; } @Override public void update() { updateFiringDirection(); updateWeaponPosition(); setCurrentFrameIndex(currentFrame); } /** * update constant de positie van het wapen gebaseerd op de positie van de speler */ private void updateWeaponPosition() { // wapen naar links if(firingDirection[0] == -1) { currentFrame = 1; weaponZ = owner.getZ() -1; particleSpawnLocationX = owner.getX() - particleOffsetX/4; particleSpawnLocationY = owner.getY() + particleOffsetY; weaponSpawnLocationX = owner.getX() - weaponOffsetX/4; weaponSpawnLocationY = owner.getY() + weaponOffsetY; } // wapen naar rechts of andere richtingen else { currentFrame = 0; weaponZ = owner.getZ() +1; particleSpawnLocationX = owner.getX() + particleOffsetX; particleSpawnLocationY = owner.getY() + particleOffsetY; weaponSpawnLocationX = owner.getX() + weaponOffsetX; weaponSpawnLocationY = owner.getY() + weaponOffsetY; } setX(weaponSpawnLocationX); setY(weaponSpawnLocationY); setZ(weaponZ); } /** * update constant de schietrichting van het wapen gebaseerd op de looprichting van de speler. */ public void updateFiringDirection() { if (!owner.isWalking()) { if (owner.getFacingDirection()[0] == -1) { // Speler kijkt naar links firingDirection[0] = -1; firingDirection[1] = 0; } else { // Speler kijkt niet naar links, dus schiet naar rechts firingDirection[0] = 1; firingDirection[1] = 0; } } else { firingDirection[0] = owner.getFacingDirection()[0]; firingDirection[1] = owner.getFacingDirection()[1]; } } /** * Standaard fire()-functie: moet overschreven worden bij het afvuren van meerdere Particles. */ public void fire() { if (autoFire && canFire) { world.addGameObject(new Particle(world, this, particlefn, particleSpawnLocationX, particleSpawnLocationY, firingDirection, particleSpeed, particleSpeed)); addParticleAlarm(); weaponSound.rewind(); weaponSound.play(); canFire = false; } else if (!autoFire && canFire && shootingDelayPassed) { world.addGameObject(new Particle(world, this, particlefn, particleSpawnLocationX, particleSpawnLocationY, firingDirection, particleSpeed, particleSpeed)); addParticleAlarm(); weaponSound.rewind(); weaponSound.play(); canFire = false; shootingDelayPassed = false; } } public void addParticleAlarm() { Alarm nextParticle = new Alarm("Next particle", fireDelay); nextParticle.addTarget(this); nextParticle.start(); } @Override public void triggerAlarm(String s) { shootingDelayPassed = true; if (autoFire) { canFire = true; } } /** stel in of wapen momenteel kan vuren * @param val true / false */ public void setCanFire(boolean val) { canFire = val; } /** * @return of het<SUF>*/ public boolean getAutoFire() { return autoFire; } /** * @return de hoeveelheid damage die een wapen doet */ public int getDamage() { return damage; } }
105572_11
package game; import java.io.IOException; import java.util.ArrayList; import com.google.gson.Gson; import deps.Edge; import deps.List; import deps.Vertex; import util.Logbuch; public class ManageClass { private Logbuch m_LogBuch; private GameInfo gi; private Kampfklasse m_kampfklasse; // Kampfklasse private FeldBuilder fb; private ErrorManaged m_ErrorManager; public ManageClass() { fb = new FeldBuilder(); gi = new GameInfo(); try { m_LogBuch = Logbuch.getLogbuch(); } catch (IOException e) { e.printStackTrace(); } } /** * @param spieler * F�gt den Spieler zum Spiel hinzu */ public void addPlayer(Player spieler) { if (gi.getM_SpielStatus() == SpielStatus.nichtAngegeben) { gi.getM_Spieler().add(spieler); } } public void removePlayer(Player spieler) { if (gi.getM_SpielStatus() == SpielStatus.nichtAngegeben) { gi.getM_Spieler().remove(spieler); } } public void setup(){ String result; fb = new FeldBuilder(); result = fb.readFelder("data/Weltkarte/Koordinaten.txt"); if (!result.equals("")) { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben(result); } catch (IOException e) { e.printStackTrace(); } } gi.setM_Felder(fb.getFelder()); fb.readEdges("data/Weltkarte/Graphen.txt"); if (!result.equals("")) { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben(result); } catch (IOException e) { e.printStackTrace(); } } gi.setM_SpielPlan(fb.getGraph()); /*gi.setM_Felder(new ArrayList<Feld>()); ArrayList<Vertex> vertextemp = convertAbiListToArrayList(gi.getM_SpielPlan().getVertices()); for (Vertex vt : vertextemp) { gi.getM_Felder().add(new Feld(vt.getID())); }*/ gi.setM_Gebiete(Gebiet.readGebiete()); } /** * Das Spiel beginnt und wird initialisiert. Keine Spieler k�nnen nun zum * Spiel hinzugef�gt werden. */ public void beginn() { if (gi.getM_SpielStatus() == SpielStatus.nichtAngegeben) { if (gi.getM_Spieler() != null && !gi.getM_Spieler().isEmpty()) { gi.setM_SpielStatus(SpielStatus.Vorbereitung); gi.setM_Runde(0); gebietszuordnung(); gi.setM_TeamsTurn(gi.getM_Spieler().get(0).getTeam()); versorgung(); } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Spieler nicht vorhanden"); } catch (IOException e) { e.printStackTrace(); } } } } /** * Teilt alle Felder an alle Spieler in gleichm��iger Anzahl zuf�llig auf. */ private void gebietszuordnung() { ArrayList<Integer> FreieFelderTeam = new ArrayList<Integer>(); ArrayList<Integer> freieTeam = new ArrayList<Integer>(); for (int i = 0; i < gi.getM_Spieler().size(); i++) { FreieFelderTeam.add((int) (gi.getM_Felder().size() / gi.getM_Spieler().size())); freieTeam.add(gi.getM_Spieler().get(i).getTeam()); } java.util.Random zufall = new java.util.Random(); for (Feld fl : gi.getM_Felder()) { if (freieTeam == null || freieTeam.isEmpty()) { int temp = zufall.nextInt(gi.getM_Spieler().size()); fl.addUnit("Soldat", 1); fl.setZg(gi.getM_Spieler().get(temp).getTeam()); } else { int temp = zufall.nextInt(freieTeam.size()); fl.addUnit("Soldat", 1); fl.setZg(freieTeam.get(temp)); FreieFelderTeam.set(temp, FreieFelderTeam.get(temp) - 1); if (FreieFelderTeam.get(temp) <= 0) { FreieFelderTeam.remove(temp); freieTeam.remove(temp); } } } } /** * Berechnet wieviele Soldaten der Spieler auf das Spielfeld neu verteilen * kann. */ private void versorgung() { gi.setM_SpielStatus(SpielStatus.Versorgung); gi.setM_unitsPlacedNum( (int) Math.ceil((double) Feld.getFelderFromTeam(gi.getM_Felder(), gi.getM_TeamsTurn()).size() / 3) + Gebiet.getTeamBonus(gi.getM_Felder(), gi.getM_TeamsTurn(), gi.getM_Gebiete())); } /** * Ein Soldat wird auf das angegbende Feld gesetzt. * * @param index * des geklickten Buttons (gleich des Index im Feldarray) */ public void versorgungButtonClicked(String id, String typ) { if (gi.getM_SpielStatus() == SpielStatus.Versorgung) { Feld feld = Feld.searchFeld(gi.getM_Felder(), id); if (gi.getM_unitsPlacedNum() > 0 && feld.getZg() == gi.getM_TeamsTurn()) { Feld.searchFeld(gi.getM_Felder(), id).addUnit("Soldat", 1); gi.setM_unitsPlacedNum(gi.getM_unitsPlacedNum() - 1); if (gi.getM_unitsPlacedNum() <= 0) { gi.setM_SpielStatus(SpielStatus.Angriff); } } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Die Einheit konnte nicht auf einem Feld platziert werden, da es nicht dem Spieler der am Zug ist geh�rt."); } catch (IOException e) { e.printStackTrace(); } } } } /** * es wird ein Angriff durchgef�hrt * * @param startId * FeldId der Angreifenden Armee * @param endId * FeldId der Verteidigenden Armee * @param AnzUnits * Anzahl an Soldaten, die vom angreifenden Feld aus angreifen * * */ public void angreifen(String startId, String endId, int AnzUnits) { if (gi.getM_SpielStatus() != SpielStatus.Angriff) { return; } Feld feldStart = Feld.searchFeld(gi.getM_Felder(), startId); Feld feldEnd = Feld.searchFeld(gi.getM_Felder(), endId); if (feldStart.getZg() == gi.getM_TeamsTurn() && feldEnd.getZg() != gi.getM_TeamsTurn() && convertAbiListToArrayList(gi.getM_SpielPlan().getNeighbours(gi.getM_SpielPlan().getVertex(startId))) .contains(gi.getM_SpielPlan().getVertex(endId))) { ArrayList<Einheit> angriffEinheiten = feldStart.getEinheiten(); ArrayList<Einheit> verteidigungsEinheiten = feldEnd.getEinheiten(); for (Einheit ei : angriffEinheiten) { if (ei.getTyp().equals("Soldat") && ei.getAnzahl() > AnzUnits && AnzUnits > 0) { for (Einheit ai : verteidigungsEinheiten) { if (ai.getTyp().equals("Soldat")) { int angriffwuerfel = AnzUnits, verteidigungswuerfel = ai.getAnzahl(); if (verteidigungswuerfel > 2) verteidigungswuerfel = 2; if (angriffwuerfel > 3) angriffwuerfel = 3; int result = Kampfklasse.sieger(angriffwuerfel, verteidigungswuerfel); if (result == 1) { ai.setAnzahl(ai.getAnzahl() - 1); if (ai.getAnzahl() <= 0) { Feld erobertesfeld = Feld.searchFeld(gi.getM_Felder(), endId); erobertesfeld.setZg(gi.getM_TeamsTurn()); erobertesfeld.addUnit("Soldat", angriffwuerfel); ei.setAnzahl(ei.getAnzahl() - angriffwuerfel); } } else { ei.setAnzahl(ei.getAnzahl() - 1); } } } } else { try { m_LogBuch.schreiben("Es wurde ein ung�ltiger Soldatentyp oder eine ung�ltige Anzahl an Soldaten f�r den Angriff ausgew�hlt"); } catch (IOException e) { e.printStackTrace(); } } } } else { try { m_LogBuch.schreiben("Ung�ltige Felder wurden f�r den Angriff gew�hlt"); } catch (IOException e) { e.printStackTrace(); } } } /** * Wenn der Spieler keinen Angriff mehr durchf�hren will, wird damit die * Truppenbewegungsphase eingeleited. */ public void beendeAngriff() { if (gi.getM_SpielStatus() == SpielStatus.Angriff) { gi.setM_SpielStatus(SpielStatus.Truppenbewegung); } } /** * Bewegt eine Anzahl an Soldaten vom Startfeld aufs EndFeld, wenn diese * benachbart sind und dem Spieler geh�ren * * @param startid * die Id des Feldes von dem die Truppen bewegt werden sollen. * @param endID * die Id des Feldes auf das die Truppen bewegt werden sollen. * @param AnzUnits * die Anzahl an Soldaten, die bewegt werden sollen. */ public void Truppenbewegen(String startid, String endID, int AnzUnits) { if (gi.getM_SpielStatus() == SpielStatus.Truppenbewegung) { ArrayList<Einheit> einheiten = Feld.searchFeld(gi.getM_Felder(), startid).getEinheiten(); for (Einheit ei : einheiten) { if (ei.getTyp().equals("Soldat")) { if (ei.getAnzahl() > AnzUnits && convertAbiListToArrayList( gi.getM_SpielPlan().getNeighbours(gi.getM_SpielPlan().getVertex(startid))) .contains(gi.getM_SpielPlan().getVertex(endID)) && Feld.searchFeld(gi.getM_Felder(), startid).getZg() == gi.getM_TeamsTurn() && Feld.searchFeld(gi.getM_Felder(), endID).getZg() == gi.getM_TeamsTurn()) { Feld.searchFeld(gi.getM_Felder(), startid).addUnit("Soldat", -AnzUnits); Feld.searchFeld(gi.getM_Felder(), endID).addUnit("Soldat", AnzUnits); } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Es wurden ung�ltige Felder f�r die Truppenbewegung ausgew�hlt"); } catch (IOException e) { e.printStackTrace(); } } } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Ung�ltiger Armeetyp bei der Truppenbewegung ausgew�hlt."); } catch (IOException e) { e.printStackTrace(); } } } } } /** * Der Spieler m�chte keine Truppen mehr bewegen und beendet damit seinen * Zug */ public void endTruppenbewegung() { if (gi.getM_SpielStatus() == SpielStatus.Truppenbewegung) { gi.setM_SpielStatus(SpielStatus.Versorgung); for (int i = 0; i < gi.getM_Spieler().size(); i++) { if (gi.getM_Spieler().get(i).getTeam() == gi.getM_TeamsTurn()) { if (i >= gi.getM_Spieler().size() - 1) { gi.setM_TeamsTurn(gi.getM_Spieler().get(0).getTeam()); break; } else { gi.setM_TeamsTurn(gi.getM_Spieler().get(i + 1).getTeam()); break; } } } gi.setM_Runde(gi.getM_Runde() + 1); versorgung(); } } /** * �berpr�ft, ob der Spieler, der am Zug ist gewonnen hat * * @return gibt wieder, ob der Spieler der am Zug ist gewonnen hat */ private boolean checkSpielVorbei() { return Feld.getFelderFromTeam(gi.getM_Felder(), gi.getM_TeamsTurn()).containsAll(gi.getM_Felder()); } /** * beendet das Spiel */ public void end() { } /** * convertiert eine AbiListe zu einer ArrayListe * * @param felder * Abiturliste von Vertexen * @return gibt eine ArrayList von Vertexen wieder */ public static ArrayList<Vertex> convertAbiListToArrayList(List<Vertex> felder) { ArrayList<Vertex> result = new ArrayList<Vertex>(); felder.toFirst(); while (felder.hasAccess()) { result.add(felder.getContent()); felder.next(); } return result; } public SpielStatus getStatus() { return gi.getM_SpielStatus(); } public int getTeamsTurn() { return gi.getM_TeamsTurn(); } public String graphToString() { List<Edge> edges = fb.getGraph().getEdges(); String felder = ""; edges.toFirst(); for (; edges.hasAccess(); edges.next()) { Vertex[] verticies = edges.getContent().getVertices(); double weight = edges.getContent().getWeight(); felder += weight + "," + verticies[0].getID() + "," + verticies[1].getID() + ";"; } return felder; } public String gameInfoData() { return gi.toData(); } public ArrayList<Feld> getAlleFelder() { return gi.getM_Felder(); } }
ysndr/rho-SMIMS
rho/src/game/ManageClass.java
4,614
/** * beendet das Spiel */
block_comment
nl
package game; import java.io.IOException; import java.util.ArrayList; import com.google.gson.Gson; import deps.Edge; import deps.List; import deps.Vertex; import util.Logbuch; public class ManageClass { private Logbuch m_LogBuch; private GameInfo gi; private Kampfklasse m_kampfklasse; // Kampfklasse private FeldBuilder fb; private ErrorManaged m_ErrorManager; public ManageClass() { fb = new FeldBuilder(); gi = new GameInfo(); try { m_LogBuch = Logbuch.getLogbuch(); } catch (IOException e) { e.printStackTrace(); } } /** * @param spieler * F�gt den Spieler zum Spiel hinzu */ public void addPlayer(Player spieler) { if (gi.getM_SpielStatus() == SpielStatus.nichtAngegeben) { gi.getM_Spieler().add(spieler); } } public void removePlayer(Player spieler) { if (gi.getM_SpielStatus() == SpielStatus.nichtAngegeben) { gi.getM_Spieler().remove(spieler); } } public void setup(){ String result; fb = new FeldBuilder(); result = fb.readFelder("data/Weltkarte/Koordinaten.txt"); if (!result.equals("")) { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben(result); } catch (IOException e) { e.printStackTrace(); } } gi.setM_Felder(fb.getFelder()); fb.readEdges("data/Weltkarte/Graphen.txt"); if (!result.equals("")) { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben(result); } catch (IOException e) { e.printStackTrace(); } } gi.setM_SpielPlan(fb.getGraph()); /*gi.setM_Felder(new ArrayList<Feld>()); ArrayList<Vertex> vertextemp = convertAbiListToArrayList(gi.getM_SpielPlan().getVertices()); for (Vertex vt : vertextemp) { gi.getM_Felder().add(new Feld(vt.getID())); }*/ gi.setM_Gebiete(Gebiet.readGebiete()); } /** * Das Spiel beginnt und wird initialisiert. Keine Spieler k�nnen nun zum * Spiel hinzugef�gt werden. */ public void beginn() { if (gi.getM_SpielStatus() == SpielStatus.nichtAngegeben) { if (gi.getM_Spieler() != null && !gi.getM_Spieler().isEmpty()) { gi.setM_SpielStatus(SpielStatus.Vorbereitung); gi.setM_Runde(0); gebietszuordnung(); gi.setM_TeamsTurn(gi.getM_Spieler().get(0).getTeam()); versorgung(); } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Spieler nicht vorhanden"); } catch (IOException e) { e.printStackTrace(); } } } } /** * Teilt alle Felder an alle Spieler in gleichm��iger Anzahl zuf�llig auf. */ private void gebietszuordnung() { ArrayList<Integer> FreieFelderTeam = new ArrayList<Integer>(); ArrayList<Integer> freieTeam = new ArrayList<Integer>(); for (int i = 0; i < gi.getM_Spieler().size(); i++) { FreieFelderTeam.add((int) (gi.getM_Felder().size() / gi.getM_Spieler().size())); freieTeam.add(gi.getM_Spieler().get(i).getTeam()); } java.util.Random zufall = new java.util.Random(); for (Feld fl : gi.getM_Felder()) { if (freieTeam == null || freieTeam.isEmpty()) { int temp = zufall.nextInt(gi.getM_Spieler().size()); fl.addUnit("Soldat", 1); fl.setZg(gi.getM_Spieler().get(temp).getTeam()); } else { int temp = zufall.nextInt(freieTeam.size()); fl.addUnit("Soldat", 1); fl.setZg(freieTeam.get(temp)); FreieFelderTeam.set(temp, FreieFelderTeam.get(temp) - 1); if (FreieFelderTeam.get(temp) <= 0) { FreieFelderTeam.remove(temp); freieTeam.remove(temp); } } } } /** * Berechnet wieviele Soldaten der Spieler auf das Spielfeld neu verteilen * kann. */ private void versorgung() { gi.setM_SpielStatus(SpielStatus.Versorgung); gi.setM_unitsPlacedNum( (int) Math.ceil((double) Feld.getFelderFromTeam(gi.getM_Felder(), gi.getM_TeamsTurn()).size() / 3) + Gebiet.getTeamBonus(gi.getM_Felder(), gi.getM_TeamsTurn(), gi.getM_Gebiete())); } /** * Ein Soldat wird auf das angegbende Feld gesetzt. * * @param index * des geklickten Buttons (gleich des Index im Feldarray) */ public void versorgungButtonClicked(String id, String typ) { if (gi.getM_SpielStatus() == SpielStatus.Versorgung) { Feld feld = Feld.searchFeld(gi.getM_Felder(), id); if (gi.getM_unitsPlacedNum() > 0 && feld.getZg() == gi.getM_TeamsTurn()) { Feld.searchFeld(gi.getM_Felder(), id).addUnit("Soldat", 1); gi.setM_unitsPlacedNum(gi.getM_unitsPlacedNum() - 1); if (gi.getM_unitsPlacedNum() <= 0) { gi.setM_SpielStatus(SpielStatus.Angriff); } } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Die Einheit konnte nicht auf einem Feld platziert werden, da es nicht dem Spieler der am Zug ist geh�rt."); } catch (IOException e) { e.printStackTrace(); } } } } /** * es wird ein Angriff durchgef�hrt * * @param startId * FeldId der Angreifenden Armee * @param endId * FeldId der Verteidigenden Armee * @param AnzUnits * Anzahl an Soldaten, die vom angreifenden Feld aus angreifen * * */ public void angreifen(String startId, String endId, int AnzUnits) { if (gi.getM_SpielStatus() != SpielStatus.Angriff) { return; } Feld feldStart = Feld.searchFeld(gi.getM_Felder(), startId); Feld feldEnd = Feld.searchFeld(gi.getM_Felder(), endId); if (feldStart.getZg() == gi.getM_TeamsTurn() && feldEnd.getZg() != gi.getM_TeamsTurn() && convertAbiListToArrayList(gi.getM_SpielPlan().getNeighbours(gi.getM_SpielPlan().getVertex(startId))) .contains(gi.getM_SpielPlan().getVertex(endId))) { ArrayList<Einheit> angriffEinheiten = feldStart.getEinheiten(); ArrayList<Einheit> verteidigungsEinheiten = feldEnd.getEinheiten(); for (Einheit ei : angriffEinheiten) { if (ei.getTyp().equals("Soldat") && ei.getAnzahl() > AnzUnits && AnzUnits > 0) { for (Einheit ai : verteidigungsEinheiten) { if (ai.getTyp().equals("Soldat")) { int angriffwuerfel = AnzUnits, verteidigungswuerfel = ai.getAnzahl(); if (verteidigungswuerfel > 2) verteidigungswuerfel = 2; if (angriffwuerfel > 3) angriffwuerfel = 3; int result = Kampfklasse.sieger(angriffwuerfel, verteidigungswuerfel); if (result == 1) { ai.setAnzahl(ai.getAnzahl() - 1); if (ai.getAnzahl() <= 0) { Feld erobertesfeld = Feld.searchFeld(gi.getM_Felder(), endId); erobertesfeld.setZg(gi.getM_TeamsTurn()); erobertesfeld.addUnit("Soldat", angriffwuerfel); ei.setAnzahl(ei.getAnzahl() - angriffwuerfel); } } else { ei.setAnzahl(ei.getAnzahl() - 1); } } } } else { try { m_LogBuch.schreiben("Es wurde ein ung�ltiger Soldatentyp oder eine ung�ltige Anzahl an Soldaten f�r den Angriff ausgew�hlt"); } catch (IOException e) { e.printStackTrace(); } } } } else { try { m_LogBuch.schreiben("Ung�ltige Felder wurden f�r den Angriff gew�hlt"); } catch (IOException e) { e.printStackTrace(); } } } /** * Wenn der Spieler keinen Angriff mehr durchf�hren will, wird damit die * Truppenbewegungsphase eingeleited. */ public void beendeAngriff() { if (gi.getM_SpielStatus() == SpielStatus.Angriff) { gi.setM_SpielStatus(SpielStatus.Truppenbewegung); } } /** * Bewegt eine Anzahl an Soldaten vom Startfeld aufs EndFeld, wenn diese * benachbart sind und dem Spieler geh�ren * * @param startid * die Id des Feldes von dem die Truppen bewegt werden sollen. * @param endID * die Id des Feldes auf das die Truppen bewegt werden sollen. * @param AnzUnits * die Anzahl an Soldaten, die bewegt werden sollen. */ public void Truppenbewegen(String startid, String endID, int AnzUnits) { if (gi.getM_SpielStatus() == SpielStatus.Truppenbewegung) { ArrayList<Einheit> einheiten = Feld.searchFeld(gi.getM_Felder(), startid).getEinheiten(); for (Einheit ei : einheiten) { if (ei.getTyp().equals("Soldat")) { if (ei.getAnzahl() > AnzUnits && convertAbiListToArrayList( gi.getM_SpielPlan().getNeighbours(gi.getM_SpielPlan().getVertex(startid))) .contains(gi.getM_SpielPlan().getVertex(endID)) && Feld.searchFeld(gi.getM_Felder(), startid).getZg() == gi.getM_TeamsTurn() && Feld.searchFeld(gi.getM_Felder(), endID).getZg() == gi.getM_TeamsTurn()) { Feld.searchFeld(gi.getM_Felder(), startid).addUnit("Soldat", -AnzUnits); Feld.searchFeld(gi.getM_Felder(), endID).addUnit("Soldat", AnzUnits); } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Es wurden ung�ltige Felder f�r die Truppenbewegung ausgew�hlt"); } catch (IOException e) { e.printStackTrace(); } } } else { m_ErrorManager.setErrorManaged(false); try { m_LogBuch.schreiben("Ung�ltiger Armeetyp bei der Truppenbewegung ausgew�hlt."); } catch (IOException e) { e.printStackTrace(); } } } } } /** * Der Spieler m�chte keine Truppen mehr bewegen und beendet damit seinen * Zug */ public void endTruppenbewegung() { if (gi.getM_SpielStatus() == SpielStatus.Truppenbewegung) { gi.setM_SpielStatus(SpielStatus.Versorgung); for (int i = 0; i < gi.getM_Spieler().size(); i++) { if (gi.getM_Spieler().get(i).getTeam() == gi.getM_TeamsTurn()) { if (i >= gi.getM_Spieler().size() - 1) { gi.setM_TeamsTurn(gi.getM_Spieler().get(0).getTeam()); break; } else { gi.setM_TeamsTurn(gi.getM_Spieler().get(i + 1).getTeam()); break; } } } gi.setM_Runde(gi.getM_Runde() + 1); versorgung(); } } /** * �berpr�ft, ob der Spieler, der am Zug ist gewonnen hat * * @return gibt wieder, ob der Spieler der am Zug ist gewonnen hat */ private boolean checkSpielVorbei() { return Feld.getFelderFromTeam(gi.getM_Felder(), gi.getM_TeamsTurn()).containsAll(gi.getM_Felder()); } /** * beendet das Spiel <SUF>*/ public void end() { } /** * convertiert eine AbiListe zu einer ArrayListe * * @param felder * Abiturliste von Vertexen * @return gibt eine ArrayList von Vertexen wieder */ public static ArrayList<Vertex> convertAbiListToArrayList(List<Vertex> felder) { ArrayList<Vertex> result = new ArrayList<Vertex>(); felder.toFirst(); while (felder.hasAccess()) { result.add(felder.getContent()); felder.next(); } return result; } public SpielStatus getStatus() { return gi.getM_SpielStatus(); } public int getTeamsTurn() { return gi.getM_TeamsTurn(); } public String graphToString() { List<Edge> edges = fb.getGraph().getEdges(); String felder = ""; edges.toFirst(); for (; edges.hasAccess(); edges.next()) { Vertex[] verticies = edges.getContent().getVertices(); double weight = edges.getContent().getWeight(); felder += weight + "," + verticies[0].getID() + "," + verticies[1].getID() + ";"; } return felder; } public String gameInfoData() { return gi.toData(); } public ArrayList<Feld> getAlleFelder() { return gi.getM_Felder(); } }
167781_11
/* * Copyright 2023 YugaByte, Inc. and Contributors * * Licensed under the Polyform Free Trial License 1.0.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://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt */ package com.yugabyte.yw.common; import static org.flywaydb.play.FileUtils.readFileToString; import com.google.inject.Inject; import com.google.inject.Singleton; import com.yugabyte.operator.OperatorConfig; import com.yugabyte.yw.models.HighAvailabilityConfig; import com.yugabyte.yw.models.helpers.provider.KubernetesInfo; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.yaml.snakeyaml.Yaml; @Singleton @Slf4j public class PrometheusConfigManager { private final KubernetesManagerFactory kubernetesManagerFactory; private final PrometheusConfigHelper prometheusConfigHelper; private static final String SCRAPE_CONFIG_TEMPLATE = "metric/k8s-node-scrape-config.yaml.template"; private VelocityEngine velocityEngine; @Inject public PrometheusConfigManager( PrometheusConfigHelper prometheusConfigHelper, KubernetesManagerFactory kubernetesManagerFactory) { this.kubernetesManagerFactory = kubernetesManagerFactory; this.prometheusConfigHelper = prometheusConfigHelper; velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.init(); } /** * Update the Prometheus scrape config entries for all the Kubernetes providers in the background. */ public void updateK8sScrapeConfigs() { boolean COMMUNITY_OP_ENABLED = OperatorConfig.getOssMode(); if (COMMUNITY_OP_ENABLED) { log.info("Skipping Prometheus config update as community edition is enabled"); return; } Thread syncThread = new Thread( () -> { try { log.info("Trying to update scrape config entries for Kubernetes providers"); updateK8sScrapeConfigsNow(); log.info("Successfully updated Kubernetes scrape configs"); } catch (Exception e) { log.warn("Failed to update Kubernetes scrape configs", e); } }); syncThread.start(); } public synchronized void updateK8sScrapeConfigsNow() { if (HighAvailabilityConfig.isFollower()) { log.info("Running in follower mode. Skipping Prometheus config update"); return; } // Load the Prometheus configuration file and delete the old // generated entries. File promConfigFile = prometheusConfigHelper.getPrometheusConfigFile(); Yaml yaml = new Yaml(); Map<String, Object> promConfig = yaml.load(readFileToString(promConfigFile)); List<Map<String, Object>> scrapeConfigs = (List<Map<String, Object>>) promConfig.get("scrape_configs"); scrapeConfigs.removeIf( sc -> ((String) sc.getOrDefault("job_name", "")).startsWith("yba-generated-")); // Create scrape_config entry for each Kubernetes info Map<String, KubernetesInfo> k8sInfos = KubernetesUtil.getAllKubernetesInfos(); if (k8sInfos.isEmpty()) { log.info("No Kubernetes infos found. Skipping Prometheus config update"); return; } List<Map<String, Object>> k8sScrapeConfigs = new ArrayList<Map<String, Object>>(); KubernetesManager k8s = kubernetesManagerFactory.getManager(); // To avoid duplicate scrape targets, we keep track of APIServer // Endpoints of the visited clusters. HashSet visitedClusters = new HashSet<>(); // TODO: make these class variables and initialize in the // constructor? Template template = velocityEngine.getTemplate(SCRAPE_CONFIG_TEMPLATE); VelocityContext context = new VelocityContext(); for (Map.Entry<String, KubernetesInfo> entry : k8sInfos.entrySet()) { String uuid = entry.getKey(); KubernetesInfo k8sInfo = entry.getValue(); String apiServerEndpoint = k8sInfo.getApiServerEndpoint(); // Skip the KubernetesInfo if we have successfully processed it before. if (visitedClusters.contains(apiServerEndpoint)) { continue; } String kubeConfigFile = k8sInfo.getKubeConfig(); String tokenFile = k8sInfo.getKubeConfigTokenFile(); String caFile = k8sInfo.getKubeConfigCAFile(); // Only blank kubeconfig indicates that in-cluster credentials // are used. null kubeconfig means that this kubernetesinfo is // unused and some other kubernetesinfo from provider, zone, or // region is in use. if (StringUtils.isBlank(kubeConfigFile) && kubeConfigFile != null) { log.debug("Skipping home cluster Kubernetes info: {}", uuid); continue; } if (StringUtils.isAnyBlank(kubeConfigFile, apiServerEndpoint, tokenFile, caFile)) { log.debug("Skipping Kubernetes info due to missing authentication data: {}", uuid); continue; } // Skip the Kubernetes info if it is pointing to same cluster // where YBA is running. Prometheus already has scrape config // for the home cluster. try { if (k8s.isHomeCluster(kubeConfigFile)) { log.debug("Skipping home cluster Kubernetes info: {}", uuid); visitedClusters.add(apiServerEndpoint); continue; } // We skip the Kubernetes infos in case of failure to avoid any // duplicate metrics. We don't consider those as visited as we // might get a different authentication data in later iteration. } catch (Exception e) { log.warn( "Skipping Kubernetes info {}: Failed to verify if it is of the home cluster: {}", uuid, e.getMessage()); continue; } visitedClusters.add(apiServerEndpoint); String apiServerScheme; // TODO(bhavin192): switch to java.net.URI/URL here? It doesn't // seem to work with just IPs without a protocol. String[] apiServerParts = apiServerEndpoint.split("://", 2); // APIServer endpoint without a scheme if (apiServerParts.length < 2) { apiServerEndpoint = apiServerParts[0]; apiServerScheme = "http"; } else { apiServerScheme = apiServerParts[0]; apiServerEndpoint = apiServerParts[1]; } String scrapeConfig = ""; context.put("kubeconfig_uuid", uuid); context.put("scheme", apiServerScheme); context.put("server_domain", apiServerEndpoint); context.put("ca_file", caFile); context.put("bearer_token_file", tokenFile); context.put("kubeconfig_file", kubeConfigFile); try (StringWriter writer = new StringWriter()) { template.merge(context, writer); scrapeConfig = writer.toString(); } catch (IOException ignored) { // Can't happen as it is from StringWriter's close, which does // nothing. } List<Map<String, Object>> scYaml = yaml.load(scrapeConfig); k8sScrapeConfigs.addAll(scYaml); } // Update Prometheus config with new Kubernetes scrape config // entries. scrapeConfigs.addAll(k8sScrapeConfigs); promConfig.put("scrape_configs", scrapeConfigs); try (BufferedWriter bw = new BufferedWriter(new FileWriter(promConfigFile))) { yaml.dump(promConfig, bw); } catch (IOException e) { log.error(e.getMessage()); throw new RuntimeException("Error writing Prometheus configuration"); } log.info("Wrote updated Prometheus configuration to disk"); prometheusConfigHelper.reloadPrometheusConfig(); } }
yugabyte/yugabyte-db
managed/src/main/java/com/yugabyte/yw/common/PrometheusConfigManager.java
2,521
// region is in use.
line_comment
nl
/* * Copyright 2023 YugaByte, Inc. and Contributors * * Licensed under the Polyform Free Trial License 1.0.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://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt */ package com.yugabyte.yw.common; import static org.flywaydb.play.FileUtils.readFileToString; import com.google.inject.Inject; import com.google.inject.Singleton; import com.yugabyte.operator.OperatorConfig; import com.yugabyte.yw.models.HighAvailabilityConfig; import com.yugabyte.yw.models.helpers.provider.KubernetesInfo; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.yaml.snakeyaml.Yaml; @Singleton @Slf4j public class PrometheusConfigManager { private final KubernetesManagerFactory kubernetesManagerFactory; private final PrometheusConfigHelper prometheusConfigHelper; private static final String SCRAPE_CONFIG_TEMPLATE = "metric/k8s-node-scrape-config.yaml.template"; private VelocityEngine velocityEngine; @Inject public PrometheusConfigManager( PrometheusConfigHelper prometheusConfigHelper, KubernetesManagerFactory kubernetesManagerFactory) { this.kubernetesManagerFactory = kubernetesManagerFactory; this.prometheusConfigHelper = prometheusConfigHelper; velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.init(); } /** * Update the Prometheus scrape config entries for all the Kubernetes providers in the background. */ public void updateK8sScrapeConfigs() { boolean COMMUNITY_OP_ENABLED = OperatorConfig.getOssMode(); if (COMMUNITY_OP_ENABLED) { log.info("Skipping Prometheus config update as community edition is enabled"); return; } Thread syncThread = new Thread( () -> { try { log.info("Trying to update scrape config entries for Kubernetes providers"); updateK8sScrapeConfigsNow(); log.info("Successfully updated Kubernetes scrape configs"); } catch (Exception e) { log.warn("Failed to update Kubernetes scrape configs", e); } }); syncThread.start(); } public synchronized void updateK8sScrapeConfigsNow() { if (HighAvailabilityConfig.isFollower()) { log.info("Running in follower mode. Skipping Prometheus config update"); return; } // Load the Prometheus configuration file and delete the old // generated entries. File promConfigFile = prometheusConfigHelper.getPrometheusConfigFile(); Yaml yaml = new Yaml(); Map<String, Object> promConfig = yaml.load(readFileToString(promConfigFile)); List<Map<String, Object>> scrapeConfigs = (List<Map<String, Object>>) promConfig.get("scrape_configs"); scrapeConfigs.removeIf( sc -> ((String) sc.getOrDefault("job_name", "")).startsWith("yba-generated-")); // Create scrape_config entry for each Kubernetes info Map<String, KubernetesInfo> k8sInfos = KubernetesUtil.getAllKubernetesInfos(); if (k8sInfos.isEmpty()) { log.info("No Kubernetes infos found. Skipping Prometheus config update"); return; } List<Map<String, Object>> k8sScrapeConfigs = new ArrayList<Map<String, Object>>(); KubernetesManager k8s = kubernetesManagerFactory.getManager(); // To avoid duplicate scrape targets, we keep track of APIServer // Endpoints of the visited clusters. HashSet visitedClusters = new HashSet<>(); // TODO: make these class variables and initialize in the // constructor? Template template = velocityEngine.getTemplate(SCRAPE_CONFIG_TEMPLATE); VelocityContext context = new VelocityContext(); for (Map.Entry<String, KubernetesInfo> entry : k8sInfos.entrySet()) { String uuid = entry.getKey(); KubernetesInfo k8sInfo = entry.getValue(); String apiServerEndpoint = k8sInfo.getApiServerEndpoint(); // Skip the KubernetesInfo if we have successfully processed it before. if (visitedClusters.contains(apiServerEndpoint)) { continue; } String kubeConfigFile = k8sInfo.getKubeConfig(); String tokenFile = k8sInfo.getKubeConfigTokenFile(); String caFile = k8sInfo.getKubeConfigCAFile(); // Only blank kubeconfig indicates that in-cluster credentials // are used. null kubeconfig means that this kubernetesinfo is // unused and some other kubernetesinfo from provider, zone, or // region is<SUF> if (StringUtils.isBlank(kubeConfigFile) && kubeConfigFile != null) { log.debug("Skipping home cluster Kubernetes info: {}", uuid); continue; } if (StringUtils.isAnyBlank(kubeConfigFile, apiServerEndpoint, tokenFile, caFile)) { log.debug("Skipping Kubernetes info due to missing authentication data: {}", uuid); continue; } // Skip the Kubernetes info if it is pointing to same cluster // where YBA is running. Prometheus already has scrape config // for the home cluster. try { if (k8s.isHomeCluster(kubeConfigFile)) { log.debug("Skipping home cluster Kubernetes info: {}", uuid); visitedClusters.add(apiServerEndpoint); continue; } // We skip the Kubernetes infos in case of failure to avoid any // duplicate metrics. We don't consider those as visited as we // might get a different authentication data in later iteration. } catch (Exception e) { log.warn( "Skipping Kubernetes info {}: Failed to verify if it is of the home cluster: {}", uuid, e.getMessage()); continue; } visitedClusters.add(apiServerEndpoint); String apiServerScheme; // TODO(bhavin192): switch to java.net.URI/URL here? It doesn't // seem to work with just IPs without a protocol. String[] apiServerParts = apiServerEndpoint.split("://", 2); // APIServer endpoint without a scheme if (apiServerParts.length < 2) { apiServerEndpoint = apiServerParts[0]; apiServerScheme = "http"; } else { apiServerScheme = apiServerParts[0]; apiServerEndpoint = apiServerParts[1]; } String scrapeConfig = ""; context.put("kubeconfig_uuid", uuid); context.put("scheme", apiServerScheme); context.put("server_domain", apiServerEndpoint); context.put("ca_file", caFile); context.put("bearer_token_file", tokenFile); context.put("kubeconfig_file", kubeConfigFile); try (StringWriter writer = new StringWriter()) { template.merge(context, writer); scrapeConfig = writer.toString(); } catch (IOException ignored) { // Can't happen as it is from StringWriter's close, which does // nothing. } List<Map<String, Object>> scYaml = yaml.load(scrapeConfig); k8sScrapeConfigs.addAll(scYaml); } // Update Prometheus config with new Kubernetes scrape config // entries. scrapeConfigs.addAll(k8sScrapeConfigs); promConfig.put("scrape_configs", scrapeConfigs); try (BufferedWriter bw = new BufferedWriter(new FileWriter(promConfigFile))) { yaml.dump(promConfig, bw); } catch (IOException e) { log.error(e.getMessage()); throw new RuntimeException("Error writing Prometheus configuration"); } log.info("Wrote updated Prometheus configuration to disk"); prometheusConfigHelper.reloadPrometheusConfig(); } }
80802_2
/* * Bot for teamspeak3 to collect data for generating statistics * Copyright (C) 2014-2022 Robin C. * * This program 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. * * 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package core; import java.util.Calendar; import logging.Logger; import main.Config; public class Job extends Thread { private Connection con; public boolean stopReq = false; public static Calendar calendar; int lastMinute = -1; public Job(Connection con){ this.con = con; } @Override public void run() { while(!stopReq) { try { Thread.sleep(20000); // checkn iedere 20s, why not? calendar.setTimeInMillis(System.currentTimeMillis()); int m = calendar.get(Calendar.MINUTE); if (lastMinute == -1) lastMinute = m; // 2x stats preventie bij restart op de minuut if ((m-1)%5 == 0 && lastMinute != m) { // om de 5 minten, @1,6,11,16,21,26,31,36,41,46,51,56 (hence the (m-1)%5) lastMinute = m; con.update(); } else if (Config.getBool("experimental_forcekeepalive")) { con.keepalive(); } } catch (InterruptedException e) { Logger.err.println("InterruptedException in job", e); } } } }
yugecin/tsstats
src/core/Job.java
566
// 2x stats preventie bij restart op de minuut
line_comment
nl
/* * Bot for teamspeak3 to collect data for generating statistics * Copyright (C) 2014-2022 Robin C. * * This program 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. * * 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package core; import java.util.Calendar; import logging.Logger; import main.Config; public class Job extends Thread { private Connection con; public boolean stopReq = false; public static Calendar calendar; int lastMinute = -1; public Job(Connection con){ this.con = con; } @Override public void run() { while(!stopReq) { try { Thread.sleep(20000); // checkn iedere 20s, why not? calendar.setTimeInMillis(System.currentTimeMillis()); int m = calendar.get(Calendar.MINUTE); if (lastMinute == -1) lastMinute = m; // 2x stats<SUF> if ((m-1)%5 == 0 && lastMinute != m) { // om de 5 minten, @1,6,11,16,21,26,31,36,41,46,51,56 (hence the (m-1)%5) lastMinute = m; con.update(); } else if (Config.getBool("experimental_forcekeepalive")) { con.keepalive(); } } catch (InterruptedException e) { Logger.err.println("InterruptedException in job", e); } } } }
49881_17
/******************************************************************************* * Copyright 2012 Analog Devices, Inc. * * 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.analog.lyric.dimple.solvers.sumproduct; import static com.analog.lyric.math.Utilities.*; import java.util.Arrays; import java.util.Objects; import org.eclipse.jdt.annotation.Nullable; import com.analog.lyric.collect.ArrayUtil; import com.analog.lyric.collect.Selection; import com.analog.lyric.dimple.environment.DimpleEnvironment; import com.analog.lyric.dimple.exceptions.DimpleException; import com.analog.lyric.dimple.factorfunctions.core.FactorFunction; import com.analog.lyric.dimple.factorfunctions.core.FactorTableRepresentation; import com.analog.lyric.dimple.factorfunctions.core.IFactorTable; import com.analog.lyric.dimple.model.factors.Factor; import com.analog.lyric.dimple.model.variables.Variable; import com.analog.lyric.dimple.options.BPOptions; import com.analog.lyric.dimple.solvers.core.STableFactorDoubleArray; import com.analog.lyric.dimple.solvers.core.kbest.IKBestFactor; import com.analog.lyric.dimple.solvers.core.kbest.KBestFactorEngine; import com.analog.lyric.dimple.solvers.core.kbest.KBestFactorTableEngine; import com.analog.lyric.dimple.solvers.core.parameterizedMessages.DiscreteMessage; import com.analog.lyric.dimple.solvers.core.parameterizedMessages.DiscreteWeightMessage; import com.analog.lyric.dimple.solvers.interfaces.ISolverFactorGraph; import com.analog.lyric.dimple.solvers.interfaces.ISolverNode; import com.analog.lyric.dimple.solvers.optimizedupdate.FactorTableUpdateSettings; import com.analog.lyric.dimple.solvers.optimizedupdate.FactorUpdatePlan; import com.analog.lyric.dimple.solvers.optimizedupdate.ISTableFactorSupportingOptimizedUpdate; import com.analog.lyric.dimple.solvers.optimizedupdate.UpdateApproach; import com.analog.lyric.util.misc.Internal; /** * Solver representation of table factor under Sum-Product solver. * * @since 0.07 */ public class SumProductTableFactor extends STableFactorDoubleArray implements IKBestFactor, ISTableFactorSupportingOptimizedUpdate { /* * We cache all of the double arrays we use during the update. This saves * time when performing the update. */ protected double [][] _savedOutMsgArray = ArrayUtil.EMPTY_DOUBLE_ARRAY_ARRAY; protected @Nullable double [][][] _outPortDerivativeMsgs; protected double [] _dampingParams = ArrayUtil.EMPTY_DOUBLE_ARRAY; protected @Nullable TableFactorEngine _tableFactorEngine; protected KBestFactorEngine _kbestFactorEngine; protected int _k; protected boolean _kIsSmallerThanDomain = false; protected boolean _updateDerivative = false; protected boolean _dampingInUse = false; /*-------------- * Construction */ public SumProductTableFactor(Factor factor) { super(factor); //TODO: should I recheck for factor table every once in a while? if (factor.getFactorFunction().factorTableExists(getFactor())) { _kbestFactorEngine = new KBestFactorTableEngine(this); } else { _kbestFactorEngine = new KBestFactorEngine(this); } } @Override public void initialize() { super.initialize(); configureDampingFromOptions(); updateK(getOptionOrDefault(BPOptions.maxMessageSize)); } @Internal public void setupTableFactorEngine() { FactorUpdatePlan updatePlan = null; final FactorTableUpdateSettings factorTableUpdateSettings = getFactorTableUpdateSettings(); if (factorTableUpdateSettings != null) { updatePlan = factorTableUpdateSettings.getOptimizedUpdatePlan(); } if (updatePlan != null) { _tableFactorEngine = new TableFactorEngineOptimized(this, updatePlan); } else { _tableFactorEngine = new TableFactorEngine(this); } } @Internal @Nullable FactorTableUpdateSettings getFactorTableUpdateSettings() { ISolverFactorGraph rootGraph = getRootGraph(); if (rootGraph instanceof SumProductSolverGraph) { final SumProductSolverGraph sfg = (SumProductSolverGraph) getRootGraph(); if (sfg != null) { return sfg.getFactorTableUpdateSettings(getFactor()); } } return null; } /*--------------------- * ISolverNode methods */ @Override public void moveMessages(ISolverNode other, int portNum, int otherPort) { super.moveMessages(other,portNum,otherPort); SumProductTableFactor sother = (SumProductTableFactor)other; if (_dampingInUse) _savedOutMsgArray[portNum] = sother._savedOutMsgArray[otherPort]; } private TableFactorEngine getTableFactorEngine() { final TableFactorEngine tableFactorEngine = _tableFactorEngine; if (tableFactorEngine != null) { return tableFactorEngine; } else { throw new DimpleException("The solver was not initialized. Use solve() or call initialize() before iterate()."); } } @Override protected void doUpdate() { if (_kIsSmallerThanDomain) //TODO: damping _kbestFactorEngine.update(); else getTableFactorEngine().update(); if (_updateDerivative) for (int i = 0; i < _inputMsgs.length ;i++) updateDerivative(i); } @Override public void doUpdateEdge(int outPortNum) { if (_kIsSmallerThanDomain) _kbestFactorEngine.updateEdge(outPortNum); else getTableFactorEngine().updateEdge(outPortNum); if (_updateDerivative) updateDerivative(outPortNum); } /*----------------------- * ISolverFactor methods */ @Override public void createMessages() { super.createMessages(); } /* * (non-Javadoc) * @see com.analog.lyric.dimple.solvers.core.SFactorBase#getBelief() * * Calculates a piece of the beta free energy */ @Override public double [] getBelief() { double [] retval = getUnormalizedBelief(); double sum = 0; for (int i = 0; i < retval.length; i++) sum += retval[i]; for (int i = 0; i < retval.length; i++) retval[i] /= sum; return retval; } /*--------------- * SNode methods */ @Override public DiscreteMessage cloneMessage(int edge) { return new DiscreteWeightMessage(_outputMsgs[edge]); } /*-------------------------- * STableFactorBase methods */ @Override protected void setTableRepresentation(IFactorTable table) { table.setRepresentation(FactorTableRepresentation.SPARSE_WEIGHT_WITH_INDICES); } @Override public boolean supportsMessageEvents() { return true; } /*------------- * New methods */ @Deprecated public void setDamping(int index, double val) { double[] params = BPOptions.nodeSpecificDamping.getOrDefault(this).toPrimitiveArray(); if (params.length == 0 && val != 0.0) { params = new double[getSiblingCount()]; } if (params.length != 0) { params[index] = val; } BPOptions.nodeSpecificDamping.set(this, params); configureDampingFromOptions(); } @Override public double getDamping(int index) { return _dampingParams.length > 0 ? _dampingParams[index] : 0.0; } /** * Enables use of the optimized update algorithm on this factor, if its degree is greater than * 1. The optimized update algorithm is employed only when all of the factor's edges are updated * together with an update call. If the schedule instead uses update_edge, the algorithm is not * used. * <p> * This method is deprecated; instead set UpdateOptions.updateApproach. * * @since 0.06 */ @Deprecated public void enableOptimizedUpdate() { setOption(BPOptions.updateApproach, UpdateApproach.OPTIMIZED); } /** * Disables use of the optimized update algorithm on this factor. * <p> * This method is deprecated; instead set UpdateOptions.updateApproach. * * @see #enableOptimizedUpdate() * @since 0.06 */ @Deprecated public void disableOptimizedUpdate() { setOption(BPOptions.updateApproach, UpdateApproach.NORMAL); } /** * Reverts to the default setting for enabling of the optimized update algorithm, eliminating * the effect of previous calls to {@link #enableOptimizedUpdate()} or * {@link #disableOptimizedUpdate()}. * <p> * This method is deprecated; instead reset UpdateOptions.updateApproach. * * @since 0.06 */ @Deprecated public void useDefaultOptimizedUpdateEnable() { unsetOption(BPOptions.updateApproach); } /** * Returns the effective update approach for the factor. If the update approach is set to * automatic, this value is not valid until the graph is initialized. Note that a factor * with only one edge always employs the normal update approach. * * @since 0.07 */ public UpdateApproach getEffectiveUpdateApproach() { FactorTableUpdateSettings factorTableUpdateSettings = getFactorTableUpdateSettings(); if (factorTableUpdateSettings != null && factorTableUpdateSettings.getOptimizedUpdatePlan() != null) { return UpdateApproach.OPTIMIZED; } else { return UpdateApproach.NORMAL; } } @Internal public @Nullable UpdateApproach getAutomaticUpdateApproach() { FactorTableUpdateSettings updateSettings = getFactorTableUpdateSettings(); if (updateSettings != null) { return updateSettings.getAutomaticUpdateApproach(); } return null; } public int getK() { return _k; } public void setK(int k) { setOption(BPOptions.maxMessageSize, k); updateK(k); } private void updateK(int k) { if (k != _k) { _k = k; _kbestFactorEngine.setK(k); _kIsSmallerThanDomain = false; for (int i = 0; i < _inputMsgs.length; i++) { if (_inputMsgs[i] != null && _k < _inputMsgs[i].length) { _kIsSmallerThanDomain = true; break; } } } } public void setUpdateDerivative(boolean updateDer) { _updateDerivative = updateDer; } public double [] getUnormalizedBelief() { final int [][] table = getFactorTable().getIndicesSparseUnsafe(); final double [] values = getFactorTable().getWeightsSparseUnsafe(); final int nEntries = values.length; final double [] retval = new double[nEntries]; for (int i = 0; i < nEntries; i++) { retval[i] = values[i]; final int[] indices = table[i]; for (int j = 0; j < indices.length; j++) { retval[i] *= _inputMsgs[j][indices[j]]; } } return retval; } @Override public FactorFunction getFactorFunction() { return getFactor().getFactorFunction(); } @Override public double initAccumulator() { return 1; } @Override public double accumulate(double oldVal, double newVal) { return oldVal*newVal; } @Override public double combine(double oldVal, double newVal) { return oldVal+newVal; } @Override public void normalize(double[] outputMsg) { double sum = 0; for (int i = 0; i < outputMsg.length; i++) sum += outputMsg[i]; if (sum == 0) throw new DimpleException("Update failed in SumProduct Solver. All probabilities were zero when calculating message for port " + " on factor " +_factor.getLabel()); for (int i = 0; i < outputMsg.length; i++) outputMsg[i] /= sum; } @Override public double evalFactorFunction(Object[] inputs) { return getFactor().getFactorFunction().eval(inputs); } @Override public void initMsg(double[] msg) { Arrays.fill(msg, 0); } @Override public double getFactorTableValue(int index) { return getFactorTable().getWeightsSparseUnsafe()[index]; } @Override public int[] findKBestForMsg(double[] msg, int k) { return Selection.findLastKIndices(msg, k); } /****************************************************** * Energy, Entropy, and derivatives of all that. ******************************************************/ @Override public double getInternalEnergy() { final double [] beliefs = getBelief(); final double [] weights = getFactorTable().getWeightsSparseUnsafe(); double sum = 0; for (int i = beliefs.length; --i>=0;) { sum += beliefs[i] * weightToEnergy(weights[i]); } return sum; } @Override public double getBetheEntropy() { double sum = 0; final double [] beliefs = getBelief(); for (double belief : beliefs) { sum -= belief * Math.log(belief); } return sum; } @SuppressWarnings("null") public double calculateDerivativeOfInternalEnergyWithRespectToWeight(int weightIndex) { SumProductSolverGraph sfg = (SumProductSolverGraph)getRootGraph(); boolean isFactorOfInterest = sfg.getCurrentFactorTable() == getFactor().getFactorTable(); double [] weights = _factor.getFactorTable().getWeightsSparseUnsafe(); //TODO: avoid recompute double [] beliefs = getBelief(); double sum = 0; for (int i = 0; i < weights.length; i++) { //beliefs = getUnormalizedBelief(); //Belief'(weightIndex)*(-log(weight(weightIndex))) + Belief(weightIndex)*(-log(weight(weightIndex)))' //(-log(weight(weightIndex)))' = - 1 / weight(weightIndex) double mlogweight = -Math.log(weights[i]); double belief = beliefs[i]; double mlogweightderivative = 0; if (i == weightIndex && isFactorOfInterest) mlogweightderivative = -1.0 / weights[weightIndex]; double beliefderivative = calculateDerivativeOfBeliefWithRespectToWeight(weightIndex,i,isFactorOfInterest); sum += beliefderivative*mlogweight + belief*mlogweightderivative; //sum += beliefderivative; } //return beliefderivative*mlogweight + belief*mlogweightderivative; return sum; } @SuppressWarnings("null") public double calculateDerivativeOfBeliefNumeratorWithRespectToWeight(int weightIndex, int index, boolean isFactorOfInterest) { double [] weights = _factor.getFactorTable().getWeightsSparseUnsafe(); int [][] indices = _factor.getFactorTable().getIndicesSparseUnsafe(); //calculate product of messages and phi double prod = weights[index]; for (int i = 0; i < _inputMsgs.length; i++) prod *= _inputMsgs[i][indices[index][i]]; double sum = 0; //if index == weightIndex, add in this term if (index == weightIndex && isFactorOfInterest) { sum = prod / weights[index]; } //for each variable for (int i = 0; i < _inputMsgs.length; i++) { SumProductDiscrete var = (SumProductDiscrete)getFactor().getConnectedNodesFlat().getByIndex(i).getSolver(); //divide out contribution sum += prod / _inputMsgs[i][indices[index][i]] * var.getMessageDerivative(weightIndex,getFactor())[indices[index][i]]; } return sum; } public double calculateDerivativeOfBeliefDenomenatorWithRespectToWeight(int weightIndex, int index, boolean isFactorOfInterest) { double sum = 0; for (int i = 0, end = getFactor().getFactorTable().sparseSize(); i < end; i++) sum += calculateDerivativeOfBeliefNumeratorWithRespectToWeight(weightIndex,i,isFactorOfInterest); return sum; } public double calculateDerivativeOfBeliefWithRespectToWeight(int weightIndex,int index, boolean isFactorOfInterest) { double [] un = getUnormalizedBelief(); double f = un[index]; double fderivative = calculateDerivativeOfBeliefNumeratorWithRespectToWeight(weightIndex, index,isFactorOfInterest); double gderivative = calculateDerivativeOfBeliefDenomenatorWithRespectToWeight(weightIndex, index,isFactorOfInterest); double g = 0; for (int i = 0; i < un.length; i++) g += un[i]; double tmp = (fderivative*g-f*gderivative)/(g*g); return tmp; } public void initializeDerivativeMessages(int weights) { final double[][][] msgs = _outPortDerivativeMsgs = new double[weights][_inputMsgs.length][]; for (int i = 0; i < weights; i++) for (int j = 0; j < _inputMsgs.length; j++) msgs[i][j] = new double[_inputMsgs[j].length]; } public double [] getMessageDerivative(int wn, Variable var) { int index = getFactor().getPortNum(var); return Objects.requireNonNull(_outPortDerivativeMsgs)[wn][index]; } public double calculateMessageForDomainValueAndTableIndex(int domainValue, int outPortNum, int tableIndex) { IFactorTable ft = getFactor().getFactorTable(); int [][] indices = ft.getIndicesSparseUnsafe(); double [] weights = ft.getWeightsSparseUnsafe(); if (indices[tableIndex][outPortNum] == domainValue) { double prod = weights[tableIndex]; for (int j = 0; j < _inputMsgs.length; j++) { if (outPortNum != j) { prod *= _inputMsgs[j][indices[tableIndex][j]]; } } return prod; } else return 0; } public double calculateMessageForDomainValue(int domainValue, int outPortNum) { IFactorTable ft = getFactor().getFactorTable(); double sum = 0; int [][] indices = ft.getIndicesSparseUnsafe(); for (int i = 0, end = ft.sparseSize(); i < end; i++) if (indices[i][outPortNum] == domainValue) sum += calculateMessageForDomainValueAndTableIndex(domainValue,outPortNum,i); return sum; } public double calculatedf(int outPortNum, int domainValue, int wn, boolean factorUsesTable) { IFactorTable ft = getFactor().getFactorTable(); double sum = 0; int [][] indices = ft.getIndicesSparseUnsafe(); double [] weights = ft.getWeightsSparseUnsafe(); for (int i = 0; i < indices.length; i++) { if (indices[i][outPortNum] == domainValue) { double prod = calculateMessageForDomainValueAndTableIndex(domainValue,outPortNum,i); if (factorUsesTable && (wn == i)) { sum += prod/weights[i]; } for (int j = 0; j < _inputMsgs.length; j++) { if (j != outPortNum) { SumProductDiscrete sv = (SumProductDiscrete)getFactor().getConnectedNodesFlat().getByIndex(j).getSolver(); @SuppressWarnings("null") double [] dvar = sv.getMessageDerivative(wn,getFactor()); sum += (prod / _inputMsgs[j][indices[i][j]]) * dvar[indices[i][j]]; } } } } return sum; } public double calculatedg(int outPortNum, int wn, boolean factorUsesTable) { double sum = 0; for (int i = 0; i < _inputMsgs[outPortNum].length; i++) sum += calculatedf(outPortNum,i,wn,factorUsesTable); return sum; } public void updateDerivativeForWeightAndDomain(int outPortNum, int wn, int d,boolean factorUsesTable) { //TODO: not re-using computation efficiently. //calculate f double f = calculateMessageForDomainValue(d,outPortNum); //calculate g double g = 0; for (int i = 0; i < _inputMsgs[outPortNum].length; i++) g += calculateMessageForDomainValue(i,outPortNum); double derivative = 0; if (g != 0) { double df = calculatedf(outPortNum,d,wn,factorUsesTable); double dg = calculatedg(outPortNum,wn,factorUsesTable); //derivative = df; derivative = (df*g - f*dg) / (g*g); } Objects.requireNonNull(_outPortDerivativeMsgs)[wn][outPortNum][d] = derivative; } public void updateDerivativeForWeight(int outPortNum, int wn,boolean factorUsesTable) { int D = _inputMsgs[outPortNum].length; for (int d = 0; d < D; d++) { updateDerivativeForWeightAndDomain(outPortNum,wn,d,factorUsesTable); } } public void updateDerivative(int outPortNum) { SumProductSolverGraph sfg = (SumProductSolverGraph)getRootGraph(); @SuppressWarnings("null") IFactorTable ft = sfg.getCurrentFactorTable(); @SuppressWarnings("null") int numWeights = ft.sparseSize(); for (int wn = 0; wn < numWeights; wn++) { updateDerivativeForWeight(outPortNum,wn,ft == getFactor().getFactorTable()); } } public double calculateDerivativeOfBetheEntropyWithRespectToWeight(int weightIndex) { @SuppressWarnings("null") boolean isFactorOfInterest = ((SumProductSolverGraph)getRootGraph()).getCurrentFactorTable() == getFactor().getFactorTable(); //Belief'(weightIndex)*(-log(Belief(weightIndex))) + Belief(weightIndex)*(-log(Belief(weightIndex)))' double [] beliefs = getBelief(); double sum = 0; for (int i = 0; i < beliefs.length; i++) { double beliefderivative = calculateDerivativeOfBeliefWithRespectToWeight(weightIndex,i,isFactorOfInterest); double belief = beliefs[i]; sum += beliefderivative*(-Math.log(belief)) - beliefderivative; } return sum; } @Override public double[][] getInPortMsgs() { return _inputMsgs; } @Override public double[][] getOutPortMsgs() { return _outputMsgs; } @Override public boolean isDampingInUse() { return _dampingInUse; } @Override public double[] getSavedOutMsgArray(int _outPortNum) { return _savedOutMsgArray[_outPortNum]; } /*------------------ * Internal methods */ protected void configureDampingFromOptions() { final int size = getSiblingCount(); _dampingParams = getReplicatedNonZeroListFromOptions(BPOptions.nodeSpecificDamping, BPOptions.damping, size, _dampingParams); if (_dampingParams.length > 0 && _dampingParams.length != size) { DimpleEnvironment.logWarning("%s has wrong number of parameters for %s\n", BPOptions.nodeSpecificDamping, this); _dampingParams = ArrayUtil.EMPTY_DOUBLE_ARRAY; } _dampingInUse = _dampingParams.length > 0; configureSavedMessages(size); } protected void configureSavedMessages(int size) { if (!_dampingInUse) { _savedOutMsgArray = ArrayUtil.EMPTY_DOUBLE_ARRAY_ARRAY; } else if (_savedOutMsgArray.length != size) { _savedOutMsgArray = new double[size][]; for (int i = 0; i < size; i++) { _savedOutMsgArray[i] = new double[_inputMsgs[i].length]; } } } }
yujianyuanhaha/Co-Channel-Sig-Detection
solvers/java/src/main/java/com/analog/lyric/dimple/solvers/sumproduct/SumProductTableFactor.java
7,507
//beliefs = getUnormalizedBelief();
line_comment
nl
/******************************************************************************* * Copyright 2012 Analog Devices, Inc. * * 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.analog.lyric.dimple.solvers.sumproduct; import static com.analog.lyric.math.Utilities.*; import java.util.Arrays; import java.util.Objects; import org.eclipse.jdt.annotation.Nullable; import com.analog.lyric.collect.ArrayUtil; import com.analog.lyric.collect.Selection; import com.analog.lyric.dimple.environment.DimpleEnvironment; import com.analog.lyric.dimple.exceptions.DimpleException; import com.analog.lyric.dimple.factorfunctions.core.FactorFunction; import com.analog.lyric.dimple.factorfunctions.core.FactorTableRepresentation; import com.analog.lyric.dimple.factorfunctions.core.IFactorTable; import com.analog.lyric.dimple.model.factors.Factor; import com.analog.lyric.dimple.model.variables.Variable; import com.analog.lyric.dimple.options.BPOptions; import com.analog.lyric.dimple.solvers.core.STableFactorDoubleArray; import com.analog.lyric.dimple.solvers.core.kbest.IKBestFactor; import com.analog.lyric.dimple.solvers.core.kbest.KBestFactorEngine; import com.analog.lyric.dimple.solvers.core.kbest.KBestFactorTableEngine; import com.analog.lyric.dimple.solvers.core.parameterizedMessages.DiscreteMessage; import com.analog.lyric.dimple.solvers.core.parameterizedMessages.DiscreteWeightMessage; import com.analog.lyric.dimple.solvers.interfaces.ISolverFactorGraph; import com.analog.lyric.dimple.solvers.interfaces.ISolverNode; import com.analog.lyric.dimple.solvers.optimizedupdate.FactorTableUpdateSettings; import com.analog.lyric.dimple.solvers.optimizedupdate.FactorUpdatePlan; import com.analog.lyric.dimple.solvers.optimizedupdate.ISTableFactorSupportingOptimizedUpdate; import com.analog.lyric.dimple.solvers.optimizedupdate.UpdateApproach; import com.analog.lyric.util.misc.Internal; /** * Solver representation of table factor under Sum-Product solver. * * @since 0.07 */ public class SumProductTableFactor extends STableFactorDoubleArray implements IKBestFactor, ISTableFactorSupportingOptimizedUpdate { /* * We cache all of the double arrays we use during the update. This saves * time when performing the update. */ protected double [][] _savedOutMsgArray = ArrayUtil.EMPTY_DOUBLE_ARRAY_ARRAY; protected @Nullable double [][][] _outPortDerivativeMsgs; protected double [] _dampingParams = ArrayUtil.EMPTY_DOUBLE_ARRAY; protected @Nullable TableFactorEngine _tableFactorEngine; protected KBestFactorEngine _kbestFactorEngine; protected int _k; protected boolean _kIsSmallerThanDomain = false; protected boolean _updateDerivative = false; protected boolean _dampingInUse = false; /*-------------- * Construction */ public SumProductTableFactor(Factor factor) { super(factor); //TODO: should I recheck for factor table every once in a while? if (factor.getFactorFunction().factorTableExists(getFactor())) { _kbestFactorEngine = new KBestFactorTableEngine(this); } else { _kbestFactorEngine = new KBestFactorEngine(this); } } @Override public void initialize() { super.initialize(); configureDampingFromOptions(); updateK(getOptionOrDefault(BPOptions.maxMessageSize)); } @Internal public void setupTableFactorEngine() { FactorUpdatePlan updatePlan = null; final FactorTableUpdateSettings factorTableUpdateSettings = getFactorTableUpdateSettings(); if (factorTableUpdateSettings != null) { updatePlan = factorTableUpdateSettings.getOptimizedUpdatePlan(); } if (updatePlan != null) { _tableFactorEngine = new TableFactorEngineOptimized(this, updatePlan); } else { _tableFactorEngine = new TableFactorEngine(this); } } @Internal @Nullable FactorTableUpdateSettings getFactorTableUpdateSettings() { ISolverFactorGraph rootGraph = getRootGraph(); if (rootGraph instanceof SumProductSolverGraph) { final SumProductSolverGraph sfg = (SumProductSolverGraph) getRootGraph(); if (sfg != null) { return sfg.getFactorTableUpdateSettings(getFactor()); } } return null; } /*--------------------- * ISolverNode methods */ @Override public void moveMessages(ISolverNode other, int portNum, int otherPort) { super.moveMessages(other,portNum,otherPort); SumProductTableFactor sother = (SumProductTableFactor)other; if (_dampingInUse) _savedOutMsgArray[portNum] = sother._savedOutMsgArray[otherPort]; } private TableFactorEngine getTableFactorEngine() { final TableFactorEngine tableFactorEngine = _tableFactorEngine; if (tableFactorEngine != null) { return tableFactorEngine; } else { throw new DimpleException("The solver was not initialized. Use solve() or call initialize() before iterate()."); } } @Override protected void doUpdate() { if (_kIsSmallerThanDomain) //TODO: damping _kbestFactorEngine.update(); else getTableFactorEngine().update(); if (_updateDerivative) for (int i = 0; i < _inputMsgs.length ;i++) updateDerivative(i); } @Override public void doUpdateEdge(int outPortNum) { if (_kIsSmallerThanDomain) _kbestFactorEngine.updateEdge(outPortNum); else getTableFactorEngine().updateEdge(outPortNum); if (_updateDerivative) updateDerivative(outPortNum); } /*----------------------- * ISolverFactor methods */ @Override public void createMessages() { super.createMessages(); } /* * (non-Javadoc) * @see com.analog.lyric.dimple.solvers.core.SFactorBase#getBelief() * * Calculates a piece of the beta free energy */ @Override public double [] getBelief() { double [] retval = getUnormalizedBelief(); double sum = 0; for (int i = 0; i < retval.length; i++) sum += retval[i]; for (int i = 0; i < retval.length; i++) retval[i] /= sum; return retval; } /*--------------- * SNode methods */ @Override public DiscreteMessage cloneMessage(int edge) { return new DiscreteWeightMessage(_outputMsgs[edge]); } /*-------------------------- * STableFactorBase methods */ @Override protected void setTableRepresentation(IFactorTable table) { table.setRepresentation(FactorTableRepresentation.SPARSE_WEIGHT_WITH_INDICES); } @Override public boolean supportsMessageEvents() { return true; } /*------------- * New methods */ @Deprecated public void setDamping(int index, double val) { double[] params = BPOptions.nodeSpecificDamping.getOrDefault(this).toPrimitiveArray(); if (params.length == 0 && val != 0.0) { params = new double[getSiblingCount()]; } if (params.length != 0) { params[index] = val; } BPOptions.nodeSpecificDamping.set(this, params); configureDampingFromOptions(); } @Override public double getDamping(int index) { return _dampingParams.length > 0 ? _dampingParams[index] : 0.0; } /** * Enables use of the optimized update algorithm on this factor, if its degree is greater than * 1. The optimized update algorithm is employed only when all of the factor's edges are updated * together with an update call. If the schedule instead uses update_edge, the algorithm is not * used. * <p> * This method is deprecated; instead set UpdateOptions.updateApproach. * * @since 0.06 */ @Deprecated public void enableOptimizedUpdate() { setOption(BPOptions.updateApproach, UpdateApproach.OPTIMIZED); } /** * Disables use of the optimized update algorithm on this factor. * <p> * This method is deprecated; instead set UpdateOptions.updateApproach. * * @see #enableOptimizedUpdate() * @since 0.06 */ @Deprecated public void disableOptimizedUpdate() { setOption(BPOptions.updateApproach, UpdateApproach.NORMAL); } /** * Reverts to the default setting for enabling of the optimized update algorithm, eliminating * the effect of previous calls to {@link #enableOptimizedUpdate()} or * {@link #disableOptimizedUpdate()}. * <p> * This method is deprecated; instead reset UpdateOptions.updateApproach. * * @since 0.06 */ @Deprecated public void useDefaultOptimizedUpdateEnable() { unsetOption(BPOptions.updateApproach); } /** * Returns the effective update approach for the factor. If the update approach is set to * automatic, this value is not valid until the graph is initialized. Note that a factor * with only one edge always employs the normal update approach. * * @since 0.07 */ public UpdateApproach getEffectiveUpdateApproach() { FactorTableUpdateSettings factorTableUpdateSettings = getFactorTableUpdateSettings(); if (factorTableUpdateSettings != null && factorTableUpdateSettings.getOptimizedUpdatePlan() != null) { return UpdateApproach.OPTIMIZED; } else { return UpdateApproach.NORMAL; } } @Internal public @Nullable UpdateApproach getAutomaticUpdateApproach() { FactorTableUpdateSettings updateSettings = getFactorTableUpdateSettings(); if (updateSettings != null) { return updateSettings.getAutomaticUpdateApproach(); } return null; } public int getK() { return _k; } public void setK(int k) { setOption(BPOptions.maxMessageSize, k); updateK(k); } private void updateK(int k) { if (k != _k) { _k = k; _kbestFactorEngine.setK(k); _kIsSmallerThanDomain = false; for (int i = 0; i < _inputMsgs.length; i++) { if (_inputMsgs[i] != null && _k < _inputMsgs[i].length) { _kIsSmallerThanDomain = true; break; } } } } public void setUpdateDerivative(boolean updateDer) { _updateDerivative = updateDer; } public double [] getUnormalizedBelief() { final int [][] table = getFactorTable().getIndicesSparseUnsafe(); final double [] values = getFactorTable().getWeightsSparseUnsafe(); final int nEntries = values.length; final double [] retval = new double[nEntries]; for (int i = 0; i < nEntries; i++) { retval[i] = values[i]; final int[] indices = table[i]; for (int j = 0; j < indices.length; j++) { retval[i] *= _inputMsgs[j][indices[j]]; } } return retval; } @Override public FactorFunction getFactorFunction() { return getFactor().getFactorFunction(); } @Override public double initAccumulator() { return 1; } @Override public double accumulate(double oldVal, double newVal) { return oldVal*newVal; } @Override public double combine(double oldVal, double newVal) { return oldVal+newVal; } @Override public void normalize(double[] outputMsg) { double sum = 0; for (int i = 0; i < outputMsg.length; i++) sum += outputMsg[i]; if (sum == 0) throw new DimpleException("Update failed in SumProduct Solver. All probabilities were zero when calculating message for port " + " on factor " +_factor.getLabel()); for (int i = 0; i < outputMsg.length; i++) outputMsg[i] /= sum; } @Override public double evalFactorFunction(Object[] inputs) { return getFactor().getFactorFunction().eval(inputs); } @Override public void initMsg(double[] msg) { Arrays.fill(msg, 0); } @Override public double getFactorTableValue(int index) { return getFactorTable().getWeightsSparseUnsafe()[index]; } @Override public int[] findKBestForMsg(double[] msg, int k) { return Selection.findLastKIndices(msg, k); } /****************************************************** * Energy, Entropy, and derivatives of all that. ******************************************************/ @Override public double getInternalEnergy() { final double [] beliefs = getBelief(); final double [] weights = getFactorTable().getWeightsSparseUnsafe(); double sum = 0; for (int i = beliefs.length; --i>=0;) { sum += beliefs[i] * weightToEnergy(weights[i]); } return sum; } @Override public double getBetheEntropy() { double sum = 0; final double [] beliefs = getBelief(); for (double belief : beliefs) { sum -= belief * Math.log(belief); } return sum; } @SuppressWarnings("null") public double calculateDerivativeOfInternalEnergyWithRespectToWeight(int weightIndex) { SumProductSolverGraph sfg = (SumProductSolverGraph)getRootGraph(); boolean isFactorOfInterest = sfg.getCurrentFactorTable() == getFactor().getFactorTable(); double [] weights = _factor.getFactorTable().getWeightsSparseUnsafe(); //TODO: avoid recompute double [] beliefs = getBelief(); double sum = 0; for (int i = 0; i < weights.length; i++) { //beliefs =<SUF> //Belief'(weightIndex)*(-log(weight(weightIndex))) + Belief(weightIndex)*(-log(weight(weightIndex)))' //(-log(weight(weightIndex)))' = - 1 / weight(weightIndex) double mlogweight = -Math.log(weights[i]); double belief = beliefs[i]; double mlogweightderivative = 0; if (i == weightIndex && isFactorOfInterest) mlogweightderivative = -1.0 / weights[weightIndex]; double beliefderivative = calculateDerivativeOfBeliefWithRespectToWeight(weightIndex,i,isFactorOfInterest); sum += beliefderivative*mlogweight + belief*mlogweightderivative; //sum += beliefderivative; } //return beliefderivative*mlogweight + belief*mlogweightderivative; return sum; } @SuppressWarnings("null") public double calculateDerivativeOfBeliefNumeratorWithRespectToWeight(int weightIndex, int index, boolean isFactorOfInterest) { double [] weights = _factor.getFactorTable().getWeightsSparseUnsafe(); int [][] indices = _factor.getFactorTable().getIndicesSparseUnsafe(); //calculate product of messages and phi double prod = weights[index]; for (int i = 0; i < _inputMsgs.length; i++) prod *= _inputMsgs[i][indices[index][i]]; double sum = 0; //if index == weightIndex, add in this term if (index == weightIndex && isFactorOfInterest) { sum = prod / weights[index]; } //for each variable for (int i = 0; i < _inputMsgs.length; i++) { SumProductDiscrete var = (SumProductDiscrete)getFactor().getConnectedNodesFlat().getByIndex(i).getSolver(); //divide out contribution sum += prod / _inputMsgs[i][indices[index][i]] * var.getMessageDerivative(weightIndex,getFactor())[indices[index][i]]; } return sum; } public double calculateDerivativeOfBeliefDenomenatorWithRespectToWeight(int weightIndex, int index, boolean isFactorOfInterest) { double sum = 0; for (int i = 0, end = getFactor().getFactorTable().sparseSize(); i < end; i++) sum += calculateDerivativeOfBeliefNumeratorWithRespectToWeight(weightIndex,i,isFactorOfInterest); return sum; } public double calculateDerivativeOfBeliefWithRespectToWeight(int weightIndex,int index, boolean isFactorOfInterest) { double [] un = getUnormalizedBelief(); double f = un[index]; double fderivative = calculateDerivativeOfBeliefNumeratorWithRespectToWeight(weightIndex, index,isFactorOfInterest); double gderivative = calculateDerivativeOfBeliefDenomenatorWithRespectToWeight(weightIndex, index,isFactorOfInterest); double g = 0; for (int i = 0; i < un.length; i++) g += un[i]; double tmp = (fderivative*g-f*gderivative)/(g*g); return tmp; } public void initializeDerivativeMessages(int weights) { final double[][][] msgs = _outPortDerivativeMsgs = new double[weights][_inputMsgs.length][]; for (int i = 0; i < weights; i++) for (int j = 0; j < _inputMsgs.length; j++) msgs[i][j] = new double[_inputMsgs[j].length]; } public double [] getMessageDerivative(int wn, Variable var) { int index = getFactor().getPortNum(var); return Objects.requireNonNull(_outPortDerivativeMsgs)[wn][index]; } public double calculateMessageForDomainValueAndTableIndex(int domainValue, int outPortNum, int tableIndex) { IFactorTable ft = getFactor().getFactorTable(); int [][] indices = ft.getIndicesSparseUnsafe(); double [] weights = ft.getWeightsSparseUnsafe(); if (indices[tableIndex][outPortNum] == domainValue) { double prod = weights[tableIndex]; for (int j = 0; j < _inputMsgs.length; j++) { if (outPortNum != j) { prod *= _inputMsgs[j][indices[tableIndex][j]]; } } return prod; } else return 0; } public double calculateMessageForDomainValue(int domainValue, int outPortNum) { IFactorTable ft = getFactor().getFactorTable(); double sum = 0; int [][] indices = ft.getIndicesSparseUnsafe(); for (int i = 0, end = ft.sparseSize(); i < end; i++) if (indices[i][outPortNum] == domainValue) sum += calculateMessageForDomainValueAndTableIndex(domainValue,outPortNum,i); return sum; } public double calculatedf(int outPortNum, int domainValue, int wn, boolean factorUsesTable) { IFactorTable ft = getFactor().getFactorTable(); double sum = 0; int [][] indices = ft.getIndicesSparseUnsafe(); double [] weights = ft.getWeightsSparseUnsafe(); for (int i = 0; i < indices.length; i++) { if (indices[i][outPortNum] == domainValue) { double prod = calculateMessageForDomainValueAndTableIndex(domainValue,outPortNum,i); if (factorUsesTable && (wn == i)) { sum += prod/weights[i]; } for (int j = 0; j < _inputMsgs.length; j++) { if (j != outPortNum) { SumProductDiscrete sv = (SumProductDiscrete)getFactor().getConnectedNodesFlat().getByIndex(j).getSolver(); @SuppressWarnings("null") double [] dvar = sv.getMessageDerivative(wn,getFactor()); sum += (prod / _inputMsgs[j][indices[i][j]]) * dvar[indices[i][j]]; } } } } return sum; } public double calculatedg(int outPortNum, int wn, boolean factorUsesTable) { double sum = 0; for (int i = 0; i < _inputMsgs[outPortNum].length; i++) sum += calculatedf(outPortNum,i,wn,factorUsesTable); return sum; } public void updateDerivativeForWeightAndDomain(int outPortNum, int wn, int d,boolean factorUsesTable) { //TODO: not re-using computation efficiently. //calculate f double f = calculateMessageForDomainValue(d,outPortNum); //calculate g double g = 0; for (int i = 0; i < _inputMsgs[outPortNum].length; i++) g += calculateMessageForDomainValue(i,outPortNum); double derivative = 0; if (g != 0) { double df = calculatedf(outPortNum,d,wn,factorUsesTable); double dg = calculatedg(outPortNum,wn,factorUsesTable); //derivative = df; derivative = (df*g - f*dg) / (g*g); } Objects.requireNonNull(_outPortDerivativeMsgs)[wn][outPortNum][d] = derivative; } public void updateDerivativeForWeight(int outPortNum, int wn,boolean factorUsesTable) { int D = _inputMsgs[outPortNum].length; for (int d = 0; d < D; d++) { updateDerivativeForWeightAndDomain(outPortNum,wn,d,factorUsesTable); } } public void updateDerivative(int outPortNum) { SumProductSolverGraph sfg = (SumProductSolverGraph)getRootGraph(); @SuppressWarnings("null") IFactorTable ft = sfg.getCurrentFactorTable(); @SuppressWarnings("null") int numWeights = ft.sparseSize(); for (int wn = 0; wn < numWeights; wn++) { updateDerivativeForWeight(outPortNum,wn,ft == getFactor().getFactorTable()); } } public double calculateDerivativeOfBetheEntropyWithRespectToWeight(int weightIndex) { @SuppressWarnings("null") boolean isFactorOfInterest = ((SumProductSolverGraph)getRootGraph()).getCurrentFactorTable() == getFactor().getFactorTable(); //Belief'(weightIndex)*(-log(Belief(weightIndex))) + Belief(weightIndex)*(-log(Belief(weightIndex)))' double [] beliefs = getBelief(); double sum = 0; for (int i = 0; i < beliefs.length; i++) { double beliefderivative = calculateDerivativeOfBeliefWithRespectToWeight(weightIndex,i,isFactorOfInterest); double belief = beliefs[i]; sum += beliefderivative*(-Math.log(belief)) - beliefderivative; } return sum; } @Override public double[][] getInPortMsgs() { return _inputMsgs; } @Override public double[][] getOutPortMsgs() { return _outputMsgs; } @Override public boolean isDampingInUse() { return _dampingInUse; } @Override public double[] getSavedOutMsgArray(int _outPortNum) { return _savedOutMsgArray[_outPortNum]; } /*------------------ * Internal methods */ protected void configureDampingFromOptions() { final int size = getSiblingCount(); _dampingParams = getReplicatedNonZeroListFromOptions(BPOptions.nodeSpecificDamping, BPOptions.damping, size, _dampingParams); if (_dampingParams.length > 0 && _dampingParams.length != size) { DimpleEnvironment.logWarning("%s has wrong number of parameters for %s\n", BPOptions.nodeSpecificDamping, this); _dampingParams = ArrayUtil.EMPTY_DOUBLE_ARRAY; } _dampingInUse = _dampingParams.length > 0; configureSavedMessages(size); } protected void configureSavedMessages(int size) { if (!_dampingInUse) { _savedOutMsgArray = ArrayUtil.EMPTY_DOUBLE_ARRAY_ARRAY; } else if (_savedOutMsgArray.length != size) { _savedOutMsgArray = new double[size][]; for (int i = 0; i < size; i++) { _savedOutMsgArray[i] = new double[_inputMsgs[i].length]; } } } }
173429_20
package com.smart.om.rest.base; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.googlecode.jsonplugin.JSONException; import com.googlecode.jsonplugin.JSONUtil; import com.smart.om.util.Const; /** * 封装调研设备接口 * @author langyuk * */ public class BaseController { private static final Logger logger = Logger.getLogger(BaseController.class); /** * 返回预期结果 */ private static final int RESULT_CODE_SUCCESS = 0; /** * 返回非预期结果 */ private static final int RESULT_CODE_ERROR = 1; /** * 服务端返回json的键名:结果代码 */ private static final String KEY_RESULT_CODE = "RESULT_CODE"; /** * 服务端返回json的键名:结果数据 */ private static final String KEY_RESULT_DATA = "RESULT_DATA"; /** * 调用外部接口 * @param param * @return */ public String extInf(String param,String requestMethod){ String result = ""; Map<String,String> map = new HashMap<String,String>(); String errInfo = "success"; String rTime=""; String str = ""; try{ long startTime = System.currentTimeMillis(); //请求起始时间_毫秒 URL url = new URL(Const.DEVICE_URL + param); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("contentType", "utf-8"); connection.setRequestMethod(requestMethod); //请求类型 POST or GET InputStream inStream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "utf-8")); //BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); long endTime = System.currentTimeMillis(); //请求结束时间_毫秒 String temp = ""; while((temp = in.readLine()) != null){ str = str + temp; } rTime = String.valueOf(endTime - startTime); } catch(Exception e){ errInfo = "error"; e.printStackTrace(); } result = str; return result; } /** * 调用外部接口POST * @param param * @return */ public String extInf(String urlStr,String param,String requestMethod){ String result = ""; Map<String,String> map = new HashMap<String,String>(); String errInfo = "success"; try{ long startTime = System.currentTimeMillis(); //请求起始时间_毫秒 URL url = new URL(Const.DEVICE_URL+urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST");//请求类型 POST or GET connection.setDoInput(true); connection.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); osw.write(param); osw.flush(); osw.close(); if(connection.getResponseCode() ==200){ BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } in.close(); } } catch(Exception e){ errInfo = "error"; e.printStackTrace(); } // result = str; return result; } /** 返回成功时,把Map转换成String **/ protected String toResultJsonSuccess(Object resultData) { return this.toResultJson(RESULT_CODE_SUCCESS, resultData); } /** 把Map转换成String **/ protected String toResultJson(int resultCode, Object resultData) { try { Map<Object, Object> map = new HashMap<Object, Object>(); map.put(KEY_RESULT_CODE, resultCode); map.put(KEY_RESULT_DATA, resultData); return JSONUtil.serialize(map); } catch (JSONException ex) { return "{\"" + KEY_RESULT_CODE + "\":" + RESULT_CODE_ERROR + ",\"" + KEY_RESULT_DATA + "\":\"转换为Json异常\"}"; } } /** 获得服务验证令牌 **/ public String getAccessToken(){ BaseController baseController = new BaseController(); String loginStr = baseController.extInf(Const.DEVICE_LOGIN,Const.REQUEST_METHOD_GET); JSONObject jsonObject=JSONObject.fromObject(loginStr); String accessKoken = jsonObject.getString("access_token"); return accessKoken; } /** 物料信息查询 **/ public String getFileName(String name,String msg){ String result = ""; StringBuffer param = new StringBuffer(); param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?"); param.append("pageIndex=1&pageSize=32767&"); param.append("access_token=" + this.getAccessToken()); param.append("&name=").append(name); String mediaInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET); if(StringUtils.isNotBlank(mediaInfo)){ JSONObject jsonObject = JSONObject.fromObject(mediaInfo); String mediaInfos = jsonObject.getString("MediaInfos"); System.out.println(mediaInfos); if(StringUtils.isNotBlank(mediaInfos)){ JSONArray jsonArray = JSONArray.fromObject(mediaInfos); if(jsonArray.size() > 0){ JSONObject json = jsonArray.getJSONObject(0); result = json.getString(msg); } } } return result; } /** 广告信息查询 **/ public String getAdvertMsg(String deviceNo,String msg){ String result = ""; StringBuffer param = new StringBuffer(); param.append("/PFPROWebAPI/api/JuicerApi/GetAdvertisingInfos?"); param.append("pageIndex=1&pageSize=10&StartTime=&EndTime=&"); param.append("access_token=" + this.getAccessToken()); param.append("&JuicerCode=").append(deviceNo); String advertInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET); if(StringUtils.isNotBlank(advertInfo)){ JSONObject jsonObject = JSONObject.fromObject(advertInfo); String mediaInfos = jsonObject.getString("Advertisings"); if(StringUtils.isNotBlank(mediaInfos)){ JSONArray jsonArray = JSONArray.fromObject(mediaInfos); if(jsonArray.size() > 0){ JSONObject json = jsonArray.getJSONObject(0); result = json.getString(msg); } } } return result; } /** 创建广告 **/ public void createAdvert(String startTime,String endTime,String juicerCode,String name){ System.out.println("name:" + name); String url = this.getFileName(name, "Url"); System.out.println("url:" + url); if(StringUtils.isNotBlank(url)){ String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.START_TIME + "=" + startTime + "&" + Const.END_TIME + "=" + endTime + "&" + Const.JUICER_CODE + "=" + juicerCode + "&" + Const.DOWN_LOAD_URL + "=" + url; this.extInf("PFPROWebAPI/api/JuicerApi/AddAdvertising", param, Const.REQUEST_METHOD_POST); } } /** 广告删除 **/ public void delAdvert(int code){ String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code; this.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST); } /** 删除物料 **/ public void delFile(int code){ String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code; this.extInf("PFPROWebAPI/api/JuicerApi/DelMediaInfo", param, Const.REQUEST_METHOD_POST); } public static void main(String[] args) { BaseController baseController = new BaseController(); String accessKoken = baseController.getAccessToken(); // StringBuffer param = new StringBuffer(); // String param = "Juicer?access_token="+accessKoken; // String deviceList = baseController.extInf(param, Const.REQUEST_METHOD_GET); // param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?"); // param.append("pageIndex=1&pageSize=32767&name=测试接口&"); // param.append("access_token=" + accessKoken); // String mediaInfo = baseController.extInf(param.toString(), Const.REQUEST_METHOD_GET); // JSONObject jsonObject = JSONObject.fromObject(mediaInfo); // String ss = jsonObject.getString("MediaInfos"); // JSONArray jsonArray = JSONArray.fromObject(ss); // JSONObject jsonObject2 = jsonArray.getJSONObject(0); // String s = jsonObject2.getString("Url"); // logger.info(s); // logger.info(mediaInfo); // String s = "接口测试"; // String url = baseController.getFileName("接口测试2","Url"); // System.out.println(url); // String code = baseController.getAdvertMsg("0000027", "Code"); // System.out.println(code); // String param = Const.ACCESS_TOKEN + "=" + baseController.getAccessToken() + "&" + Const.CODE + "=" + 97; // baseController.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST); // baseController.delAdvert(98); // baseController.delFile(62); baseController.createAdvert("2016-1-18 9:13", "2016-1-19 9:13", "0000027", "测试接口2"); } }
yujuekong/OM
src/main/com/smart/om/rest/base/BaseController.java
3,017
// JSONObject jsonObject2 = jsonArray.getJSONObject(0);
line_comment
nl
package com.smart.om.rest.base; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.googlecode.jsonplugin.JSONException; import com.googlecode.jsonplugin.JSONUtil; import com.smart.om.util.Const; /** * 封装调研设备接口 * @author langyuk * */ public class BaseController { private static final Logger logger = Logger.getLogger(BaseController.class); /** * 返回预期结果 */ private static final int RESULT_CODE_SUCCESS = 0; /** * 返回非预期结果 */ private static final int RESULT_CODE_ERROR = 1; /** * 服务端返回json的键名:结果代码 */ private static final String KEY_RESULT_CODE = "RESULT_CODE"; /** * 服务端返回json的键名:结果数据 */ private static final String KEY_RESULT_DATA = "RESULT_DATA"; /** * 调用外部接口 * @param param * @return */ public String extInf(String param,String requestMethod){ String result = ""; Map<String,String> map = new HashMap<String,String>(); String errInfo = "success"; String rTime=""; String str = ""; try{ long startTime = System.currentTimeMillis(); //请求起始时间_毫秒 URL url = new URL(Const.DEVICE_URL + param); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("contentType", "utf-8"); connection.setRequestMethod(requestMethod); //请求类型 POST or GET InputStream inStream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "utf-8")); //BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); long endTime = System.currentTimeMillis(); //请求结束时间_毫秒 String temp = ""; while((temp = in.readLine()) != null){ str = str + temp; } rTime = String.valueOf(endTime - startTime); } catch(Exception e){ errInfo = "error"; e.printStackTrace(); } result = str; return result; } /** * 调用外部接口POST * @param param * @return */ public String extInf(String urlStr,String param,String requestMethod){ String result = ""; Map<String,String> map = new HashMap<String,String>(); String errInfo = "success"; try{ long startTime = System.currentTimeMillis(); //请求起始时间_毫秒 URL url = new URL(Const.DEVICE_URL+urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST");//请求类型 POST or GET connection.setDoInput(true); connection.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); osw.write(param); osw.flush(); osw.close(); if(connection.getResponseCode() ==200){ BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } in.close(); } } catch(Exception e){ errInfo = "error"; e.printStackTrace(); } // result = str; return result; } /** 返回成功时,把Map转换成String **/ protected String toResultJsonSuccess(Object resultData) { return this.toResultJson(RESULT_CODE_SUCCESS, resultData); } /** 把Map转换成String **/ protected String toResultJson(int resultCode, Object resultData) { try { Map<Object, Object> map = new HashMap<Object, Object>(); map.put(KEY_RESULT_CODE, resultCode); map.put(KEY_RESULT_DATA, resultData); return JSONUtil.serialize(map); } catch (JSONException ex) { return "{\"" + KEY_RESULT_CODE + "\":" + RESULT_CODE_ERROR + ",\"" + KEY_RESULT_DATA + "\":\"转换为Json异常\"}"; } } /** 获得服务验证令牌 **/ public String getAccessToken(){ BaseController baseController = new BaseController(); String loginStr = baseController.extInf(Const.DEVICE_LOGIN,Const.REQUEST_METHOD_GET); JSONObject jsonObject=JSONObject.fromObject(loginStr); String accessKoken = jsonObject.getString("access_token"); return accessKoken; } /** 物料信息查询 **/ public String getFileName(String name,String msg){ String result = ""; StringBuffer param = new StringBuffer(); param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?"); param.append("pageIndex=1&pageSize=32767&"); param.append("access_token=" + this.getAccessToken()); param.append("&name=").append(name); String mediaInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET); if(StringUtils.isNotBlank(mediaInfo)){ JSONObject jsonObject = JSONObject.fromObject(mediaInfo); String mediaInfos = jsonObject.getString("MediaInfos"); System.out.println(mediaInfos); if(StringUtils.isNotBlank(mediaInfos)){ JSONArray jsonArray = JSONArray.fromObject(mediaInfos); if(jsonArray.size() > 0){ JSONObject json = jsonArray.getJSONObject(0); result = json.getString(msg); } } } return result; } /** 广告信息查询 **/ public String getAdvertMsg(String deviceNo,String msg){ String result = ""; StringBuffer param = new StringBuffer(); param.append("/PFPROWebAPI/api/JuicerApi/GetAdvertisingInfos?"); param.append("pageIndex=1&pageSize=10&StartTime=&EndTime=&"); param.append("access_token=" + this.getAccessToken()); param.append("&JuicerCode=").append(deviceNo); String advertInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET); if(StringUtils.isNotBlank(advertInfo)){ JSONObject jsonObject = JSONObject.fromObject(advertInfo); String mediaInfos = jsonObject.getString("Advertisings"); if(StringUtils.isNotBlank(mediaInfos)){ JSONArray jsonArray = JSONArray.fromObject(mediaInfos); if(jsonArray.size() > 0){ JSONObject json = jsonArray.getJSONObject(0); result = json.getString(msg); } } } return result; } /** 创建广告 **/ public void createAdvert(String startTime,String endTime,String juicerCode,String name){ System.out.println("name:" + name); String url = this.getFileName(name, "Url"); System.out.println("url:" + url); if(StringUtils.isNotBlank(url)){ String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.START_TIME + "=" + startTime + "&" + Const.END_TIME + "=" + endTime + "&" + Const.JUICER_CODE + "=" + juicerCode + "&" + Const.DOWN_LOAD_URL + "=" + url; this.extInf("PFPROWebAPI/api/JuicerApi/AddAdvertising", param, Const.REQUEST_METHOD_POST); } } /** 广告删除 **/ public void delAdvert(int code){ String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code; this.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST); } /** 删除物料 **/ public void delFile(int code){ String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code; this.extInf("PFPROWebAPI/api/JuicerApi/DelMediaInfo", param, Const.REQUEST_METHOD_POST); } public static void main(String[] args) { BaseController baseController = new BaseController(); String accessKoken = baseController.getAccessToken(); // StringBuffer param = new StringBuffer(); // String param = "Juicer?access_token="+accessKoken; // String deviceList = baseController.extInf(param, Const.REQUEST_METHOD_GET); // param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?"); // param.append("pageIndex=1&pageSize=32767&name=测试接口&"); // param.append("access_token=" + accessKoken); // String mediaInfo = baseController.extInf(param.toString(), Const.REQUEST_METHOD_GET); // JSONObject jsonObject = JSONObject.fromObject(mediaInfo); // String ss = jsonObject.getString("MediaInfos"); // JSONArray jsonArray = JSONArray.fromObject(ss); // JSONObject jsonObject2<SUF> // String s = jsonObject2.getString("Url"); // logger.info(s); // logger.info(mediaInfo); // String s = "接口测试"; // String url = baseController.getFileName("接口测试2","Url"); // System.out.println(url); // String code = baseController.getAdvertMsg("0000027", "Code"); // System.out.println(code); // String param = Const.ACCESS_TOKEN + "=" + baseController.getAccessToken() + "&" + Const.CODE + "=" + 97; // baseController.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST); // baseController.delAdvert(98); // baseController.delFile(62); baseController.createAdvert("2016-1-18 9:13", "2016-1-19 9:13", "0000027", "测试接口2"); } }
68722_20
// Copyright (C) 2013 Andrew Allen // // 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 prettify.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import prettify.parser.Prettify; /** * This is similar to the lang-erlang.js in JavaScript Prettify. * <p> * All comments are adapted from the JavaScript Prettify. * <p> * <p> * <p> * Derived from https://raw.github.com/erlang/otp/dev/lib/compiler/src/core_parse.yrl * Modified from Mike Samuel's Haskell plugin for google-code-prettify * * @author [email protected] */ public class LangErlang extends Lang { public LangErlang() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // Whitespace // whitechar -> newline | vertab | space | tab | uniWhite // newline -> return linefeed | return | linefeed | formfeed _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("\\t\\n\\x0B\\x0C\\r ]+"), null, "\t\n" + Character.toString((char) 0x0B) + Character.toString((char) 0x0C) + "\r "})); // Single line double-quoted strings. _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)"), null, "\""})); // Handle atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[a-z][a-zA-Z0-9_]*")})); // Handle single quoted atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])+\\'?"), null, "'"})); // Handle macros. Just to be extra clear on this one, it detects the ? // then uses the regexp to end it so be very careful about matching // all the terminal elements _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\?[^ \\t\\n({]+"), null, "?"})); // decimal -> digit{digit} // octal -> octit{octit} // hexadecimal -> hexit{hexit} // integer -> decimal // | 0o octal | 0O octal // | 0x hexadecimal | 0X hexadecimal // float -> decimal . decimal [exponent] // | decimal exponent // exponent -> (e | E) [+ | -] decimal _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)", Pattern.CASE_INSENSITIVE), null, "0123456789"})); // TODO: catch @declarations inside comments // Comments in erlang are started with % and go till a newline _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n\\r]*")})); // Catch macros //[PR['PR_TAG'], /?[^( \n)]+/], /** * %% Keywords (atoms are assumed to always be single-quoted). * 'module' 'attributes' 'do' 'let' 'in' 'letrec' * 'apply' 'call' 'primop' * 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after' */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\\b")})); /** * Catch definitions (usually defined at the top of the file) * Anything that starts -something */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-[a-z_]+")})); // Catch variables _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_TYPE, Pattern.compile("^[A-Z_][a-zA-Z0-9_]*")})); // matches the symbol production _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[.,;]")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"erlang", "erl"}); } }
yydcdut/RxMarkdown
markdown-processor/src/main/java/prettify/lang/LangErlang.java
1,633
// integer -> decimal
line_comment
nl
// Copyright (C) 2013 Andrew Allen // // 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 prettify.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import prettify.parser.Prettify; /** * This is similar to the lang-erlang.js in JavaScript Prettify. * <p> * All comments are adapted from the JavaScript Prettify. * <p> * <p> * <p> * Derived from https://raw.github.com/erlang/otp/dev/lib/compiler/src/core_parse.yrl * Modified from Mike Samuel's Haskell plugin for google-code-prettify * * @author [email protected] */ public class LangErlang extends Lang { public LangErlang() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // Whitespace // whitechar -> newline | vertab | space | tab | uniWhite // newline -> return linefeed | return | linefeed | formfeed _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("\\t\\n\\x0B\\x0C\\r ]+"), null, "\t\n" + Character.toString((char) 0x0B) + Character.toString((char) 0x0C) + "\r "})); // Single line double-quoted strings. _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)"), null, "\""})); // Handle atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[a-z][a-zA-Z0-9_]*")})); // Handle single quoted atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])+\\'?"), null, "'"})); // Handle macros. Just to be extra clear on this one, it detects the ? // then uses the regexp to end it so be very careful about matching // all the terminal elements _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\?[^ \\t\\n({]+"), null, "?"})); // decimal -> digit{digit} // octal -> octit{octit} // hexadecimal -> hexit{hexit} // integer <SUF> // | 0o octal | 0O octal // | 0x hexadecimal | 0X hexadecimal // float -> decimal . decimal [exponent] // | decimal exponent // exponent -> (e | E) [+ | -] decimal _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)", Pattern.CASE_INSENSITIVE), null, "0123456789"})); // TODO: catch @declarations inside comments // Comments in erlang are started with % and go till a newline _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n\\r]*")})); // Catch macros //[PR['PR_TAG'], /?[^( \n)]+/], /** * %% Keywords (atoms are assumed to always be single-quoted). * 'module' 'attributes' 'do' 'let' 'in' 'letrec' * 'apply' 'call' 'primop' * 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after' */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\\b")})); /** * Catch definitions (usually defined at the top of the file) * Anything that starts -something */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-[a-z_]+")})); // Catch variables _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_TYPE, Pattern.compile("^[A-Z_][a-zA-Z0-9_]*")})); // matches the symbol production _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[.,;]")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"erlang", "erl"}); } }
123213_6
package com.zy.devicesinfo.data; import static com.zy.devicesinfo.utils.GeneralUtils.getSimCardInfo; import static com.zy.devicesinfo.utils.OtherUtils.isNetState; import static com.zy.devicesinfo.utils.StorageQueryUtil.queryWithStorageManager; import com.zy.devicesinfo.UtilsApp; import com.zy.devicesinfo.utils.NetWorkUtils; import com.zy.devicesinfo.utils.OtherUtils; public class DeviceInfos { // HardwareData dhoamrpdewtare = new HardwareData(); // MediaFilesData dmoemdpieat = new MediaFilesData(); // OtherData dootmhpeert = new OtherData(); // SimCardData dsoimmpet = getSimCardInfo(); // StorageData dsotmopreatge = new StorageData(); // LocationAddressData dgopmspet = new LocationAddressData(); // NetWorkData dnoemtpweotrk = NetWorkUtils.getNetWorkInfo(new NetWorkData()); // SensorData dsoemnpseotr = OtherUtils.getSensorList(new SensorData()); // BatteryStatusData dboamtpteetry = UtilsApp.batteryStatusData; // GeneralData dgoemnpeertal = new GeneralData(); HardwareData hardwareData = new HardwareData(); MediaFilesData mediaFilesData = new MediaFilesData(); OtherData otherData = new OtherData(); SimCardData simCardData = getSimCardInfo(); StorageData storageData = queryWithStorageManager(new StorageData()); LocationAddressData locationAddressData = new LocationAddressData(); NetWorkData netWorkData = null; SensorData sensorDataList = OtherUtils.getSensorList(new SensorData()); BatteryStatusData batteryStatusData = UtilsApp.batteryStatusData; GeneralData generalData = new GeneralData(); //List<ContactData> contalist = new ContactData().getContactList(new ArrayList<ContactData>()); // List<AppListData> appListData = new AppListData().getAppListData(new ArrayList<AppListData>()); { if (isNetState() == 1) { netWorkData = NetWorkUtils.getNetWorkInfo(new NetWorkData()); } } }
z244370114/devicesinfo
android/src/main/kotlin/com/zy/devicesinfo/data/DeviceInfos.java
578
// NetWorkData dnoemtpweotrk = NetWorkUtils.getNetWorkInfo(new NetWorkData());
line_comment
nl
package com.zy.devicesinfo.data; import static com.zy.devicesinfo.utils.GeneralUtils.getSimCardInfo; import static com.zy.devicesinfo.utils.OtherUtils.isNetState; import static com.zy.devicesinfo.utils.StorageQueryUtil.queryWithStorageManager; import com.zy.devicesinfo.UtilsApp; import com.zy.devicesinfo.utils.NetWorkUtils; import com.zy.devicesinfo.utils.OtherUtils; public class DeviceInfos { // HardwareData dhoamrpdewtare = new HardwareData(); // MediaFilesData dmoemdpieat = new MediaFilesData(); // OtherData dootmhpeert = new OtherData(); // SimCardData dsoimmpet = getSimCardInfo(); // StorageData dsotmopreatge = new StorageData(); // LocationAddressData dgopmspet = new LocationAddressData(); // NetWorkData dnoemtpweotrk<SUF> // SensorData dsoemnpseotr = OtherUtils.getSensorList(new SensorData()); // BatteryStatusData dboamtpteetry = UtilsApp.batteryStatusData; // GeneralData dgoemnpeertal = new GeneralData(); HardwareData hardwareData = new HardwareData(); MediaFilesData mediaFilesData = new MediaFilesData(); OtherData otherData = new OtherData(); SimCardData simCardData = getSimCardInfo(); StorageData storageData = queryWithStorageManager(new StorageData()); LocationAddressData locationAddressData = new LocationAddressData(); NetWorkData netWorkData = null; SensorData sensorDataList = OtherUtils.getSensorList(new SensorData()); BatteryStatusData batteryStatusData = UtilsApp.batteryStatusData; GeneralData generalData = new GeneralData(); //List<ContactData> contalist = new ContactData().getContactList(new ArrayList<ContactData>()); // List<AppListData> appListData = new AppListData().getAppListData(new ArrayList<AppListData>()); { if (isNetState() == 1) { netWorkData = NetWorkUtils.getNetWorkInfo(new NetWorkData()); } } }
212016_12
package org.tmotte.klonk.windows.popup; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.ListCellRenderer; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.tmotte.common.swang.CurrentOS; import org.tmotte.common.swang.GridBug; import org.tmotte.common.swang.KeyMapper; import org.tmotte.common.swang.MinimumFont; import org.tmotte.common.swang.Radios; import org.tmotte.klonk.config.PopupInfo; import org.tmotte.klonk.config.msg.Setter; import org.tmotte.klonk.config.option.FontOptions; import org.tmotte.klonk.edit.MyTextArea; import org.tmotte.klonk.windows.Positioner; public class FontPicker { ///////////////////////// // INSTANCE VARIABLES: // ///////////////////////// // DI: private PopupInfo pInfo; private Setter<String> alerter; private FontOptions fontOptions; // State: private boolean ok=false; private Map<String,Font> goodFonts, badFonts; private Color selectedForeground, selectedBackground, selectedCaret; private boolean initialized=false; private boolean shownBefore=false; private DefaultListModel<String> fontNameData; private DefaultListModel<Integer> fontSizeData; private JList<String> jlFonts; private JList<Integer> jlFontSize; // Controls: private JDialog win; private JScrollPane jspFonts, jspFontSize; private JButton btnOK, btnCancel; private JColorChooser colorChooser; private MyTextArea mta; private JScrollPane jspMTA; private JRadioButton jrbForeground, jrbBackground, jrbCaret; private JCheckBox jcbBold, jcbItalic; private JSpinner jspControlSize, jspCaretWidth; private JLabel jlCFO, jlEFO; ///////////////////// // PUBLIC METHODS: // ///////////////////// public FontPicker(PopupInfo pInfo, Setter<String> alerter) { this.pInfo=pInfo; this.alerter=alerter; } public boolean show(FontOptions fontOptions) { init(); prepare(fontOptions); while (true){ ok=false; win.setVisible(true); win.toFront(); if (!ok) return false; if (jlFonts.isSelectionEmpty()) alerter.set("No font selected"); else if (jlFontSize.isSelectionEmpty()) alerter.set("No font size selected"); else { fontOptions.setFontName(jlFonts.getSelectedValue()); fontOptions.setFontSize(jlFontSize.getSelectedValue()); fontOptions.setFontStyle(getSelectedStyle()); fontOptions.setControlsFont(Integer.parseInt(jspControlSize.getValue().toString())); fontOptions.setColor(selectedForeground); fontOptions.setBackgroundColor(selectedBackground); fontOptions.setCaretColor(selectedCaret); fontOptions.setCaretWidth(Integer.parseInt(jspCaretWidth.getValue().toString())); return true; } } } //////////////////////// // // // PRIVATE METHODS: // // // //////////////////////// private void prepare(FontOptions fontOptions) { //Basic initialization: this.fontOptions=fontOptions; //General fonts: fontOptions.getControlsFont().set(win); jspControlSize.setValue(fontOptions.getControlsFont().getSize()); //Set font name, size: { final int i=fontNameData.indexOf(fontOptions.getFont().getFamily()); if (i!=-1) { jlFonts.setSelectedIndex(i); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { jlFonts.ensureIndexIsVisible(i); } }); } } { final int i=fontSizeData.indexOf(fontOptions.getFontSize()); if (i!=-1) { jlFontSize.setSelectedIndex(i); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { jlFontSize.ensureIndexIsVisible(i); } }); } } //Set up color: selectedForeground=fontOptions.getColor(); selectedBackground=fontOptions.getBackgroundColor(); selectedCaret =fontOptions.getCaretColor(); setColorChooserColor(); //Set up style: jcbBold.setSelected((fontOptions.getFontStyle() & Font.BOLD) > 0); jcbItalic.setSelected((fontOptions.getFontStyle() & Font.ITALIC) > 0); //Caret width jspCaretWidth.setValue(fontOptions.getCaretWidth()); //Set up text area: mta.setFont(fontOptions.getFont()); mta.setRows(4); mta.setForeground(fontOptions.getColor()); mta.setBackground(fontOptions.getBackgroundColor()); mta.setCaretColor(fontOptions.getCaretColor()); mta.setCaretWidth(fontOptions.getCaretWidth()); if (!shownBefore) { win.pack(); shownBefore=true; } Positioner.set(pInfo.parentFrame, win, false); } /** action=true means OK, false means Cancel */ private void click(boolean action) { ok=action; win.setVisible(false); } private void changeFont() { int size=Integer.parseInt(jspControlSize.getValue().toString()); new MinimumFont(size).set(win); new MinimumFont(size + 2).set(jlCFO, jlEFO); if (mta==null || jlFonts==null || jlFontSize==null || jlFonts.isSelectionEmpty() || jlFontSize.isSelectionEmpty()) return; mta.setFont( new Font( jlFonts.getSelectedValue(), getSelectedStyle(), jlFontSize.getSelectedValue()) ); mta.setCaretWidth(Integer.parseInt(jspCaretWidth.getValue().toString())); } ///////////// // CREATE: // ///////////// private void init() { if (!initialized) { create(); layout(); listen(); initialized=true; } } private void create(){ win=new JDialog(pInfo.parentFrame, true); win.setTitle("Font Options"); jlCFO=new JLabel("General Font Options:"); jlCFO.setFont(jlCFO.getFont().deriveFont(Font.BOLD)); jspControlSize=new JSpinner(new SpinnerNumberModel(1,1,99,1)); jlEFO=new JLabel("Editor Font Options:"); jlEFO.setFont(jlEFO.getFont().deriveFont(Font.BOLD)); goodFonts=new HashMap<>(); badFonts =new HashMap<>(); fontNameData=new DefaultListModel<>(); fontSizeData=new DefaultListModel<>(); jlFonts=new JList<>(fontNameData); jlFonts.setVisibleRowCount(-1); jlFonts.setCellRenderer(new MyFontRenderer(jlFonts.getFont())); jspFonts = new JScrollPane(jlFonts); for (Font f: GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()){ String name=f.getFamily(); if (goodFonts.get(name)==null && f.canDisplayUpTo("abcdefgh")==-1){ fontNameData.addElement(name); f=f.deriveFont(0, 14); goodFonts.put(name, f); } } jlFontSize=new JList<>(fontSizeData); jlFontSize.setVisibleRowCount(6); jspFontSize = new JScrollPane(jlFontSize); for (int i=5; i<40; i++) fontSizeData.addElement(i); jcbBold=new JCheckBox("Bold"); jcbBold.setFont(jcbBold.getFont().deriveFont(Font.BOLD)); jcbBold.setMnemonic(KeyEvent.VK_B); jcbItalic=new JCheckBox("Italic"); jcbItalic.setFont(jcbItalic.getFont().deriveFont(Font.ITALIC)); jcbItalic.setMnemonic(KeyEvent.VK_I); jspCaretWidth=new JSpinner(new SpinnerNumberModel(1,1,99,1)); jrbForeground=new JRadioButton("Foreground"); jrbForeground.setMnemonic(KeyEvent.VK_O); jrbForeground.setSelected(true); jrbBackground=new JRadioButton("Background"); jrbBackground.setMnemonic(KeyEvent.VK_A); jrbCaret=new JRadioButton("Caret"); jrbCaret.setMnemonic(KeyEvent.VK_T); Radios.doLeftRightArrows(Radios.create(jrbForeground, jrbBackground, jrbCaret)); colorChooser=new JColorChooser(); //This eliminates the preview so we can customize: colorChooser.setPreviewPanel(new JPanel()); mta=new MyTextArea(pInfo.currentOS); mta.setRows(4);//This doesn't work right because we set the font different. mta.setLineWrap(false); mta.setWrapStyleWord(false); jspMTA=mta.makeVerticalScrollable(); mta.setText("The quick brown fox jumped over the lazy dog.\n Fourscore and seven years ago..." +"\n One day Chicken Little was walking in the woods when -" +"\n1234567890 < > ? ! / \\ | , . : ; { } [ ] ( ) - + = @ # $ % ^ & * ~ `" ); btnOK =new JButton("OK"); btnOK.setMnemonic(KeyEvent.VK_K); btnCancel=new JButton("Cancel"); btnCancel.setMnemonic(KeyEvent.VK_C); } private class MyFontRenderer extends JLabel implements ListCellRenderer<String> { private Font defaultFont; Color badColor=new Color(230, 100, 100); public MyFontRenderer(Font defaultFont) { this.defaultFont=defaultFont; setOpaque(true); } public Component getListCellRendererComponent( JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus ) { Font font=badFonts.get(value); boolean isBad=font!=null; if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(isBad ?badColor :list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(isBad ?badColor :list.getForeground()); } font=null; if (!isBad) font=goodFonts.get(value); if (font==null) font=defaultFont; this.setFont(font); setText(value); return this; } } ///////////// // LAYOUT: // ///////////// private void layout() { GridBug gb=new GridBug(win); gb.gridXY(0); gb.weightXY(0); gb.setInsets(5, 5, 0, 5); gb.fill=gb.BOTH; gb.anchor=gb.NORTHWEST; gb.addY(layoutTop()); gb.fill=gb.BOTH; gb.weightXY(1); gb.addY(layoutBottom()); win.pack(); } private JPanel layoutTop() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.gridXY(0); gb.weightXY(0); gb.fill=gb.BOTH; gb.anchor=gb.NORTHWEST; gb.setInsets(5); gb.insets.top=0; // Title: gb.gridwidth=2; gb.setX(0); gb.addX(jlCFO); gb.gridwidth=1; // Spinner: gb.insets.top=0; gb.insets.left=20; gb.setX(0).setY(1); gb.gridXY(0, 2); gb.weightXY(0, 1); gb.fill=gb.NONE; gb.add(jspControlSize); // Spinner label; gb.insets.left=4; gb.fill=gb.VERTICAL; gb.weightXY(1, 0); gb.addX(new JLabel("Minimum font size for various controls")); return jp; } private JPanel layoutBottom() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.gridXY(0); gb.weightXY(0); gb.anchor=gb.NORTHWEST; // Label: gb.insets.top=0; gb.insets.left=5; gb.addY(jlEFO); // Font name, size< style: gb.fill=gb.BOTH; gb.insets.left=20; gb.weightXY(0, 0.3); gb.addY(getEditorFontSelectionPanel()); // Colors: gb.insets.top=5; gb.weightXY(1, 0); gb.fill=gb.HORIZONTAL; gb.addY(getColorPanel()); // Preview: gb.insets.top=0; gb.weightXY(1, 0.7); gb.fill=gb.BOTH; gb.addY(getPreviewPanel()); // Buttons: gb.weightXY(1, 0); gb.fill=gb.HORIZONTAL; gb.addY(getButtonPanel()); return jp; } private JPanel getEditorFontSelectionPanel() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.anchor=gb.WEST; gb.weightXY(0.1, 1); gb.fill=gb.BOTH; gb.add(getFontListPanel()); gb.insets.left=10; gb.weightx=0; gb.addX(getFontSizePanel()); gb.weightx=0; gb.fill=gb.VERTICAL; gb.addX(getFontStylePanel()); return jp; } private JPanel getFontListPanel() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.weightXY(0).gridXY(0); gb.anchor=gb.WEST; JLabel label=new JLabel("Font:"); label.setDisplayedMnemonic(KeyEvent.VK_F); label.setLabelFor(jlFonts); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.insets.top=10; gb.insets.left=5; gb.insets.right=5; gb.add(label); gb.weightXY(1); gb.insets.top=0; gb.fill=gb.BOTH; gb.addY(jspFonts); return jp; } private JPanel getFontSizePanel(){ JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.NORTHWEST; gb.insets.left=5; gb.insets.right=5; gb.weightXY(1,0); JLabel label=new JLabel("Font Size:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); label.setDisplayedMnemonic(KeyEvent.VK_Z); label.setLabelFor(jlFontSize); gb.insets.top=10; gb.add(label); gb.weightXY(1); gb.insets.top=0; gb.fill=gb.BOTH; gb.addY(jspFontSize); return panel; } private JPanel getFontStylePanel(){ JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.NORTHWEST; gb.insets.left=5; gb.insets.right=5; { gb.weightXY(1,0); JLabel label=new JLabel("Font Style:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.insets.top=10; gb.add(label); } gb.insets.top=0; gb.fill=gb.NONE; gb.addY(jcbBold); gb.weightXY(1,0); gb.addY(jcbItalic); { gb.weightXY(1,0); JLabel label=new JLabel("Caret Width:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.insets.top=10; gb.addY(label); } gb.insets.top=0; gb.fill=gb.NONE; gb.weightXY(1,1); gb.addY(jspCaretWidth); return panel; } private JPanel getColorPanel() { JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.NORTHWEST; gb.insets.left=5; gb.insets.right=5; gb.weightXY(1, 0); gb.insets.top=5; gb.fill=gb.HORIZONTAL; gb.anchor=gb.WEST; gb.add(getColorTopPanel()); gb.insets.top=0; gb.addY(colorChooser); return panel; } private JPanel getColorTopPanel() { JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.WEST; JLabel label=new JLabel("Color:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.add(label); gb.insets.left=5; gb.addX(jrbForeground); gb.addX(jrbBackground); gb.weightx=1; gb.addX(jrbCaret); return panel; } private JPanel getPreviewPanel() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.weightXY(0).gridXY(0); gb.anchor=gb.WEST; JLabel label=new JLabel("Preview:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); label.setDisplayedMnemonic(KeyEvent.VK_P); label.setLabelFor(jspMTA); gb.insets.top=10; gb.insets.left=5; gb.insets.right=5; gb.add(label); gb.weightXY(1); gb.insets.top=0; gb.fill=gb.BOTH; gb.addY(jspMTA); return jp; } private JPanel getButtonPanel() { JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); Insets insets=gb.insets; insets.top=5; insets.bottom=5; insets.left=5; insets.right=5; gb.gridx=0; gb.add(btnOK); gb.addX(btnCancel); return panel; } ///////////// // LISTEN: // ///////////// private void listen() { //Controls font size change: { ChangeListener styleListen=new ChangeListener(){ public void stateChanged(ChangeEvent ce) { new MinimumFont(Integer.parseInt(jspControlSize.getValue().toString())); changeFont(); } }; jspControlSize.addChangeListener(styleListen); } //Font name & size change: { ListSelectionListener lsl=new ListSelectionListener(){ public void valueChanged(ListSelectionEvent lse) { changeFont(); } }; jlFonts.addListSelectionListener(lsl); jlFontSize.addListSelectionListener(lsl); } //Font style change: { ChangeListener styleListen=new ChangeListener(){ public void stateChanged(ChangeEvent ce) { changeFont(); } }; jcbBold.addChangeListener(styleListen); jcbItalic.addChangeListener(styleListen); } //Caret width change: { ChangeListener listen=new ChangeListener(){ public void stateChanged(ChangeEvent ce) { changeFont(); } }; jspCaretWidth.addChangeListener(listen); } //Color chooser radio button change: { ActionListener clisten=new ActionListener(){ public void actionPerformed(ActionEvent ce) { setColorChooserColor(); } }; jrbForeground.addActionListener(clisten); jrbBackground.addActionListener(clisten); jrbCaret.addActionListener(clisten); } //Color change: colorChooser.getSelectionModel().addChangeListener(new ChangeListener(){ public void stateChanged(ChangeEvent ce) { if (jrbForeground==null || jrbBackground==null || jrbCaret==null || mta==null) return; if (jrbForeground.isSelected()){ selectedForeground=colorChooser.getColor(); mta.setForeground(selectedForeground); } else if (jrbBackground.isSelected()) { selectedBackground=colorChooser.getColor(); mta.setBackground(selectedBackground); } else if (jrbCaret.isSelected()) { selectedCaret=colorChooser.getColor(); mta.setCaretColor(selectedCaret); } } }); mta.addKeyListener(textAreaListener); //Button clicks: Action okAction=new AbstractAction() { public void actionPerformed(ActionEvent event) {click(true);} }; btnOK.addActionListener(okAction); // This means clicking enter anywhere activates ok KeyMapper.accel(btnOK, okAction, KeyMapper.key(KeyEvent.VK_ENTER)); Action cancelAction=new AbstractAction() { public void actionPerformed(ActionEvent event) {click(false);} }; btnCancel.addActionListener(cancelAction); KeyMapper.easyCancel(btnCancel, cancelAction); } private void setColorChooserColor() { if (colorChooser==null || jrbForeground==null || jrbBackground==null || jrbCaret==null) return; if (jrbForeground.isSelected()) colorChooser.setColor(selectedForeground); else if (jrbBackground.isSelected()) colorChooser.setColor(selectedBackground); else if (jrbCaret.isSelected()) colorChooser.setColor(selectedCaret); } private int getSelectedStyle() { return Font.PLAIN | (jcbBold.isSelected() ?Font.BOLD :0) | (jcbItalic.isSelected() ?Font.ITALIC :0); } /** Listening to the textareas for tab & enter keys: */ private KeyAdapter textAreaListener=new KeyAdapter() { public void keyPressed(KeyEvent e){ final int code=e.getKeyCode(); if (code==e.VK_TAB) { int mods=e.getModifiersEx(); if (KeyMapper.shiftPressed(mods)) colorChooser.requestFocusInWindow(); else btnOK.requestFocusInWindow(); e.consume(); } } }; ///////////// /// TEST: /// ///////////// public static void main(final String[] args) throws Exception { javax.swing.SwingUtilities.invokeLater(()->{ try { PopupTestContext ptc=new PopupTestContext(); FontOptions fo=new FontOptions(); System.out.println("Before: "+fo); new FontPicker( ptc.getPopupInfo(), s->System.out.println("!!!!\n"+s+"\n!!!!") ).show(fo); System.out.println("After: "+fo); } catch (Exception e) { e.printStackTrace(); } }); } }
zaboople/klonk
java/org/tmotte/klonk/windows/popup/FontPicker.java
7,513
//Font name & size change:
line_comment
nl
package org.tmotte.klonk.windows.popup; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.ListCellRenderer; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.tmotte.common.swang.CurrentOS; import org.tmotte.common.swang.GridBug; import org.tmotte.common.swang.KeyMapper; import org.tmotte.common.swang.MinimumFont; import org.tmotte.common.swang.Radios; import org.tmotte.klonk.config.PopupInfo; import org.tmotte.klonk.config.msg.Setter; import org.tmotte.klonk.config.option.FontOptions; import org.tmotte.klonk.edit.MyTextArea; import org.tmotte.klonk.windows.Positioner; public class FontPicker { ///////////////////////// // INSTANCE VARIABLES: // ///////////////////////// // DI: private PopupInfo pInfo; private Setter<String> alerter; private FontOptions fontOptions; // State: private boolean ok=false; private Map<String,Font> goodFonts, badFonts; private Color selectedForeground, selectedBackground, selectedCaret; private boolean initialized=false; private boolean shownBefore=false; private DefaultListModel<String> fontNameData; private DefaultListModel<Integer> fontSizeData; private JList<String> jlFonts; private JList<Integer> jlFontSize; // Controls: private JDialog win; private JScrollPane jspFonts, jspFontSize; private JButton btnOK, btnCancel; private JColorChooser colorChooser; private MyTextArea mta; private JScrollPane jspMTA; private JRadioButton jrbForeground, jrbBackground, jrbCaret; private JCheckBox jcbBold, jcbItalic; private JSpinner jspControlSize, jspCaretWidth; private JLabel jlCFO, jlEFO; ///////////////////// // PUBLIC METHODS: // ///////////////////// public FontPicker(PopupInfo pInfo, Setter<String> alerter) { this.pInfo=pInfo; this.alerter=alerter; } public boolean show(FontOptions fontOptions) { init(); prepare(fontOptions); while (true){ ok=false; win.setVisible(true); win.toFront(); if (!ok) return false; if (jlFonts.isSelectionEmpty()) alerter.set("No font selected"); else if (jlFontSize.isSelectionEmpty()) alerter.set("No font size selected"); else { fontOptions.setFontName(jlFonts.getSelectedValue()); fontOptions.setFontSize(jlFontSize.getSelectedValue()); fontOptions.setFontStyle(getSelectedStyle()); fontOptions.setControlsFont(Integer.parseInt(jspControlSize.getValue().toString())); fontOptions.setColor(selectedForeground); fontOptions.setBackgroundColor(selectedBackground); fontOptions.setCaretColor(selectedCaret); fontOptions.setCaretWidth(Integer.parseInt(jspCaretWidth.getValue().toString())); return true; } } } //////////////////////// // // // PRIVATE METHODS: // // // //////////////////////// private void prepare(FontOptions fontOptions) { //Basic initialization: this.fontOptions=fontOptions; //General fonts: fontOptions.getControlsFont().set(win); jspControlSize.setValue(fontOptions.getControlsFont().getSize()); //Set font name, size: { final int i=fontNameData.indexOf(fontOptions.getFont().getFamily()); if (i!=-1) { jlFonts.setSelectedIndex(i); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { jlFonts.ensureIndexIsVisible(i); } }); } } { final int i=fontSizeData.indexOf(fontOptions.getFontSize()); if (i!=-1) { jlFontSize.setSelectedIndex(i); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { jlFontSize.ensureIndexIsVisible(i); } }); } } //Set up color: selectedForeground=fontOptions.getColor(); selectedBackground=fontOptions.getBackgroundColor(); selectedCaret =fontOptions.getCaretColor(); setColorChooserColor(); //Set up style: jcbBold.setSelected((fontOptions.getFontStyle() & Font.BOLD) > 0); jcbItalic.setSelected((fontOptions.getFontStyle() & Font.ITALIC) > 0); //Caret width jspCaretWidth.setValue(fontOptions.getCaretWidth()); //Set up text area: mta.setFont(fontOptions.getFont()); mta.setRows(4); mta.setForeground(fontOptions.getColor()); mta.setBackground(fontOptions.getBackgroundColor()); mta.setCaretColor(fontOptions.getCaretColor()); mta.setCaretWidth(fontOptions.getCaretWidth()); if (!shownBefore) { win.pack(); shownBefore=true; } Positioner.set(pInfo.parentFrame, win, false); } /** action=true means OK, false means Cancel */ private void click(boolean action) { ok=action; win.setVisible(false); } private void changeFont() { int size=Integer.parseInt(jspControlSize.getValue().toString()); new MinimumFont(size).set(win); new MinimumFont(size + 2).set(jlCFO, jlEFO); if (mta==null || jlFonts==null || jlFontSize==null || jlFonts.isSelectionEmpty() || jlFontSize.isSelectionEmpty()) return; mta.setFont( new Font( jlFonts.getSelectedValue(), getSelectedStyle(), jlFontSize.getSelectedValue()) ); mta.setCaretWidth(Integer.parseInt(jspCaretWidth.getValue().toString())); } ///////////// // CREATE: // ///////////// private void init() { if (!initialized) { create(); layout(); listen(); initialized=true; } } private void create(){ win=new JDialog(pInfo.parentFrame, true); win.setTitle("Font Options"); jlCFO=new JLabel("General Font Options:"); jlCFO.setFont(jlCFO.getFont().deriveFont(Font.BOLD)); jspControlSize=new JSpinner(new SpinnerNumberModel(1,1,99,1)); jlEFO=new JLabel("Editor Font Options:"); jlEFO.setFont(jlEFO.getFont().deriveFont(Font.BOLD)); goodFonts=new HashMap<>(); badFonts =new HashMap<>(); fontNameData=new DefaultListModel<>(); fontSizeData=new DefaultListModel<>(); jlFonts=new JList<>(fontNameData); jlFonts.setVisibleRowCount(-1); jlFonts.setCellRenderer(new MyFontRenderer(jlFonts.getFont())); jspFonts = new JScrollPane(jlFonts); for (Font f: GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()){ String name=f.getFamily(); if (goodFonts.get(name)==null && f.canDisplayUpTo("abcdefgh")==-1){ fontNameData.addElement(name); f=f.deriveFont(0, 14); goodFonts.put(name, f); } } jlFontSize=new JList<>(fontSizeData); jlFontSize.setVisibleRowCount(6); jspFontSize = new JScrollPane(jlFontSize); for (int i=5; i<40; i++) fontSizeData.addElement(i); jcbBold=new JCheckBox("Bold"); jcbBold.setFont(jcbBold.getFont().deriveFont(Font.BOLD)); jcbBold.setMnemonic(KeyEvent.VK_B); jcbItalic=new JCheckBox("Italic"); jcbItalic.setFont(jcbItalic.getFont().deriveFont(Font.ITALIC)); jcbItalic.setMnemonic(KeyEvent.VK_I); jspCaretWidth=new JSpinner(new SpinnerNumberModel(1,1,99,1)); jrbForeground=new JRadioButton("Foreground"); jrbForeground.setMnemonic(KeyEvent.VK_O); jrbForeground.setSelected(true); jrbBackground=new JRadioButton("Background"); jrbBackground.setMnemonic(KeyEvent.VK_A); jrbCaret=new JRadioButton("Caret"); jrbCaret.setMnemonic(KeyEvent.VK_T); Radios.doLeftRightArrows(Radios.create(jrbForeground, jrbBackground, jrbCaret)); colorChooser=new JColorChooser(); //This eliminates the preview so we can customize: colorChooser.setPreviewPanel(new JPanel()); mta=new MyTextArea(pInfo.currentOS); mta.setRows(4);//This doesn't work right because we set the font different. mta.setLineWrap(false); mta.setWrapStyleWord(false); jspMTA=mta.makeVerticalScrollable(); mta.setText("The quick brown fox jumped over the lazy dog.\n Fourscore and seven years ago..." +"\n One day Chicken Little was walking in the woods when -" +"\n1234567890 < > ? ! / \\ | , . : ; { } [ ] ( ) - + = @ # $ % ^ & * ~ `" ); btnOK =new JButton("OK"); btnOK.setMnemonic(KeyEvent.VK_K); btnCancel=new JButton("Cancel"); btnCancel.setMnemonic(KeyEvent.VK_C); } private class MyFontRenderer extends JLabel implements ListCellRenderer<String> { private Font defaultFont; Color badColor=new Color(230, 100, 100); public MyFontRenderer(Font defaultFont) { this.defaultFont=defaultFont; setOpaque(true); } public Component getListCellRendererComponent( JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus ) { Font font=badFonts.get(value); boolean isBad=font!=null; if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(isBad ?badColor :list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(isBad ?badColor :list.getForeground()); } font=null; if (!isBad) font=goodFonts.get(value); if (font==null) font=defaultFont; this.setFont(font); setText(value); return this; } } ///////////// // LAYOUT: // ///////////// private void layout() { GridBug gb=new GridBug(win); gb.gridXY(0); gb.weightXY(0); gb.setInsets(5, 5, 0, 5); gb.fill=gb.BOTH; gb.anchor=gb.NORTHWEST; gb.addY(layoutTop()); gb.fill=gb.BOTH; gb.weightXY(1); gb.addY(layoutBottom()); win.pack(); } private JPanel layoutTop() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.gridXY(0); gb.weightXY(0); gb.fill=gb.BOTH; gb.anchor=gb.NORTHWEST; gb.setInsets(5); gb.insets.top=0; // Title: gb.gridwidth=2; gb.setX(0); gb.addX(jlCFO); gb.gridwidth=1; // Spinner: gb.insets.top=0; gb.insets.left=20; gb.setX(0).setY(1); gb.gridXY(0, 2); gb.weightXY(0, 1); gb.fill=gb.NONE; gb.add(jspControlSize); // Spinner label; gb.insets.left=4; gb.fill=gb.VERTICAL; gb.weightXY(1, 0); gb.addX(new JLabel("Minimum font size for various controls")); return jp; } private JPanel layoutBottom() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.gridXY(0); gb.weightXY(0); gb.anchor=gb.NORTHWEST; // Label: gb.insets.top=0; gb.insets.left=5; gb.addY(jlEFO); // Font name, size< style: gb.fill=gb.BOTH; gb.insets.left=20; gb.weightXY(0, 0.3); gb.addY(getEditorFontSelectionPanel()); // Colors: gb.insets.top=5; gb.weightXY(1, 0); gb.fill=gb.HORIZONTAL; gb.addY(getColorPanel()); // Preview: gb.insets.top=0; gb.weightXY(1, 0.7); gb.fill=gb.BOTH; gb.addY(getPreviewPanel()); // Buttons: gb.weightXY(1, 0); gb.fill=gb.HORIZONTAL; gb.addY(getButtonPanel()); return jp; } private JPanel getEditorFontSelectionPanel() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.anchor=gb.WEST; gb.weightXY(0.1, 1); gb.fill=gb.BOTH; gb.add(getFontListPanel()); gb.insets.left=10; gb.weightx=0; gb.addX(getFontSizePanel()); gb.weightx=0; gb.fill=gb.VERTICAL; gb.addX(getFontStylePanel()); return jp; } private JPanel getFontListPanel() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.weightXY(0).gridXY(0); gb.anchor=gb.WEST; JLabel label=new JLabel("Font:"); label.setDisplayedMnemonic(KeyEvent.VK_F); label.setLabelFor(jlFonts); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.insets.top=10; gb.insets.left=5; gb.insets.right=5; gb.add(label); gb.weightXY(1); gb.insets.top=0; gb.fill=gb.BOTH; gb.addY(jspFonts); return jp; } private JPanel getFontSizePanel(){ JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.NORTHWEST; gb.insets.left=5; gb.insets.right=5; gb.weightXY(1,0); JLabel label=new JLabel("Font Size:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); label.setDisplayedMnemonic(KeyEvent.VK_Z); label.setLabelFor(jlFontSize); gb.insets.top=10; gb.add(label); gb.weightXY(1); gb.insets.top=0; gb.fill=gb.BOTH; gb.addY(jspFontSize); return panel; } private JPanel getFontStylePanel(){ JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.NORTHWEST; gb.insets.left=5; gb.insets.right=5; { gb.weightXY(1,0); JLabel label=new JLabel("Font Style:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.insets.top=10; gb.add(label); } gb.insets.top=0; gb.fill=gb.NONE; gb.addY(jcbBold); gb.weightXY(1,0); gb.addY(jcbItalic); { gb.weightXY(1,0); JLabel label=new JLabel("Caret Width:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.insets.top=10; gb.addY(label); } gb.insets.top=0; gb.fill=gb.NONE; gb.weightXY(1,1); gb.addY(jspCaretWidth); return panel; } private JPanel getColorPanel() { JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.NORTHWEST; gb.insets.left=5; gb.insets.right=5; gb.weightXY(1, 0); gb.insets.top=5; gb.fill=gb.HORIZONTAL; gb.anchor=gb.WEST; gb.add(getColorTopPanel()); gb.insets.top=0; gb.addY(colorChooser); return panel; } private JPanel getColorTopPanel() { JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); gb.weightXY(0).gridXY(0); gb.anchor=gb.WEST; JLabel label=new JLabel("Color:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); gb.add(label); gb.insets.left=5; gb.addX(jrbForeground); gb.addX(jrbBackground); gb.weightx=1; gb.addX(jrbCaret); return panel; } private JPanel getPreviewPanel() { JPanel jp=new JPanel(); GridBug gb=new GridBug(jp); gb.weightXY(0).gridXY(0); gb.anchor=gb.WEST; JLabel label=new JLabel("Preview:"); label.setFont(label.getFont().deriveFont(Font.BOLD)); label.setDisplayedMnemonic(KeyEvent.VK_P); label.setLabelFor(jspMTA); gb.insets.top=10; gb.insets.left=5; gb.insets.right=5; gb.add(label); gb.weightXY(1); gb.insets.top=0; gb.fill=gb.BOTH; gb.addY(jspMTA); return jp; } private JPanel getButtonPanel() { JPanel panel=new JPanel(); GridBug gb=new GridBug(panel); Insets insets=gb.insets; insets.top=5; insets.bottom=5; insets.left=5; insets.right=5; gb.gridx=0; gb.add(btnOK); gb.addX(btnCancel); return panel; } ///////////// // LISTEN: // ///////////// private void listen() { //Controls font size change: { ChangeListener styleListen=new ChangeListener(){ public void stateChanged(ChangeEvent ce) { new MinimumFont(Integer.parseInt(jspControlSize.getValue().toString())); changeFont(); } }; jspControlSize.addChangeListener(styleListen); } //Font name<SUF> { ListSelectionListener lsl=new ListSelectionListener(){ public void valueChanged(ListSelectionEvent lse) { changeFont(); } }; jlFonts.addListSelectionListener(lsl); jlFontSize.addListSelectionListener(lsl); } //Font style change: { ChangeListener styleListen=new ChangeListener(){ public void stateChanged(ChangeEvent ce) { changeFont(); } }; jcbBold.addChangeListener(styleListen); jcbItalic.addChangeListener(styleListen); } //Caret width change: { ChangeListener listen=new ChangeListener(){ public void stateChanged(ChangeEvent ce) { changeFont(); } }; jspCaretWidth.addChangeListener(listen); } //Color chooser radio button change: { ActionListener clisten=new ActionListener(){ public void actionPerformed(ActionEvent ce) { setColorChooserColor(); } }; jrbForeground.addActionListener(clisten); jrbBackground.addActionListener(clisten); jrbCaret.addActionListener(clisten); } //Color change: colorChooser.getSelectionModel().addChangeListener(new ChangeListener(){ public void stateChanged(ChangeEvent ce) { if (jrbForeground==null || jrbBackground==null || jrbCaret==null || mta==null) return; if (jrbForeground.isSelected()){ selectedForeground=colorChooser.getColor(); mta.setForeground(selectedForeground); } else if (jrbBackground.isSelected()) { selectedBackground=colorChooser.getColor(); mta.setBackground(selectedBackground); } else if (jrbCaret.isSelected()) { selectedCaret=colorChooser.getColor(); mta.setCaretColor(selectedCaret); } } }); mta.addKeyListener(textAreaListener); //Button clicks: Action okAction=new AbstractAction() { public void actionPerformed(ActionEvent event) {click(true);} }; btnOK.addActionListener(okAction); // This means clicking enter anywhere activates ok KeyMapper.accel(btnOK, okAction, KeyMapper.key(KeyEvent.VK_ENTER)); Action cancelAction=new AbstractAction() { public void actionPerformed(ActionEvent event) {click(false);} }; btnCancel.addActionListener(cancelAction); KeyMapper.easyCancel(btnCancel, cancelAction); } private void setColorChooserColor() { if (colorChooser==null || jrbForeground==null || jrbBackground==null || jrbCaret==null) return; if (jrbForeground.isSelected()) colorChooser.setColor(selectedForeground); else if (jrbBackground.isSelected()) colorChooser.setColor(selectedBackground); else if (jrbCaret.isSelected()) colorChooser.setColor(selectedCaret); } private int getSelectedStyle() { return Font.PLAIN | (jcbBold.isSelected() ?Font.BOLD :0) | (jcbItalic.isSelected() ?Font.ITALIC :0); } /** Listening to the textareas for tab & enter keys: */ private KeyAdapter textAreaListener=new KeyAdapter() { public void keyPressed(KeyEvent e){ final int code=e.getKeyCode(); if (code==e.VK_TAB) { int mods=e.getModifiersEx(); if (KeyMapper.shiftPressed(mods)) colorChooser.requestFocusInWindow(); else btnOK.requestFocusInWindow(); e.consume(); } } }; ///////////// /// TEST: /// ///////////// public static void main(final String[] args) throws Exception { javax.swing.SwingUtilities.invokeLater(()->{ try { PopupTestContext ptc=new PopupTestContext(); FontOptions fo=new FontOptions(); System.out.println("Before: "+fo); new FontPicker( ptc.getPopupInfo(), s->System.out.println("!!!!\n"+s+"\n!!!!") ).show(fo); System.out.println("After: "+fo); } catch (Exception e) { e.printStackTrace(); } }); } }
28765_13
package net.minecraft.src; import java.util.Random; import org.lwjgl.input.Keyboard; public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode = "survival"; private boolean generateStructures = true; private boolean commandsAllowed; /** True iif player has clicked buttonAllowCommands at least once */ private boolean commandsToggled; /** toggles when GUIButton 7 is pressed */ private boolean bonusItems; /** True if and only if gameMode.equals("hardcore") */ private boolean isHardcore; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton buttonGameMode; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton buttonGenerateStructures; private GuiButton buttonBonusItems; /** The GuiButton in the more world options screen. */ private GuiButton buttonWorldType; private GuiButton buttonAllowCommands; /** GuiButton in the more world options screen. */ private GuiButton buttonCustomize; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */ private String localizedNewWorldText; private int worldTypeId; /** Generator options to use when creating the world. */ public String generatorOptionsToUse = ""; /** * If the world name is one of these, it'll be surrounded with underscores. */ private static final String[] ILLEGAL_WORLD_NAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public GuiCreateWorld(GuiScreen par1GuiScreen) { this.parentGuiScreen = par1GuiScreen; this.seed = ""; this.localizedNewWorldText = I18n.func_135053_a("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { this.textboxWorldName.updateCursorCounter(); this.textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.func_135053_a("selectWorld.create"))); this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.func_135053_a("gui.cancel"))); this.buttonList.add(this.buttonGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.func_135053_a("selectWorld.gameMode"))); this.buttonList.add(this.moreWorldOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.func_135053_a("selectWorld.moreWorldOptions"))); this.buttonList.add(this.buttonGenerateStructures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.func_135053_a("selectWorld.mapFeatures"))); this.buttonGenerateStructures.drawButton = false; this.buttonList.add(this.buttonBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.func_135053_a("selectWorld.bonusItems"))); this.buttonBonusItems.drawButton = false; this.buttonList.add(this.buttonWorldType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.func_135053_a("selectWorld.mapType"))); this.buttonWorldType.drawButton = false; this.buttonList.add(this.buttonAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.func_135053_a("selectWorld.allowCommands"))); this.buttonAllowCommands.drawButton = false; this.buttonList.add(this.buttonCustomize = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.func_135053_a("selectWorld.customizeType"))); this.buttonCustomize.drawButton = false; this.textboxWorldName = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxWorldName.setFocused(true); this.textboxWorldName.setText(this.localizedNewWorldText); this.textboxSeed = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxSeed.setText(this.seed); this.func_82288_a(this.moreOptions); this.makeUseableName(); this.updateButtonText(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { this.folderName = this.textboxWorldName.getText().trim(); char[] var1 = ChatAllowedCharacters.allowedCharactersArray; int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { char var4 = var1[var3]; this.folderName = this.folderName.replace(var4, '_'); } if (MathHelper.stringNullOrLengthZero(this.folderName)) { this.folderName = "World"; } this.folderName = func_73913_a(this.mc.getSaveLoader(), this.folderName); } private void updateButtonText() { this.buttonGameMode.displayString = I18n.func_135053_a("selectWorld.gameMode") + " " + I18n.func_135053_a("selectWorld.gameMode." + this.gameMode); this.gameModeDescriptionLine1 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line1"); this.gameModeDescriptionLine2 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line2"); this.buttonGenerateStructures.displayString = I18n.func_135053_a("selectWorld.mapFeatures") + " "; if (this.generateStructures) { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.on"); } else { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.off"); } this.buttonBonusItems.displayString = I18n.func_135053_a("selectWorld.bonusItems") + " "; if (this.bonusItems && !this.isHardcore) { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.on"); } else { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.off"); } this.buttonWorldType.displayString = I18n.func_135053_a("selectWorld.mapType") + " " + I18n.func_135053_a(WorldType.worldTypes[this.worldTypeId].getTranslateName()); this.buttonAllowCommands.displayString = I18n.func_135053_a("selectWorld.allowCommands") + " "; if (this.commandsAllowed && !this.isHardcore) { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.on"); } else { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.off"); } } public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str) { par1Str = par1Str.replaceAll("[\\./\"]", "_"); String[] var2 = ILLEGAL_WORLD_NAMES; int var3 = var2.length; for (int var4 = 0; var4 < var3; ++var4) { String var5 = var2[var4]; if (par1Str.equalsIgnoreCase(var5)) { par1Str = "_" + par1Str + "_"; } } while (par0ISaveFormat.getWorldInfo(par1Str) != null) { par1Str = par1Str + "-"; } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { if (par1GuiButton.id == 1) { this.mc.displayGuiScreen(this.parentGuiScreen); } else if (par1GuiButton.id == 0) { this.mc.displayGuiScreen((GuiScreen)null); if (this.createClicked) { return; } this.createClicked = true; long var2 = (new Random()).nextLong(); String var4 = this.textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(var4)) { try { long var5 = Long.parseLong(var4); if (var5 != 0L) { var2 = var5; } } catch (NumberFormatException var7) { var2 = (long)var4.hashCode(); } } EnumGameType var8 = EnumGameType.getByName(this.gameMode); WorldSettings var6 = new WorldSettings(var2, var8, this.generateStructures, this.isHardcore, WorldType.worldTypes[this.worldTypeId]); var6.func_82750_a(this.generatorOptionsToUse); if (this.bonusItems && !this.isHardcore) { var6.enableBonusChest(); } if (this.commandsAllowed && !this.isHardcore) { var6.enableCommands(); } this.mc.launchIntegratedServer(this.folderName, this.textboxWorldName.getText().trim(), var6); this.mc.statFileWriter.readStat(StatList.createWorldStat, 1); } else if (par1GuiButton.id == 3) { this.func_82287_i(); } else if (par1GuiButton.id == 2) { if (this.gameMode.equals("survival")) { if (!this.commandsToggled) { this.commandsAllowed = false; } this.isHardcore = false; this.gameMode = "hardcore"; this.isHardcore = true; this.buttonAllowCommands.enabled = false; this.buttonBonusItems.enabled = false; this.updateButtonText(); } else if (this.gameMode.equals("hardcore")) { if (!this.commandsToggled) { this.commandsAllowed = true; } this.isHardcore = false; this.gameMode = "creative"; this.updateButtonText(); this.isHardcore = false; this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; } else { if (!this.commandsToggled) { this.commandsAllowed = false; } this.gameMode = "survival"; this.updateButtonText(); this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; this.isHardcore = false; } this.updateButtonText(); } else if (par1GuiButton.id == 4) { this.generateStructures = !this.generateStructures; this.updateButtonText(); } else if (par1GuiButton.id == 7) { this.bonusItems = !this.bonusItems; this.updateButtonText(); } else if (par1GuiButton.id == 5) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } while (WorldType.worldTypes[this.worldTypeId] == null || !WorldType.worldTypes[this.worldTypeId].getCanBeCreated()) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } } this.generatorOptionsToUse = ""; this.updateButtonText(); this.func_82288_a(this.moreOptions); } else if (par1GuiButton.id == 6) { this.commandsToggled = true; this.commandsAllowed = !this.commandsAllowed; this.updateButtonText(); } else if (par1GuiButton.id == 8) { this.mc.displayGuiScreen(new GuiCreateFlatWorld(this, this.generatorOptionsToUse)); } } } private void func_82287_i() { this.func_82288_a(!this.moreOptions); } private void func_82288_a(boolean par1) { this.moreOptions = par1; this.buttonGameMode.drawButton = !this.moreOptions; this.buttonGenerateStructures.drawButton = this.moreOptions; this.buttonBonusItems.drawButton = this.moreOptions; this.buttonWorldType.drawButton = this.moreOptions; this.buttonAllowCommands.drawButton = this.moreOptions; this.buttonCustomize.drawButton = this.moreOptions && WorldType.worldTypes[this.worldTypeId] == WorldType.FLAT; if (this.moreOptions) { this.moreWorldOptions.displayString = I18n.func_135053_a("gui.done"); } else { this.moreWorldOptions.displayString = I18n.func_135053_a("selectWorld.moreWorldOptions"); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (this.textboxWorldName.isFocused() && !this.moreOptions) { this.textboxWorldName.textboxKeyTyped(par1, par2); this.localizedNewWorldText = this.textboxWorldName.getText(); } else if (this.textboxSeed.isFocused() && this.moreOptions) { this.textboxSeed.textboxKeyTyped(par1, par2); this.seed = this.textboxSeed.getText(); } if (par2 == 28 || par2 == 156) { this.actionPerformed((GuiButton)this.buttonList.get(0)); } ((GuiButton)this.buttonList.get(0)).enabled = this.textboxWorldName.getText().length() > 0; this.makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (this.moreOptions) { this.textboxSeed.mouseClicked(par1, par2, par3); } else { this.textboxWorldName.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRenderer, I18n.func_135053_a("selectWorld.create"), this.width / 2, 20, 16777215); if (this.moreOptions) { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterSeed"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.seedInfo"), this.width / 2 - 100, 85, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.mapFeatures.info"), this.width / 2 - 150, 122, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.allowCommands.info"), this.width / 2 - 150, 172, 10526880); this.textboxSeed.drawTextBox(); } else { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterName"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.resultFolder") + " " + this.folderName, this.width / 2 - 100, 85, 10526880); this.textboxWorldName.drawTextBox(); this.drawString(this.fontRenderer, this.gameModeDescriptionLine1, this.width / 2 - 100, 137, 10526880); this.drawString(this.fontRenderer, this.gameModeDescriptionLine2, this.width / 2 - 100, 149, 10526880); } super.drawScreen(par1, par2, par3); } public void func_82286_a(WorldInfo par1WorldInfo) { this.localizedNewWorldText = I18n.func_135052_a("selectWorld.newWorld.copyOf", new Object[] {par1WorldInfo.getWorldName()}); this.seed = par1WorldInfo.getSeed() + ""; this.worldTypeId = par1WorldInfo.getTerrainType().getWorldTypeID(); this.generatorOptionsToUse = par1WorldInfo.getGeneratorOptions(); this.generateStructures = par1WorldInfo.isMapFeaturesEnabled(); this.commandsAllowed = par1WorldInfo.areCommandsAllowed(); if (par1WorldInfo.isHardcoreModeEnabled()) { this.gameMode = "hardcore"; } else if (par1WorldInfo.getGameType().isSurvivalOrAdventure()) { this.gameMode = "survival"; } else if (par1WorldInfo.getGameType().isCreative()) { this.gameMode = "creative"; } } }
zaices/minecraft
net/minecraft/src/GuiCreateWorld.java
5,696
/** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */
block_comment
nl
package net.minecraft.src; import java.util.Random; import org.lwjgl.input.Keyboard; public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode = "survival"; private boolean generateStructures = true; private boolean commandsAllowed; /** True iif player has clicked buttonAllowCommands at least once */ private boolean commandsToggled; /** toggles when GUIButton 7 is pressed */ private boolean bonusItems; /** True if and only if gameMode.equals("hardcore") */ private boolean isHardcore; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton buttonGameMode; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton buttonGenerateStructures; private GuiButton buttonBonusItems; /** The GuiButton in the more world options screen. */ private GuiButton buttonWorldType; private GuiButton buttonAllowCommands; /** GuiButton in the more world options screen. */ private GuiButton buttonCustomize; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World,<SUF>*/ private String localizedNewWorldText; private int worldTypeId; /** Generator options to use when creating the world. */ public String generatorOptionsToUse = ""; /** * If the world name is one of these, it'll be surrounded with underscores. */ private static final String[] ILLEGAL_WORLD_NAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public GuiCreateWorld(GuiScreen par1GuiScreen) { this.parentGuiScreen = par1GuiScreen; this.seed = ""; this.localizedNewWorldText = I18n.func_135053_a("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { this.textboxWorldName.updateCursorCounter(); this.textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.func_135053_a("selectWorld.create"))); this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.func_135053_a("gui.cancel"))); this.buttonList.add(this.buttonGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.func_135053_a("selectWorld.gameMode"))); this.buttonList.add(this.moreWorldOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.func_135053_a("selectWorld.moreWorldOptions"))); this.buttonList.add(this.buttonGenerateStructures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.func_135053_a("selectWorld.mapFeatures"))); this.buttonGenerateStructures.drawButton = false; this.buttonList.add(this.buttonBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.func_135053_a("selectWorld.bonusItems"))); this.buttonBonusItems.drawButton = false; this.buttonList.add(this.buttonWorldType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.func_135053_a("selectWorld.mapType"))); this.buttonWorldType.drawButton = false; this.buttonList.add(this.buttonAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.func_135053_a("selectWorld.allowCommands"))); this.buttonAllowCommands.drawButton = false; this.buttonList.add(this.buttonCustomize = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.func_135053_a("selectWorld.customizeType"))); this.buttonCustomize.drawButton = false; this.textboxWorldName = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxWorldName.setFocused(true); this.textboxWorldName.setText(this.localizedNewWorldText); this.textboxSeed = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxSeed.setText(this.seed); this.func_82288_a(this.moreOptions); this.makeUseableName(); this.updateButtonText(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { this.folderName = this.textboxWorldName.getText().trim(); char[] var1 = ChatAllowedCharacters.allowedCharactersArray; int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { char var4 = var1[var3]; this.folderName = this.folderName.replace(var4, '_'); } if (MathHelper.stringNullOrLengthZero(this.folderName)) { this.folderName = "World"; } this.folderName = func_73913_a(this.mc.getSaveLoader(), this.folderName); } private void updateButtonText() { this.buttonGameMode.displayString = I18n.func_135053_a("selectWorld.gameMode") + " " + I18n.func_135053_a("selectWorld.gameMode." + this.gameMode); this.gameModeDescriptionLine1 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line1"); this.gameModeDescriptionLine2 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line2"); this.buttonGenerateStructures.displayString = I18n.func_135053_a("selectWorld.mapFeatures") + " "; if (this.generateStructures) { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.on"); } else { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.off"); } this.buttonBonusItems.displayString = I18n.func_135053_a("selectWorld.bonusItems") + " "; if (this.bonusItems && !this.isHardcore) { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.on"); } else { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.off"); } this.buttonWorldType.displayString = I18n.func_135053_a("selectWorld.mapType") + " " + I18n.func_135053_a(WorldType.worldTypes[this.worldTypeId].getTranslateName()); this.buttonAllowCommands.displayString = I18n.func_135053_a("selectWorld.allowCommands") + " "; if (this.commandsAllowed && !this.isHardcore) { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.on"); } else { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.off"); } } public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str) { par1Str = par1Str.replaceAll("[\\./\"]", "_"); String[] var2 = ILLEGAL_WORLD_NAMES; int var3 = var2.length; for (int var4 = 0; var4 < var3; ++var4) { String var5 = var2[var4]; if (par1Str.equalsIgnoreCase(var5)) { par1Str = "_" + par1Str + "_"; } } while (par0ISaveFormat.getWorldInfo(par1Str) != null) { par1Str = par1Str + "-"; } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { if (par1GuiButton.id == 1) { this.mc.displayGuiScreen(this.parentGuiScreen); } else if (par1GuiButton.id == 0) { this.mc.displayGuiScreen((GuiScreen)null); if (this.createClicked) { return; } this.createClicked = true; long var2 = (new Random()).nextLong(); String var4 = this.textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(var4)) { try { long var5 = Long.parseLong(var4); if (var5 != 0L) { var2 = var5; } } catch (NumberFormatException var7) { var2 = (long)var4.hashCode(); } } EnumGameType var8 = EnumGameType.getByName(this.gameMode); WorldSettings var6 = new WorldSettings(var2, var8, this.generateStructures, this.isHardcore, WorldType.worldTypes[this.worldTypeId]); var6.func_82750_a(this.generatorOptionsToUse); if (this.bonusItems && !this.isHardcore) { var6.enableBonusChest(); } if (this.commandsAllowed && !this.isHardcore) { var6.enableCommands(); } this.mc.launchIntegratedServer(this.folderName, this.textboxWorldName.getText().trim(), var6); this.mc.statFileWriter.readStat(StatList.createWorldStat, 1); } else if (par1GuiButton.id == 3) { this.func_82287_i(); } else if (par1GuiButton.id == 2) { if (this.gameMode.equals("survival")) { if (!this.commandsToggled) { this.commandsAllowed = false; } this.isHardcore = false; this.gameMode = "hardcore"; this.isHardcore = true; this.buttonAllowCommands.enabled = false; this.buttonBonusItems.enabled = false; this.updateButtonText(); } else if (this.gameMode.equals("hardcore")) { if (!this.commandsToggled) { this.commandsAllowed = true; } this.isHardcore = false; this.gameMode = "creative"; this.updateButtonText(); this.isHardcore = false; this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; } else { if (!this.commandsToggled) { this.commandsAllowed = false; } this.gameMode = "survival"; this.updateButtonText(); this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; this.isHardcore = false; } this.updateButtonText(); } else if (par1GuiButton.id == 4) { this.generateStructures = !this.generateStructures; this.updateButtonText(); } else if (par1GuiButton.id == 7) { this.bonusItems = !this.bonusItems; this.updateButtonText(); } else if (par1GuiButton.id == 5) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } while (WorldType.worldTypes[this.worldTypeId] == null || !WorldType.worldTypes[this.worldTypeId].getCanBeCreated()) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } } this.generatorOptionsToUse = ""; this.updateButtonText(); this.func_82288_a(this.moreOptions); } else if (par1GuiButton.id == 6) { this.commandsToggled = true; this.commandsAllowed = !this.commandsAllowed; this.updateButtonText(); } else if (par1GuiButton.id == 8) { this.mc.displayGuiScreen(new GuiCreateFlatWorld(this, this.generatorOptionsToUse)); } } } private void func_82287_i() { this.func_82288_a(!this.moreOptions); } private void func_82288_a(boolean par1) { this.moreOptions = par1; this.buttonGameMode.drawButton = !this.moreOptions; this.buttonGenerateStructures.drawButton = this.moreOptions; this.buttonBonusItems.drawButton = this.moreOptions; this.buttonWorldType.drawButton = this.moreOptions; this.buttonAllowCommands.drawButton = this.moreOptions; this.buttonCustomize.drawButton = this.moreOptions && WorldType.worldTypes[this.worldTypeId] == WorldType.FLAT; if (this.moreOptions) { this.moreWorldOptions.displayString = I18n.func_135053_a("gui.done"); } else { this.moreWorldOptions.displayString = I18n.func_135053_a("selectWorld.moreWorldOptions"); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (this.textboxWorldName.isFocused() && !this.moreOptions) { this.textboxWorldName.textboxKeyTyped(par1, par2); this.localizedNewWorldText = this.textboxWorldName.getText(); } else if (this.textboxSeed.isFocused() && this.moreOptions) { this.textboxSeed.textboxKeyTyped(par1, par2); this.seed = this.textboxSeed.getText(); } if (par2 == 28 || par2 == 156) { this.actionPerformed((GuiButton)this.buttonList.get(0)); } ((GuiButton)this.buttonList.get(0)).enabled = this.textboxWorldName.getText().length() > 0; this.makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (this.moreOptions) { this.textboxSeed.mouseClicked(par1, par2, par3); } else { this.textboxWorldName.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRenderer, I18n.func_135053_a("selectWorld.create"), this.width / 2, 20, 16777215); if (this.moreOptions) { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterSeed"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.seedInfo"), this.width / 2 - 100, 85, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.mapFeatures.info"), this.width / 2 - 150, 122, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.allowCommands.info"), this.width / 2 - 150, 172, 10526880); this.textboxSeed.drawTextBox(); } else { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterName"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.resultFolder") + " " + this.folderName, this.width / 2 - 100, 85, 10526880); this.textboxWorldName.drawTextBox(); this.drawString(this.fontRenderer, this.gameModeDescriptionLine1, this.width / 2 - 100, 137, 10526880); this.drawString(this.fontRenderer, this.gameModeDescriptionLine2, this.width / 2 - 100, 149, 10526880); } super.drawScreen(par1, par2, par3); } public void func_82286_a(WorldInfo par1WorldInfo) { this.localizedNewWorldText = I18n.func_135052_a("selectWorld.newWorld.copyOf", new Object[] {par1WorldInfo.getWorldName()}); this.seed = par1WorldInfo.getSeed() + ""; this.worldTypeId = par1WorldInfo.getTerrainType().getWorldTypeID(); this.generatorOptionsToUse = par1WorldInfo.getGeneratorOptions(); this.generateStructures = par1WorldInfo.isMapFeaturesEnabled(); this.commandsAllowed = par1WorldInfo.areCommandsAllowed(); if (par1WorldInfo.isHardcoreModeEnabled()) { this.gameMode = "hardcore"; } else if (par1WorldInfo.getGameType().isSurvivalOrAdventure()) { this.gameMode = "survival"; } else if (par1WorldInfo.getGameType().isCreative()) { this.gameMode = "creative"; } } }
148094_3
/* * Copyright 2012 Google Inc. * * 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.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "nl" locale. */ public class LocalizedNamesImpl_nl extends LocalizedNamesImpl { @Override public String[] loadLikelyRegionCodes() { return new String[] { "NL", "DE", "BE", }; } @Override public String[] loadSortedRegionCodes() { return new String[] { "AF", "AX", "AL", "DZ", "VI", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AC", "AU", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "VG", "IO", "BN", "BG", "BF", "BI", "KH", "CA", "IC", "BQ", "CF", "EA", "CL", "CN", "CX", "CP", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CU", "CW", "CY", "DK", "DG", "DJ", "DM", "DO", "DE", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "EU", "EZ", "FO", "FK", "FJ", "PH", "FI", "FR", "TF", "GF", "PF", "GA", "GM", "GE", "GH", "GI", "GD", "GR", "GL", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "HN", "HU", "HK", "IE", "IS", "IN", "ID", "IQ", "IR", "IM", "IL", "IT", "CI", "JM", "JP", "YE", "JE", "JO", "KY", "CV", "CM", "KZ", "KE", "KG", "KI", "UM", "KW", "XK", "HR", "LA", "LS", "LV", "LB", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MV", "MY", "ML", "MT", "MA", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MZ", "MM", "NA", "NR", "NL", "NP", "NI", "NC", "NZ", "NE", "NG", "NU", "MP", "KP", "NO", "NF", "UG", "UA", "UZ", "OM", "AT", "TL", "QO", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "KN", "LC", "MF", "PM", "VC", "SB", "WS", "SM", "SA", "ST", "SN", "RS", "SC", "SL", "SG", "SH", "SX", "SI", "SK", "SD", "SO", "ES", "SJ", "LK", "SR", "SZ", "SY", "TJ", "TW", "TZ", "TH", "TG", "TK", "TO", "TT", "TA", "TD", "CZ", "TN", "TR", "TM", "TC", "TV", "UY", "VU", "VA", "VE", "AE", "UN", "US", "GB", "VN", "WF", "EH", "ZM", "ZW", "ZA", "GS", "KR", "SS", "SE", "CH", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("001", "wereld"); namesMap.put("002", "Afrika"); namesMap.put("003", "Noord-Amerika"); namesMap.put("005", "Zuid-Amerika"); namesMap.put("009", "Oceanië"); namesMap.put("011", "West-Afrika"); namesMap.put("013", "Midden-Amerika"); namesMap.put("014", "Oost-Afrika"); namesMap.put("015", "Noord-Afrika"); namesMap.put("017", "Centraal-Afrika"); namesMap.put("018", "Zuidelijk Afrika"); namesMap.put("019", "Amerika"); namesMap.put("021", "Noordelijk Amerika"); namesMap.put("029", "Caribisch gebied"); namesMap.put("030", "Oost-Azië"); namesMap.put("034", "Zuid-Azië"); namesMap.put("035", "Zuidoost-Azië"); namesMap.put("039", "Zuid-Europa"); namesMap.put("053", "Australazië"); namesMap.put("054", "Melanesië"); namesMap.put("057", "Micronesische regio"); namesMap.put("061", "Polynesië"); namesMap.put("142", "Azië"); namesMap.put("143", "Centraal-Azië"); namesMap.put("145", "West-Azië"); namesMap.put("150", "Europa"); namesMap.put("151", "Oost-Europa"); namesMap.put("154", "Noord-Europa"); namesMap.put("155", "West-Europa"); namesMap.put("419", "Latijns-Amerika"); namesMap.put("AC", "Ascension"); namesMap.put("AE", "Verenigde Arabische Emiraten"); namesMap.put("AG", "Antigua en Barbuda"); namesMap.put("AL", "Albanië"); namesMap.put("AM", "Armenië"); namesMap.put("AR", "Argentinië"); namesMap.put("AS", "Amerikaans-Samoa"); namesMap.put("AT", "Oostenrijk"); namesMap.put("AU", "Australië"); namesMap.put("AX", "Åland"); namesMap.put("AZ", "Azerbeidzjan"); namesMap.put("BA", "Bosnië en Herzegovina"); namesMap.put("BE", "België"); namesMap.put("BG", "Bulgarije"); namesMap.put("BH", "Bahrein"); namesMap.put("BL", "Saint-Barthélemy"); namesMap.put("BQ", "Caribisch Nederland"); namesMap.put("BR", "Brazilië"); namesMap.put("BS", "Bahama’s"); namesMap.put("BV", "Bouveteiland"); namesMap.put("CC", "Cocoseilanden"); namesMap.put("CD", "Congo-Kinshasa"); namesMap.put("CF", "Centraal-Afrikaanse Republiek"); namesMap.put("CG", "Congo-Brazzaville"); namesMap.put("CH", "Zwitserland"); namesMap.put("CI", "Ivoorkust"); namesMap.put("CK", "Cookeilanden"); namesMap.put("CL", "Chili"); namesMap.put("CM", "Kameroen"); namesMap.put("CP", "Clipperton"); namesMap.put("CV", "Kaapverdië"); namesMap.put("CX", "Christmaseiland"); namesMap.put("CZ", "Tsjechië"); namesMap.put("DE", "Duitsland"); namesMap.put("DK", "Denemarken"); namesMap.put("DO", "Dominicaanse Republiek"); namesMap.put("DZ", "Algerije"); namesMap.put("EA", "Ceuta en Melilla"); namesMap.put("EE", "Estland"); namesMap.put("EG", "Egypte"); namesMap.put("EH", "Westelijke Sahara"); namesMap.put("ES", "Spanje"); namesMap.put("ET", "Ethiopië"); namesMap.put("EU", "Europese Unie"); namesMap.put("EZ", "eurozone"); namesMap.put("FK", "Falklandeilanden"); namesMap.put("FO", "Faeröer"); namesMap.put("FR", "Frankrijk"); namesMap.put("GB", "Verenigd Koninkrijk"); namesMap.put("GE", "Georgië"); namesMap.put("GF", "Frans-Guyana"); namesMap.put("GL", "Groenland"); namesMap.put("GN", "Guinee"); namesMap.put("GQ", "Equatoriaal-Guinea"); namesMap.put("GR", "Griekenland"); namesMap.put("GS", "Zuid-Georgia en Zuidelijke Sandwicheilanden"); namesMap.put("GW", "Guinee-Bissau"); namesMap.put("HK", "Hongkong SAR van China"); namesMap.put("HM", "Heard en McDonaldeilanden"); namesMap.put("HR", "Kroatië"); namesMap.put("HT", "Haïti"); namesMap.put("HU", "Hongarije"); namesMap.put("IC", "Canarische Eilanden"); namesMap.put("ID", "Indonesië"); namesMap.put("IE", "Ierland"); namesMap.put("IL", "Israël"); namesMap.put("IO", "Brits Indische Oceaanterritorium"); namesMap.put("IQ", "Irak"); namesMap.put("IS", "IJsland"); namesMap.put("IT", "Italië"); namesMap.put("JO", "Jordanië"); namesMap.put("KE", "Kenia"); namesMap.put("KG", "Kirgizië"); namesMap.put("KH", "Cambodja"); namesMap.put("KM", "Comoren"); namesMap.put("KN", "Saint Kitts en Nevis"); namesMap.put("KP", "Noord-Korea"); namesMap.put("KR", "Zuid-Korea"); namesMap.put("KW", "Koeweit"); namesMap.put("KY", "Kaaimaneilanden"); namesMap.put("KZ", "Kazachstan"); namesMap.put("LB", "Libanon"); namesMap.put("LC", "Saint Lucia"); namesMap.put("LT", "Litouwen"); namesMap.put("LU", "Luxemburg"); namesMap.put("LV", "Letland"); namesMap.put("LY", "Libië"); namesMap.put("MA", "Marokko"); namesMap.put("MD", "Moldavië"); namesMap.put("MF", "Saint-Martin"); namesMap.put("MG", "Madagaskar"); namesMap.put("MH", "Marshalleilanden"); namesMap.put("MK", "Macedonië"); namesMap.put("MM", "Myanmar (Birma)"); namesMap.put("MN", "Mongolië"); namesMap.put("MO", "Macau SAR van China"); namesMap.put("MP", "Noordelijke Marianen"); namesMap.put("MR", "Mauritanië"); namesMap.put("MV", "Maldiven"); namesMap.put("MY", "Maleisië"); namesMap.put("NA", "Namibië"); namesMap.put("NC", "Nieuw-Caledonië"); namesMap.put("NF", "Norfolk"); namesMap.put("NL", "Nederland"); namesMap.put("NO", "Noorwegen"); namesMap.put("NZ", "Nieuw-Zeeland"); namesMap.put("PF", "Frans-Polynesië"); namesMap.put("PG", "Papoea-Nieuw-Guinea"); namesMap.put("PH", "Filipijnen"); namesMap.put("PL", "Polen"); namesMap.put("PM", "Saint-Pierre en Miquelon"); namesMap.put("PN", "Pitcairneilanden"); namesMap.put("PS", "Palestijnse gebieden"); namesMap.put("QO", "overig Oceanië"); namesMap.put("RO", "Roemenië"); namesMap.put("RS", "Servië"); namesMap.put("RU", "Rusland"); namesMap.put("SA", "Saoedi-Arabië"); namesMap.put("SB", "Salomonseilanden"); namesMap.put("SC", "Seychellen"); namesMap.put("SD", "Soedan"); namesMap.put("SE", "Zweden"); namesMap.put("SH", "Sint-Helena"); namesMap.put("SI", "Slovenië"); namesMap.put("SJ", "Spitsbergen en Jan Mayen"); namesMap.put("SK", "Slowakije"); namesMap.put("SO", "Somalië"); namesMap.put("SS", "Zuid-Soedan"); namesMap.put("ST", "Sao Tomé en Principe"); namesMap.put("SX", "Sint-Maarten"); namesMap.put("SY", "Syrië"); namesMap.put("TC", "Turks- en Caicoseilanden"); namesMap.put("TD", "Tsjaad"); namesMap.put("TF", "Franse Gebieden in de zuidelijke Indische Oceaan"); namesMap.put("TJ", "Tadzjikistan"); namesMap.put("TL", "Oost-Timor"); namesMap.put("TN", "Tunesië"); namesMap.put("TR", "Turkije"); namesMap.put("TT", "Trinidad en Tobago"); namesMap.put("UA", "Oekraïne"); namesMap.put("UG", "Oeganda"); namesMap.put("UM", "Kleine afgelegen eilanden van de Verenigde Staten"); namesMap.put("UN", "Verenigde Naties"); namesMap.put("US", "Verenigde Staten"); namesMap.put("UZ", "Oezbekistan"); namesMap.put("VA", "Vaticaanstad"); namesMap.put("VC", "Saint Vincent en de Grenadines"); namesMap.put("VG", "Britse Maagdeneilanden"); namesMap.put("VI", "Amerikaanse Maagdeneilanden"); namesMap.put("WF", "Wallis en Futuna"); namesMap.put("YE", "Jemen"); namesMap.put("ZA", "Zuid-Afrika"); namesMap.put("ZZ", "onbekend gebied"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ return { "001": "wereld", "002": "Afrika", "003": "Noord-Amerika", "005": "Zuid-Amerika", "009": "Oceanië", "011": "West-Afrika", "013": "Midden-Amerika", "014": "Oost-Afrika", "015": "Noord-Afrika", "017": "Centraal-Afrika", "018": "Zuidelijk Afrika", "019": "Amerika", "021": "Noordelijk Amerika", "029": "Caribisch gebied", "030": "Oost-Azië", "034": "Zuid-Azië", "035": "Zuidoost-Azië", "039": "Zuid-Europa", "053": "Australazië", "054": "Melanesië", "057": "Micronesische regio", "061": "Polynesië", "142": "Azië", "143": "Centraal-Azië", "145": "West-Azië", "150": "Europa", "151": "Oost-Europa", "154": "Noord-Europa", "155": "West-Europa", "419": "Latijns-Amerika", "AC": "Ascension", "AE": "Verenigde Arabische Emiraten", "AG": "Antigua en Barbuda", "AL": "Albanië", "AM": "Armenië", "AR": "Argentinië", "AS": "Amerikaans-Samoa", "AT": "Oostenrijk", "AU": "Australië", "AX": "Åland", "AZ": "Azerbeidzjan", "BA": "Bosnië en Herzegovina", "BE": "België", "BG": "Bulgarije", "BH": "Bahrein", "BL": "Saint-Barthélemy", "BQ": "Caribisch Nederland", "BR": "Brazilië", "BS": "Bahama’s", "BV": "Bouveteiland", "CC": "Cocoseilanden", "CD": "Congo-Kinshasa", "CF": "Centraal-Afrikaanse Republiek", "CG": "Congo-Brazzaville", "CH": "Zwitserland", "CI": "Ivoorkust", "CK": "Cookeilanden", "CL": "Chili", "CM": "Kameroen", "CP": "Clipperton", "CV": "Kaapverdië", "CX": "Christmaseiland", "CZ": "Tsjechië", "DE": "Duitsland", "DK": "Denemarken", "DO": "Dominicaanse Republiek", "DZ": "Algerije", "EA": "Ceuta en Melilla", "EE": "Estland", "EG": "Egypte", "EH": "Westelijke Sahara", "ES": "Spanje", "ET": "Ethiopië", "EU": "Europese Unie", "EZ": "eurozone", "FK": "Falklandeilanden", "FO": "Faeröer", "FR": "Frankrijk", "GB": "Verenigd Koninkrijk", "GE": "Georgië", "GF": "Frans-Guyana", "GL": "Groenland", "GN": "Guinee", "GQ": "Equatoriaal-Guinea", "GR": "Griekenland", "GS": "Zuid-Georgia en Zuidelijke Sandwicheilanden", "GW": "Guinee-Bissau", "HK": "Hongkong SAR van China", "HM": "Heard en McDonaldeilanden", "HR": "Kroatië", "HT": "Haïti", "HU": "Hongarije", "IC": "Canarische Eilanden", "ID": "Indonesië", "IE": "Ierland", "IL": "Israël", "IO": "Brits Indische Oceaanterritorium", "IQ": "Irak", "IS": "IJsland", "IT": "Italië", "JO": "Jordanië", "KE": "Kenia", "KG": "Kirgizië", "KH": "Cambodja", "KM": "Comoren", "KN": "Saint Kitts en Nevis", "KP": "Noord-Korea", "KR": "Zuid-Korea", "KW": "Koeweit", "KY": "Kaaimaneilanden", "KZ": "Kazachstan", "LB": "Libanon", "LC": "Saint Lucia", "LT": "Litouwen", "LU": "Luxemburg", "LV": "Letland", "LY": "Libië", "MA": "Marokko", "MD": "Moldavië", "MF": "Saint-Martin", "MG": "Madagaskar", "MH": "Marshalleilanden", "MK": "Macedonië", "MM": "Myanmar (Birma)", "MN": "Mongolië", "MO": "Macau SAR van China", "MP": "Noordelijke Marianen", "MR": "Mauritanië", "MV": "Maldiven", "MY": "Maleisië", "NA": "Namibië", "NC": "Nieuw-Caledonië", "NF": "Norfolk", "NL": "Nederland", "NO": "Noorwegen", "NZ": "Nieuw-Zeeland", "PF": "Frans-Polynesië", "PG": "Papoea-Nieuw-Guinea", "PH": "Filipijnen", "PL": "Polen", "PM": "Saint-Pierre en Miquelon", "PN": "Pitcairneilanden", "PS": "Palestijnse gebieden", "QO": "overig Oceanië", "RO": "Roemenië", "RS": "Servië", "RU": "Rusland", "SA": "Saoedi-Arabië", "SB": "Salomonseilanden", "SC": "Seychellen", "SD": "Soedan", "SE": "Zweden", "SH": "Sint-Helena", "SI": "Slovenië", "SJ": "Spitsbergen en Jan Mayen", "SK": "Slowakije", "SO": "Somalië", "SS": "Zuid-Soedan", "ST": "Sao Tomé en Principe", "SX": "Sint-Maarten", "SY": "Syrië", "TC": "Turks- en Caicoseilanden", "TD": "Tsjaad", "TF": "Franse Gebieden in de zuidelijke Indische Oceaan", "TJ": "Tadzjikistan", "TL": "Oost-Timor", "TN": "Tunesië", "TR": "Turkije", "TT": "Trinidad en Tobago", "UA": "Oekraïne", "UG": "Oeganda", "UM": "Kleine afgelegen eilanden van de Verenigde Staten", "UN": "Verenigde Naties", "US": "Verenigde Staten", "UZ": "Oezbekistan", "VA": "Vaticaanstad", "VC": "Saint Vincent en de Grenadines", "VG": "Britse Maagdeneilanden", "VI": "Amerikaanse Maagdeneilanden", "WF": "Wallis en Futuna", "YE": "Jemen", "ZA": "Zuid-Afrika", "ZZ": "onbekend gebied" }; }-*/; }
zak905/gwt
user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_nl.java
6,959
/*-{ return { "001": "wereld", "002": "Afrika", "003": "Noord-Amerika", "005": "Zuid-Amerika", "009": "Oceanië", "011": "West-Afrika", "013": "Midden-Amerika", "014": "Oost-Afrika", "015": "Noord-Afrika", "017": "Centraal-Afrika", "018": "Zuidelijk Afrika", "019": "Amerika", "021": "Noordelijk Amerika", "029": "Caribisch gebied", "030": "Oost-Azië", "034": "Zuid-Azië", "035": "Zuidoost-Azië", "039": "Zuid-Europa", "053": "Australazië", "054": "Melanesië", "057": "Micronesische regio", "061": "Polynesië", "142": "Azië", "143": "Centraal-Azië", "145": "West-Azië", "150": "Europa", "151": "Oost-Europa", "154": "Noord-Europa", "155": "West-Europa", "419": "Latijns-Amerika", "AC": "Ascension", "AE": "Verenigde Arabische Emiraten", "AG": "Antigua en Barbuda", "AL": "Albanië", "AM": "Armenië", "AR": "Argentinië", "AS": "Amerikaans-Samoa", "AT": "Oostenrijk", "AU": "Australië", "AX": "Åland", "AZ": "Azerbeidzjan", "BA": "Bosnië en Herzegovina", "BE": "België", "BG": "Bulgarije", "BH": "Bahrein", "BL": "Saint-Barthélemy", "BQ": "Caribisch Nederland", "BR": "Brazilië", "BS": "Bahama’s", "BV": "Bouveteiland", "CC": "Cocoseilanden", "CD": "Congo-Kinshasa", "CF": "Centraal-Afrikaanse Republiek", "CG": "Congo-Brazzaville", "CH": "Zwitserland", "CI": "Ivoorkust", "CK": "Cookeilanden", "CL": "Chili", "CM": "Kameroen", "CP": "Clipperton", "CV": "Kaapverdië", "CX": "Christmaseiland", "CZ": "Tsjechië", "DE": "Duitsland", "DK": "Denemarken", "DO": "Dominicaanse Republiek", "DZ": "Algerije", "EA": "Ceuta en Melilla", "EE": "Estland", "EG": "Egypte", "EH": "Westelijke Sahara", "ES": "Spanje", "ET": "Ethiopië", "EU": "Europese Unie", "EZ": "eurozone", "FK": "Falklandeilanden", "FO": "Faeröer", "FR": "Frankrijk", "GB": "Verenigd Koninkrijk", "GE": "Georgië", "GF": "Frans-Guyana", "GL": "Groenland", "GN": "Guinee", "GQ": "Equatoriaal-Guinea", "GR": "Griekenland", "GS": "Zuid-Georgia en Zuidelijke Sandwicheilanden", "GW": "Guinee-Bissau", "HK": "Hongkong SAR van China", "HM": "Heard en McDonaldeilanden", "HR": "Kroatië", "HT": "Haïti", "HU": "Hongarije", "IC": "Canarische Eilanden", "ID": "Indonesië", "IE": "Ierland", "IL": "Israël", "IO": "Brits Indische Oceaanterritorium", "IQ": "Irak", "IS": "IJsland", "IT": "Italië", "JO": "Jordanië", "KE": "Kenia", "KG": "Kirgizië", "KH": "Cambodja", "KM": "Comoren", "KN": "Saint Kitts en Nevis", "KP": "Noord-Korea", "KR": "Zuid-Korea", "KW": "Koeweit", "KY": "Kaaimaneilanden", "KZ": "Kazachstan", "LB": "Libanon", "LC": "Saint Lucia", "LT": "Litouwen", "LU": "Luxemburg", "LV": "Letland", "LY": "Libië", "MA": "Marokko", "MD": "Moldavië", "MF": "Saint-Martin", "MG": "Madagaskar", "MH": "Marshalleilanden", "MK": "Macedonië", "MM": "Myanmar (Birma)", "MN": "Mongolië", "MO": "Macau SAR van China", "MP": "Noordelijke Marianen", "MR": "Mauritanië", "MV": "Maldiven", "MY": "Maleisië", "NA": "Namibië", "NC": "Nieuw-Caledonië", "NF": "Norfolk", "NL": "Nederland", "NO": "Noorwegen", "NZ": "Nieuw-Zeeland", "PF": "Frans-Polynesië", "PG": "Papoea-Nieuw-Guinea", "PH": "Filipijnen", "PL": "Polen", "PM": "Saint-Pierre en Miquelon", "PN": "Pitcairneilanden", "PS": "Palestijnse gebieden", "QO": "overig Oceanië", "RO": "Roemenië", "RS": "Servië", "RU": "Rusland", "SA": "Saoedi-Arabië", "SB": "Salomonseilanden", "SC": "Seychellen", "SD": "Soedan", "SE": "Zweden", "SH": "Sint-Helena", "SI": "Slovenië", "SJ": "Spitsbergen en Jan Mayen", "SK": "Slowakije", "SO": "Somalië", "SS": "Zuid-Soedan", "ST": "Sao Tomé en Principe", "SX": "Sint-Maarten", "SY": "Syrië", "TC": "Turks- en Caicoseilanden", "TD": "Tsjaad", "TF": "Franse Gebieden in de zuidelijke Indische Oceaan", "TJ": "Tadzjikistan", "TL": "Oost-Timor", "TN": "Tunesië", "TR": "Turkije", "TT": "Trinidad en Tobago", "UA": "Oekraïne", "UG": "Oeganda", "UM": "Kleine afgelegen eilanden van de Verenigde Staten", "UN": "Verenigde Naties", "US": "Verenigde Staten", "UZ": "Oezbekistan", "VA": "Vaticaanstad", "VC": "Saint Vincent en de Grenadines", "VG": "Britse Maagdeneilanden", "VI": "Amerikaanse Maagdeneilanden", "WF": "Wallis en Futuna", "YE": "Jemen", "ZA": "Zuid-Afrika", "ZZ": "onbekend gebied" }; }-*/
block_comment
nl
/* * Copyright 2012 Google Inc. * * 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.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "nl" locale. */ public class LocalizedNamesImpl_nl extends LocalizedNamesImpl { @Override public String[] loadLikelyRegionCodes() { return new String[] { "NL", "DE", "BE", }; } @Override public String[] loadSortedRegionCodes() { return new String[] { "AF", "AX", "AL", "DZ", "VI", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AC", "AU", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "VG", "IO", "BN", "BG", "BF", "BI", "KH", "CA", "IC", "BQ", "CF", "EA", "CL", "CN", "CX", "CP", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CU", "CW", "CY", "DK", "DG", "DJ", "DM", "DO", "DE", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "EU", "EZ", "FO", "FK", "FJ", "PH", "FI", "FR", "TF", "GF", "PF", "GA", "GM", "GE", "GH", "GI", "GD", "GR", "GL", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "HN", "HU", "HK", "IE", "IS", "IN", "ID", "IQ", "IR", "IM", "IL", "IT", "CI", "JM", "JP", "YE", "JE", "JO", "KY", "CV", "CM", "KZ", "KE", "KG", "KI", "UM", "KW", "XK", "HR", "LA", "LS", "LV", "LB", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MV", "MY", "ML", "MT", "MA", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MZ", "MM", "NA", "NR", "NL", "NP", "NI", "NC", "NZ", "NE", "NG", "NU", "MP", "KP", "NO", "NF", "UG", "UA", "UZ", "OM", "AT", "TL", "QO", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "KN", "LC", "MF", "PM", "VC", "SB", "WS", "SM", "SA", "ST", "SN", "RS", "SC", "SL", "SG", "SH", "SX", "SI", "SK", "SD", "SO", "ES", "SJ", "LK", "SR", "SZ", "SY", "TJ", "TW", "TZ", "TH", "TG", "TK", "TO", "TT", "TA", "TD", "CZ", "TN", "TR", "TM", "TC", "TV", "UY", "VU", "VA", "VE", "AE", "UN", "US", "GB", "VN", "WF", "EH", "ZM", "ZW", "ZA", "GS", "KR", "SS", "SE", "CH", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("001", "wereld"); namesMap.put("002", "Afrika"); namesMap.put("003", "Noord-Amerika"); namesMap.put("005", "Zuid-Amerika"); namesMap.put("009", "Oceanië"); namesMap.put("011", "West-Afrika"); namesMap.put("013", "Midden-Amerika"); namesMap.put("014", "Oost-Afrika"); namesMap.put("015", "Noord-Afrika"); namesMap.put("017", "Centraal-Afrika"); namesMap.put("018", "Zuidelijk Afrika"); namesMap.put("019", "Amerika"); namesMap.put("021", "Noordelijk Amerika"); namesMap.put("029", "Caribisch gebied"); namesMap.put("030", "Oost-Azië"); namesMap.put("034", "Zuid-Azië"); namesMap.put("035", "Zuidoost-Azië"); namesMap.put("039", "Zuid-Europa"); namesMap.put("053", "Australazië"); namesMap.put("054", "Melanesië"); namesMap.put("057", "Micronesische regio"); namesMap.put("061", "Polynesië"); namesMap.put("142", "Azië"); namesMap.put("143", "Centraal-Azië"); namesMap.put("145", "West-Azië"); namesMap.put("150", "Europa"); namesMap.put("151", "Oost-Europa"); namesMap.put("154", "Noord-Europa"); namesMap.put("155", "West-Europa"); namesMap.put("419", "Latijns-Amerika"); namesMap.put("AC", "Ascension"); namesMap.put("AE", "Verenigde Arabische Emiraten"); namesMap.put("AG", "Antigua en Barbuda"); namesMap.put("AL", "Albanië"); namesMap.put("AM", "Armenië"); namesMap.put("AR", "Argentinië"); namesMap.put("AS", "Amerikaans-Samoa"); namesMap.put("AT", "Oostenrijk"); namesMap.put("AU", "Australië"); namesMap.put("AX", "Åland"); namesMap.put("AZ", "Azerbeidzjan"); namesMap.put("BA", "Bosnië en Herzegovina"); namesMap.put("BE", "België"); namesMap.put("BG", "Bulgarije"); namesMap.put("BH", "Bahrein"); namesMap.put("BL", "Saint-Barthélemy"); namesMap.put("BQ", "Caribisch Nederland"); namesMap.put("BR", "Brazilië"); namesMap.put("BS", "Bahama’s"); namesMap.put("BV", "Bouveteiland"); namesMap.put("CC", "Cocoseilanden"); namesMap.put("CD", "Congo-Kinshasa"); namesMap.put("CF", "Centraal-Afrikaanse Republiek"); namesMap.put("CG", "Congo-Brazzaville"); namesMap.put("CH", "Zwitserland"); namesMap.put("CI", "Ivoorkust"); namesMap.put("CK", "Cookeilanden"); namesMap.put("CL", "Chili"); namesMap.put("CM", "Kameroen"); namesMap.put("CP", "Clipperton"); namesMap.put("CV", "Kaapverdië"); namesMap.put("CX", "Christmaseiland"); namesMap.put("CZ", "Tsjechië"); namesMap.put("DE", "Duitsland"); namesMap.put("DK", "Denemarken"); namesMap.put("DO", "Dominicaanse Republiek"); namesMap.put("DZ", "Algerije"); namesMap.put("EA", "Ceuta en Melilla"); namesMap.put("EE", "Estland"); namesMap.put("EG", "Egypte"); namesMap.put("EH", "Westelijke Sahara"); namesMap.put("ES", "Spanje"); namesMap.put("ET", "Ethiopië"); namesMap.put("EU", "Europese Unie"); namesMap.put("EZ", "eurozone"); namesMap.put("FK", "Falklandeilanden"); namesMap.put("FO", "Faeröer"); namesMap.put("FR", "Frankrijk"); namesMap.put("GB", "Verenigd Koninkrijk"); namesMap.put("GE", "Georgië"); namesMap.put("GF", "Frans-Guyana"); namesMap.put("GL", "Groenland"); namesMap.put("GN", "Guinee"); namesMap.put("GQ", "Equatoriaal-Guinea"); namesMap.put("GR", "Griekenland"); namesMap.put("GS", "Zuid-Georgia en Zuidelijke Sandwicheilanden"); namesMap.put("GW", "Guinee-Bissau"); namesMap.put("HK", "Hongkong SAR van China"); namesMap.put("HM", "Heard en McDonaldeilanden"); namesMap.put("HR", "Kroatië"); namesMap.put("HT", "Haïti"); namesMap.put("HU", "Hongarije"); namesMap.put("IC", "Canarische Eilanden"); namesMap.put("ID", "Indonesië"); namesMap.put("IE", "Ierland"); namesMap.put("IL", "Israël"); namesMap.put("IO", "Brits Indische Oceaanterritorium"); namesMap.put("IQ", "Irak"); namesMap.put("IS", "IJsland"); namesMap.put("IT", "Italië"); namesMap.put("JO", "Jordanië"); namesMap.put("KE", "Kenia"); namesMap.put("KG", "Kirgizië"); namesMap.put("KH", "Cambodja"); namesMap.put("KM", "Comoren"); namesMap.put("KN", "Saint Kitts en Nevis"); namesMap.put("KP", "Noord-Korea"); namesMap.put("KR", "Zuid-Korea"); namesMap.put("KW", "Koeweit"); namesMap.put("KY", "Kaaimaneilanden"); namesMap.put("KZ", "Kazachstan"); namesMap.put("LB", "Libanon"); namesMap.put("LC", "Saint Lucia"); namesMap.put("LT", "Litouwen"); namesMap.put("LU", "Luxemburg"); namesMap.put("LV", "Letland"); namesMap.put("LY", "Libië"); namesMap.put("MA", "Marokko"); namesMap.put("MD", "Moldavië"); namesMap.put("MF", "Saint-Martin"); namesMap.put("MG", "Madagaskar"); namesMap.put("MH", "Marshalleilanden"); namesMap.put("MK", "Macedonië"); namesMap.put("MM", "Myanmar (Birma)"); namesMap.put("MN", "Mongolië"); namesMap.put("MO", "Macau SAR van China"); namesMap.put("MP", "Noordelijke Marianen"); namesMap.put("MR", "Mauritanië"); namesMap.put("MV", "Maldiven"); namesMap.put("MY", "Maleisië"); namesMap.put("NA", "Namibië"); namesMap.put("NC", "Nieuw-Caledonië"); namesMap.put("NF", "Norfolk"); namesMap.put("NL", "Nederland"); namesMap.put("NO", "Noorwegen"); namesMap.put("NZ", "Nieuw-Zeeland"); namesMap.put("PF", "Frans-Polynesië"); namesMap.put("PG", "Papoea-Nieuw-Guinea"); namesMap.put("PH", "Filipijnen"); namesMap.put("PL", "Polen"); namesMap.put("PM", "Saint-Pierre en Miquelon"); namesMap.put("PN", "Pitcairneilanden"); namesMap.put("PS", "Palestijnse gebieden"); namesMap.put("QO", "overig Oceanië"); namesMap.put("RO", "Roemenië"); namesMap.put("RS", "Servië"); namesMap.put("RU", "Rusland"); namesMap.put("SA", "Saoedi-Arabië"); namesMap.put("SB", "Salomonseilanden"); namesMap.put("SC", "Seychellen"); namesMap.put("SD", "Soedan"); namesMap.put("SE", "Zweden"); namesMap.put("SH", "Sint-Helena"); namesMap.put("SI", "Slovenië"); namesMap.put("SJ", "Spitsbergen en Jan Mayen"); namesMap.put("SK", "Slowakije"); namesMap.put("SO", "Somalië"); namesMap.put("SS", "Zuid-Soedan"); namesMap.put("ST", "Sao Tomé en Principe"); namesMap.put("SX", "Sint-Maarten"); namesMap.put("SY", "Syrië"); namesMap.put("TC", "Turks- en Caicoseilanden"); namesMap.put("TD", "Tsjaad"); namesMap.put("TF", "Franse Gebieden in de zuidelijke Indische Oceaan"); namesMap.put("TJ", "Tadzjikistan"); namesMap.put("TL", "Oost-Timor"); namesMap.put("TN", "Tunesië"); namesMap.put("TR", "Turkije"); namesMap.put("TT", "Trinidad en Tobago"); namesMap.put("UA", "Oekraïne"); namesMap.put("UG", "Oeganda"); namesMap.put("UM", "Kleine afgelegen eilanden van de Verenigde Staten"); namesMap.put("UN", "Verenigde Naties"); namesMap.put("US", "Verenigde Staten"); namesMap.put("UZ", "Oezbekistan"); namesMap.put("VA", "Vaticaanstad"); namesMap.put("VC", "Saint Vincent en de Grenadines"); namesMap.put("VG", "Britse Maagdeneilanden"); namesMap.put("VI", "Amerikaanse Maagdeneilanden"); namesMap.put("WF", "Wallis en Futuna"); namesMap.put("YE", "Jemen"); namesMap.put("ZA", "Zuid-Afrika"); namesMap.put("ZZ", "onbekend gebied"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ <SUF>*/; }
83673_0
package be.intecbrussel; import java.util.function.Consumer; public class Opdracht2 { /*Opdracht 2: 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. */ public static void main(String[] args) { Consumer<Integer> consumer = (c) -> { if (c < 18) { System.out.println("You’re too young!"); } else if (c > 18) { System.out.println("You’re too old"); } else { System.out.println("Age not valid"); } }; consumer.accept(32); } }
zakaria67/OpdrachtenLambda
src/be/intecbrussel/Opdracht2.java
234
/*Opdracht 2: 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. */
block_comment
nl
package be.intecbrussel; import java.util.function.Consumer; public class Opdracht2 { /*Opdracht 2: <SUF>*/ public static void main(String[] args) { Consumer<Integer> consumer = (c) -> { if (c < 18) { System.out.println("You’re too young!"); } else if (c > 18) { System.out.println("You’re too old"); } else { System.out.println("Age not valid"); } }; consumer.accept(32); } }