answer stringlengths 17 10.2M |
|---|
// S y s t e m //
// This software is released under the terms of the GNU General Public //
// to report bugs & suggestions. //
package omr.score;
import omr.sheet.SystemInfo;
import omr.ui.view.Zoom;
import omr.util.Dumper;
import omr.util.Logger;
import omr.util.TreeNode;
import static omr.score.ScoreConstants.*;
import java.awt.*;
import java.util.List;
/**
* Class <code>System</code> encapsulates a system in a score.
* <p>A system contains two direct children : staves and slurs, each in its
* dedicated list.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class System
extends MusicNode
{
private static final Logger logger = Logger.getLogger(System.class);
// Related info from sheet analysis
private SystemInfo info;
// Specific Child : list of staves
private final StaveList staves;
// Specific Child : list of slurs
private final SlurList slurs;
// Top left corner of the system
private PagePoint topLeft;
// System dimensions, expressed in units
private UnitDimension dimension;
// Actual display origin
private ScorePoint origin;
// First, and last measure ids
private int firstMeasureId = 0;
private int lastMeasureId = 0;
// System //
/**
* Default constructor (needed by XML binder)
*/
public System ()
{
this(null, null, null, null);
}
// System //
/**
* Create a system with all needed parameters
*
* @param info the physical information retrieved from the sheet
* @param score the containing score
* @param topLeft the coordinate, in units, of the upper left point of the
* system in its containing score
* @param dimension the dimension of the system, expressed in units
*/
public System (SystemInfo info,
Score score,
PagePoint topLeft,
UnitDimension dimension)
{
super(score);
// Allocate stave and slur (node) lists
staves = new StaveList(this);
slurs = new SlurList(this);
this.info = info;
this.topLeft = topLeft;
this.dimension = dimension;
if (logger.isFineEnabled()) {
Dumper.dump(this, "Constructed");
}
}
// getFirstMeasureId //
/**
* Report the id of the first measure in the system, knowing that 0 is
* the id of the very first measure of the very first system in the
* score
*
* @return the first measure id
*/
public int getFirstMeasureId ()
{
return firstMeasureId;
}
// getFirstStave //
/**
* Report the first stave in this system
*
* @return the first stave entity
*/
public Stave getFirstStave ()
{
return (Stave) getStaves().get(0);
}
// getDimension //
/**
* Report the system dimension.
*
* @return the system dimension, in units
* @see #setDimension
*/
public UnitDimension getDimension ()
{
return dimension;
}
// setDimension //
/**
* Set the system dimension.
*
* <p>Width is the distance, in units, between left edge and right
* edge.
*
* <p>Height is the distance, in units, from top of first stave, down
* to bottom of last stave
*
* @param dimension system dimension, in units
*/
public void setDimension (UnitDimension dimension)
{
this.dimension = dimension;
}
// getInfo //
/**
* Report the physical information retrieved from the sheet for this
* system
*
* @return the information entity
*/
public SystemInfo getInfo ()
{
return info;
}
// setLastMeasureId //
/**
* Remember the id of the last measure in this system
*
* @param lastMeasureId last measure index
*/
public void setLastMeasureId (int lastMeasureId)
{
this.lastMeasureId = lastMeasureId;
}
// getLastMeasureId //
/**
* Report the id of the last measure in this system
*
* @return the last measure id
*/
public int getLastMeasureId ()
{
return lastMeasureId;
}
// getLastStave //
/**
* Report the last stave in this system
*
* @return the last stave entity
*/
public Stave getLastStave ()
{
return (Stave) getStaves().get(getStaves().size() - 1);
}
// setTopLeft //
/**
* Set the coordinates of the top left cormer of the system in the score
*
* @param topLeft the upper left point, with coordinates in units, in
* virtual score page
*/
public void setTopLeft (PagePoint topLeft)
{
this.topLeft = topLeft;
}
// getTopLeft //
/**
* Report the coordinates of the upper left corner of this system in
* its containing score
*
* @return the top left corner
* @see #setTopLeft
*/
public PagePoint getTopLeft ()
{
return topLeft;
}
// getOrigin //
/**
* Report the origin for this system, in the horizontal score display
*
* @return the display origin
*/
public ScorePoint getOrigin ()
{
return origin;
}
// getRightPosition //
/**
* Return the actual display position of the right side.
*
* @return the display abscissa of the right system edge
*/
public int getRightPosition ()
{
return (origin.x + dimension.width) - 1;
}
// setSlurs //
/**
* Set the collection of slurs
*
* @param slurs the collection of slurs
*/
public void setSlurs (List<TreeNode> slurs)
{
final List<TreeNode> list = getSlurs();
if (list != slurs) {
list.clear();
list.addAll(slurs);
}
}
// getSlurs //
/**
* Report the collection of slurs
*
* @return the slur list, which may be empty but not null
*/
public List<TreeNode> getSlurs ()
{
return slurs.getChildren();
}
// setStaves //
/**
* Set the collection of staves
*
* @param staves the collection of staves
*/
public void setStaves (List<TreeNode> staves)
{
final List<TreeNode> list = getStaves();
if (list != staves) {
list.clear();
list.addAll(staves);
}
}
// getStaves //
/**
* Report the collection of staves
*
* @return the stave list
*/
public List<TreeNode> getStaves ()
{
return staves.getChildren();
}
// addChild //
/**
* Overrides normal behavior, to deal with the separation of children
* into slurs and staves
*
* @param node the node to insert (either a slur or a stave)
*/
@Override
public void addChild (TreeNode node)
{
if (node instanceof Stave) {
staves.addChild(node);
node.setContainer(staves);
} else if (node instanceof Slur) {
slurs.addChild(node);
node.setContainer(slurs);
} else if (node instanceof MusicNode) {
children.add(node);
node.setContainer(this);
} else {
// Programming error
Dumper.dump(node);
logger.severe("System node not Stave nor Slur");
}
}
// sheetToScore //
/**
* Compute the score display point that correspond to a given sheet
* point, since systems are displayed horizontally in the score
* display, while they are located one under the other in a sheet.
*
* @param pagPt the point in the sheet
* @param scrPt the corresponding point in score display
*
* @see #scoreToSheet
*/
public void sheetToScore (PagePoint pagPt,
ScorePoint scrPt)
{
scrPt.x = (origin.x + pagPt.x) - topLeft.x;
scrPt.y = (origin.y + pagPt.y) - topLeft.y;
}
// scoreToSheet //
/**
* Compute the point in the sheet that corresponds to a given point in
* the score display
*
* @param scrPt the point in the score display
* @param pagPt the corresponding sheet point
*
* @see #sheetToScore
*/
public void scoreToSheet (ScorePoint scrPt,
PagePoint pagPt)
{
pagPt.x = (topLeft.x + scrPt.x) - origin.x;
pagPt.y = (topLeft.y + scrPt.y) - origin.y;
}
// toString //
/**
* Report a readable description
*
* @return a string based on upper left corner
*/
@Override
public String toString ()
{
return "{System" + " topLeft=" + topLeft + " dimension=" + dimension
+ "}";
}
// xLocate //
/**
* Return the position of given x, relative to the system.
*
* @param x the abscissa value of the point (scrPt)
*
* @return -1 for left, 0 for middle, +1 for right
*/
public int xLocate (int x)
{
if (x < origin.x) {
return -1;
}
if (x > getRightPosition()) {
return +1;
}
return 0;
}
// yLocate //
/**
* Return the position of given y, relative to the system
*
* @param y the ordinate value of the point (pagPt)
*
* @return -1 for above, 0 for middle, +1 for below
*/
public int yLocate (int y)
{
if (y < topLeft.y) {
return -1;
}
if (y > (topLeft.y + dimension.height + STAFF_HEIGHT)) {
return +1;
}
return 0;
}
// computeNode //
/**
* The <code>computeNode</code> method overrides the normal routine,
* for specific system computation. The various 'systems' are aligned
* horizontally, rather than vertically as they were in the original
* music sheet.
*
* @return true
*/
@Override
protected boolean computeNode ()
{
super.computeNode();
// Is there a Previous System ?
System prevSystem = (System) getPreviousSibling();
if (prevSystem == null) {
// Very first system in the score
origin = new ScorePoint();
origin.move (SCORE_INIT_X, SCORE_INIT_Y);
firstMeasureId = 0;
} else {
// Not the first system
origin = new ScorePoint();
origin.setLocation (prevSystem.origin);
origin.translate(prevSystem.dimension.width - 1 + INTER_SYSTEM, 0);
firstMeasureId = prevSystem.lastMeasureId;
}
if (logger.isFineEnabled()) {
Dumper.dump(this, "Computed");
}
return true;
}
// paintNode //
/**
* Specific <code>paintNode</code> method, just the system left and
* right sides are drawn
*
* @param g the graphic context
* @param comp the containing component
*
* @return true if painted was actually done, so that depending
* entities (stave, slurs) are also rendered, false otherwise
* to stop the painting
*/
@Override
protected boolean paintNode (Graphics g,
Zoom zoom,
Component comp)
{
// What is the clipping region
Rectangle clip = g.getClipBounds();
// Check that our system is impacted
if (xIntersect(zoom.unscaled(clip.x),
zoom.unscaled(clip.x + clip.width))) {
g.setColor(Color.lightGray);
// Draw the system left edge
g.drawLine(zoom.scaled(origin.x),
zoom.scaled(origin.y),
zoom.scaled(origin.x),
zoom.scaled(origin.y + dimension.height + STAFF_HEIGHT));
// Draw the system right edge
g.drawLine(zoom.scaled(origin.x + dimension.width),
zoom.scaled(origin.y),
zoom.scaled(origin.x + dimension.width),
zoom.scaled(origin.y + dimension.height + STAFF_HEIGHT));
return true;
} else {
return false;
}
}
// xIntersect //
/**
* Check for intersection of a given stick determined by (left, right)
* with the system abscissa range
*
* @param left min abscissa
* @param right max abscissa
*
* @return true if overlap, false otherwise
*/
private boolean xIntersect (int left,
int right)
{
if (left > getRightPosition()) {
return false;
}
if (right < origin.x) {
return false;
}
return true;
}
// StaveList //
private static class StaveList
extends MusicNode
{
StaveList (MusicNode container)
{
super(container);
}
}
// SlurList //
private static class SlurList
extends MusicNode
{
SlurList (MusicNode container)
{
super(container);
}
}
} |
package soot.toolkits.exceptions;
import java.util.Iterator;
import soot.*;
import soot.baf.*;
import soot.jimple.*;
import soot.grimp.*;
import soot.shimple.ShimpleValueSwitch;
import soot.shimple.PhiExpr;
import soot.toolkits.exceptions.*;
/**
* A {@link ThrowAnalysis} which returns the set of runtime exceptions
* and errors that might be thrown by the bytecode instructions
* represented by a unit, as indicated by the Java Virtual Machine
* specification. I.e. this analysis is based entirely on the
* “opcode” of the unit, the types of its arguments, and
* the values of constant arguments.
*
* <p>The <code>mightThrow</code> methods could be declared static.
* They are left virtual to facilitate testing. For example,
* to verify that the expressions in a method call are actually being
* examined, a test case can override the mightThrow(SootMethod)
* with an implementation which returns the empty set instead of
* all possible exceptions.
*/
public class UnitThrowAnalysis implements ThrowAnalysis {
// Cache the response to mightThrowImplicitly():
private final ThrowableSet implicitThrowExceptions
= ThrowableSet.Manager.v().VM_ERRORS
.add(ThrowableSet.Manager.v().NULL_POINTER_EXCEPTION)
.add(ThrowableSet.Manager.v().ILLEGAL_MONITOR_STATE_EXCEPTION);
/**
* Constructs a <code>UnitThrowAnalysis</code> for inclusion in
* Soot's global variable manager, {@link G}.
*
* @param g guarantees that the constructor may only be called
* from {@link Singletons}.
*/
public UnitThrowAnalysis(Singletons.Global g) {}
/**
* A protected constructor for use by unit tests.
*/
protected UnitThrowAnalysis() {}
/**
* Returns the single instance of <code>UnitThrowAnalysis</code>.
*
* @return Soot's <code>UnitThrowAnalysis</code>.
*/
public static UnitThrowAnalysis v() { return G.v().soot_toolkits_exceptions_UnitThrowAnalysis(); }
public ThrowableSet mightThrow(Unit u) {
UnitSwitch sw = new UnitSwitch();
u.apply(sw);
return sw.getResult();
}
public ThrowableSet mightThrowExplicitly(ThrowInst t) {
// Deducing the type at the top of the Baf stack is beyond me, so...
return ThrowableSet.Manager.v().ALL_THROWABLES;
}
public ThrowableSet mightThrowImplicitly(ThrowInst t) {
return implicitThrowExceptions;
}
public ThrowableSet mightThrowExplicitly(ThrowStmt t) {
Value thrownExpression = t.getOp();
Type thrownType = thrownExpression.getType();
if (thrownType == null || thrownType instanceof UnknownType) {
// We can't identify the type of thrownExpression, so...
return ThrowableSet.Manager.v().ALL_THROWABLES;
} else if (! (thrownType instanceof RefType)) {
throw new IllegalStateException("UnitThrowAnalysis StmtSwitch: type of throw argument is not a RefType!");
} else {
ThrowableSet result = ThrowableSet.Manager.v().EMPTY;
if (thrownExpression instanceof NewInvokeExpr) {
// In this case, we know the exact type of the
// argument exception.
result = result.add((RefType) thrownType);
} else {
result = result.add(AnySubType.v((RefType) thrownType));
}
return result;
}
}
public ThrowableSet mightThrowImplicitly(ThrowStmt t) {
return implicitThrowExceptions;
}
ThrowableSet mightThrow(Value v) {
ValueSwitch sw = new ValueSwitch();
v.apply(sw);
return sw.getResult();
}
/**
* Returns the set of types that might be thrown as a result of
* calling the specified method.
*
* @param m method whose exceptions are to be returned.
*
* @return a representation of the set of {@link
* java.lang.Throwable Throwable} types that <code>m</code> might
* throw.
*/
ThrowableSet mightThrow(SootMethod m) {
// In the absence of an interprocedural analysis,
// m could throw anything.
return ThrowableSet.Manager.v().ALL_THROWABLES;
}
private static final IntConstant INT_CONSTANT_ZERO = IntConstant.v(0);
private static final LongConstant LONG_CONSTANT_ZERO = LongConstant.v(0);
protected class UnitSwitch implements InstSwitch, StmtSwitch {
private ThrowableSet.Manager mgr = ThrowableSet.Manager.v();
// Asynchronous errors are always possible:
private ThrowableSet result = mgr.VM_ERRORS;
ThrowableSet getResult() {
return result;
}
public void caseReturnVoidInst(ReturnVoidInst i) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
}
public void caseReturnInst(ReturnInst i) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
}
public void caseNopInst(NopInst i) {
}
public void caseGotoInst(GotoInst i) {
}
public void casePushInst(PushInst i) {
}
public void casePopInst(PopInst i) {
}
public void caseIdentityInst(IdentityInst i) {
}
public void caseStoreInst(StoreInst i) {
}
public void caseLoadInst(LoadInst i) {
}
public void caseArrayWriteInst(ArrayWriteInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
if (i.getOpType() instanceof RefType) {
result = result.add(mgr.ARRAY_STORE_EXCEPTION);
}
}
public void caseArrayReadInst(ArrayReadInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
}
public void caseIfNullInst(IfNullInst i) {
}
public void caseIfNonNullInst(IfNonNullInst i) {
}
public void caseIfEqInst(IfEqInst i) {
}
public void caseIfNeInst(IfNeInst i) {
}
public void caseIfGtInst(IfGtInst i) {
}
public void caseIfGeInst(IfGeInst i) {
}
public void caseIfLtInst(IfLtInst i) {
}
public void caseIfLeInst(IfLeInst i) {
}
public void caseIfCmpEqInst(IfCmpEqInst i) {
}
public void caseIfCmpNeInst(IfCmpNeInst i) {
}
public void caseIfCmpGtInst(IfCmpGtInst i) {
}
public void caseIfCmpGeInst(IfCmpGeInst i) {
}
public void caseIfCmpLtInst(IfCmpLtInst i) {
}
public void caseIfCmpLeInst(IfCmpLeInst i) {
}
public void caseStaticGetInst(StaticGetInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
public void caseStaticPutInst(StaticPutInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
public void caseFieldGetInst(FieldGetInst i) {
result = result.add(mgr.RESOLVE_FIELD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
public void caseFieldPutInst(FieldPutInst i) {
result = result.add(mgr.RESOLVE_FIELD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
public void caseInstanceCastInst(InstanceCastInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
result = result.add(mgr.CLASS_CAST_EXCEPTION);
}
public void caseInstanceOfInst(InstanceOfInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
}
public void casePrimitiveCastInst(PrimitiveCastInst i) {
}
public void caseStaticInvokeInst(StaticInvokeInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
result = result.add(mightThrow(i.getMethod()));
}
public void caseVirtualInvokeInst(VirtualInvokeInst i) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(i.getMethod()));
}
public void caseInterfaceInvokeInst(InterfaceInvokeInst i) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(i.getMethod()));
}
public void caseSpecialInvokeInst(SpecialInvokeInst i) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(i.getMethod()));
}
public void caseThrowInst(ThrowInst i) {
result = mightThrowImplicitly(i);
result = result.add(mightThrowExplicitly(i));
}
public void caseAddInst(AddInst i) {
}
public void caseAndInst(AndInst i) {
}
public void caseOrInst(OrInst i) {
}
public void caseXorInst(XorInst i) {
}
public void caseArrayLengthInst(ArrayLengthInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
public void caseCmpInst(CmpInst i) {
}
public void caseCmpgInst(CmpgInst i) {
}
public void caseCmplInst(CmplInst i) {
}
public void caseDivInst(DivInst i) {
if (i.getOpType() instanceof IntegerType ||
i.getOpType() == LongType.v()) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
}
}
public void caseIncInst(IncInst i) {
}
public void caseMulInst(MulInst i) {
}
public void caseRemInst(RemInst i) {
if (i.getOpType() instanceof IntegerType ||
i.getOpType() == LongType.v()) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
}
}
public void caseSubInst(SubInst i) {
}
public void caseShlInst(ShlInst i) {
}
public void caseShrInst(ShrInst i) {
}
public void caseUshrInst(UshrInst i) {
}
public void caseNewInst(NewInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
public void caseNegInst(NegInst i) {
}
public void caseSwapInst(SwapInst i) {
}
public void caseDup1Inst(Dup1Inst i) {
}
public void caseDup2Inst(Dup2Inst i) {
}
public void caseDup1_x1Inst(Dup1_x1Inst i) {
}
public void caseDup1_x2Inst(Dup1_x2Inst i) {
}
public void caseDup2_x1Inst(Dup2_x1Inst i) {
}
public void caseDup2_x2Inst(Dup2_x2Inst i) {
}
public void caseNewArrayInst(NewArrayInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS); // Could be omitted for primitive arrays.
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
public void caseNewMultiArrayInst(NewMultiArrayInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
public void caseLookupSwitchInst(LookupSwitchInst i) {
}
public void caseTableSwitchInst(TableSwitchInst i) {
}
public void caseEnterMonitorInst(EnterMonitorInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
public void caseExitMonitorInst(ExitMonitorInst i) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
public void caseAssignStmt(AssignStmt s) {
Value lhs = s.getLeftOp();
if (lhs instanceof ArrayRef &&
(lhs.getType() instanceof UnknownType ||
lhs.getType() instanceof RefType)) {
// This corresponds to an aastore byte code.
result = result.add(mgr.ARRAY_STORE_EXCEPTION);
}
result = result.add(mightThrow(s.getLeftOp()));
result = result.add(mightThrow(s.getRightOp()));
}
public void caseBreakpointStmt(BreakpointStmt s) {}
public void caseEnterMonitorStmt(EnterMonitorStmt s) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(s.getOp()));
}
public void caseExitMonitorStmt(ExitMonitorStmt s) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(s.getOp()));
}
public void caseGotoStmt(GotoStmt s) {
}
public void caseIdentityStmt(IdentityStmt s) {}
// Perhaps IdentityStmt shouldn't even return VM_ERRORS,
// since it corresponds to no bytecode instructions whatsoever.
public void caseIfStmt(IfStmt s) {
result = result.add(mightThrow(s.getCondition()));
}
public void caseInvokeStmt(InvokeStmt s) {
result = result.add(mightThrow(s.getInvokeExpr()));
}
public void caseLookupSwitchStmt(LookupSwitchStmt s) {
result = result.add(mightThrow(s.getKey()));
}
public void caseNopStmt(NopStmt s) {
}
public void caseRetStmt(RetStmt s) {
// Soot should never produce any RetStmt, since
// it implements jsr with gotos.
}
public void caseReturnStmt(ReturnStmt s) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
result = result.add(mightThrow(s.getOp()));
}
public void caseReturnVoidStmt(ReturnVoidStmt s) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
}
public void caseTableSwitchStmt(TableSwitchStmt s) {
result = result.add(mightThrow(s.getKey()));
}
public void caseThrowStmt(ThrowStmt s) {
result = mightThrowImplicitly(s);
result = result.add(mightThrowExplicitly(s));
}
public void defaultCase(Object obj) {
}
}
protected class ValueSwitch implements GrimpValueSwitch, ShimpleValueSwitch {
private ThrowableSet.Manager mgr =
ThrowableSet.Manager.v();
// Asynchronous errors are always possible:
private ThrowableSet result = mgr.VM_ERRORS;
ThrowableSet getResult() {
return result;
}
// Declared by ConstantSwitch interface:
public void caseDoubleConstant(DoubleConstant c) {
}
public void caseFloatConstant(FloatConstant c) {
}
public void caseIntConstant(IntConstant c) {
}
public void caseLongConstant(LongConstant c) {
}
public void caseNullConstant(NullConstant c) {
}
public void caseStringConstant(StringConstant c) {
}
// Declared by ExprSwitch interface:
public void caseAddExpr(AddExpr expr) {
caseBinopExpr(expr);
}
public void caseAndExpr(AndExpr expr) {
caseBinopExpr(expr);
}
public void caseCmpExpr(CmpExpr expr) {
caseBinopExpr(expr);
}
public void caseCmpgExpr(CmpgExpr expr) {
caseBinopExpr(expr);
}
public void caseCmplExpr(CmplExpr expr) {
caseBinopExpr(expr);
}
public void caseDivExpr(DivExpr expr) {
caseBinopDivExpr(expr);
}
public void caseEqExpr(EqExpr expr) {
caseBinopExpr(expr);
}
public void caseNeExpr(NeExpr expr) {
caseBinopExpr(expr);
}
public void caseGeExpr(GeExpr expr) {
caseBinopExpr(expr);
}
public void caseGtExpr(GtExpr expr) {
caseBinopExpr(expr);
}
public void caseLeExpr(LeExpr expr) {
caseBinopExpr(expr);
}
public void caseLtExpr(LtExpr expr) {
caseBinopExpr(expr);
}
public void caseMulExpr(MulExpr expr) {
caseBinopExpr(expr);
}
public void caseOrExpr(OrExpr expr) {
caseBinopExpr(expr);
}
public void caseRemExpr(RemExpr expr) {
caseBinopDivExpr(expr);
}
public void caseShlExpr(ShlExpr expr) {
caseBinopExpr(expr);
}
public void caseShrExpr(ShrExpr expr) {
caseBinopExpr(expr);
}
public void caseUshrExpr(UshrExpr expr) {
caseBinopExpr(expr);
}
public void caseSubExpr(SubExpr expr) {
caseBinopExpr(expr);
}
public void caseXorExpr(XorExpr expr) {
caseBinopExpr(expr);
}
public void caseInterfaceInvokeExpr(InterfaceInvokeExpr expr) {
caseInstanceInvokeExpr(expr);
}
public void caseSpecialInvokeExpr(SpecialInvokeExpr expr) {
caseInstanceInvokeExpr(expr);
}
public void caseStaticInvokeExpr(StaticInvokeExpr expr) {
result = result.add(mgr.INITIALIZATION_ERRORS);
for (int i = 0; i < expr.getArgCount(); i++) {
result = result.add(mightThrow(expr.getArg(i)));
}
result = result.add(mightThrow(expr.getMethod()));
}
public void caseVirtualInvokeExpr(VirtualInvokeExpr expr) {
caseInstanceInvokeExpr(expr);
}
public void caseCastExpr(CastExpr expr) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
Type fromType = expr.getOp().getType();
Type toType = expr.getCastType();
if (toType instanceof RefLikeType) {
// fromType might still be unknown when we are called,
// but toType will have a value.
FastHierarchy h = Scene.v().getOrMakeFastHierarchy();
if (fromType == null || fromType instanceof UnknownType ||
((! (fromType instanceof NullType)) &&
(! h.canStoreType(fromType, toType)))) {
result = result.add(mgr.CLASS_CAST_EXCEPTION);
}
}
result = result.add(mightThrow(expr.getOp()));
}
public void caseInstanceOfExpr(InstanceOfExpr expr) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
result = result.add(mightThrow(expr.getOp()));
}
public void caseNewArrayExpr(NewArrayExpr expr) {
if (expr.getBaseType() instanceof RefLikeType) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
}
Value count = expr.getSize();
if ((! (count instanceof IntConstant)) ||
(((IntConstant) count).lessThan(INT_CONSTANT_ZERO)
.equals(INT_CONSTANT_ZERO))) {
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
result = result.add(mightThrow(count));
}
public void caseNewMultiArrayExpr(NewMultiArrayExpr expr) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
for (int i = 0; i < expr.getSizeCount(); i++) {
Value count = expr.getSize(i);
if ((! (count instanceof IntConstant)) ||
(((IntConstant) count).lessThan(INT_CONSTANT_ZERO)
.equals(INT_CONSTANT_ZERO))) {
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
result = result.add(mightThrow(count));
}
}
public void caseNewExpr(NewExpr expr) {
result = result.add(mgr.INITIALIZATION_ERRORS);
for (Iterator i = expr.getUseBoxes().iterator(); i.hasNext(); ) {
ValueBox box = (ValueBox) i.next();
result = result.add(mightThrow(box.getValue()));
}
}
public void caseLengthExpr(LengthExpr expr) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(expr.getOp()));
}
public void caseNegExpr(NegExpr expr) {
result = result.add(mightThrow(expr.getOp()));
}
// Declared by RefSwitch interface:
public void caseArrayRef(ArrayRef ref) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
result = result.add(mightThrow(ref.getBase()));
result = result.add(mightThrow(ref.getIndex()));
}
public void caseStaticFieldRef(StaticFieldRef ref) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
public void caseInstanceFieldRef(InstanceFieldRef ref) {
result = result.add(mgr.RESOLVE_FIELD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(ref.getBase()));
}
public void caseParameterRef(ParameterRef v) {
}
public void caseCaughtExceptionRef(CaughtExceptionRef v) {
}
public void caseThisRef(ThisRef v) {
}
public void caseLocal(Local l) {
}
public void caseNewInvokeExpr(NewInvokeExpr e) {
caseStaticInvokeExpr(e);
}
public void casePhiExpr(PhiExpr e) {
for (Iterator i = e.getUseBoxes().iterator(); i.hasNext(); ) {
ValueBox box = (ValueBox) i.next();
result = result.add(mightThrow(box.getValue()));
}
}
public void defaultCase(Object obj) {
}
// The remaining cases are not declared by GrimpValueSwitch,
// but are used to factor out code common to several cases.
private void caseBinopExpr(BinopExpr expr) {
result = result.add(mightThrow(expr.getOp1()));
result = result.add(mightThrow(expr.getOp2()));
}
private void caseBinopDivExpr(BinopExpr expr) {
// Factors out code common to caseDivExpr and caseRemExpr.
// The checks against constant divisors would perhaps be
// better performed in a later pass, post-constant-propagation.
Value divisor = expr.getOp2();
Type divisorType = divisor.getType();
if (divisorType instanceof UnknownType) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
} else if ((divisorType instanceof IntegerType) &&
((! (divisor instanceof IntConstant)) ||
(((IntConstant) divisor).equals(INT_CONSTANT_ZERO)))) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
} else if ((divisorType == LongType.v()) &&
((! (divisor instanceof LongConstant)) ||
(((LongConstant) divisor).equals(LONG_CONSTANT_ZERO)))) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
}
caseBinopExpr(expr);
}
private void caseInstanceInvokeExpr(InstanceInvokeExpr expr) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
for (int i = 0; i < expr.getArgCount(); i++) {
result = result.add(mightThrow(expr.getArg(i)));
}
result = result.add(mightThrow(expr.getBase()));
result = result.add(mightThrow(expr.getMethod()));
}
}
} |
package brave.http;
import com.google.inject.Module;
import com.google.inject.util.Modules;
import ratpack.exec.Promise;
import ratpack.guice.Guice;
import ratpack.test.embed.EmbeddedApp;
import ratpack.zipkin.ServerTracingModule;
import java.io.IOException;
import java.net.URI;
public class ITServerTracingModule extends ITHttpServer {
private EmbeddedApp app;
@Override
protected void init() throws Exception {
Module tracingModule = Modules
.override(new ServerTracingModule())
.with(binder -> binder.bind(HttpTracing.class).toInstance(httpTracing));
app = EmbeddedApp
.of(server ->
server.registry(Guice.registry(binding -> binding.module(tracingModule)))
.handlers(chain -> chain
.get("/foo", ctx -> ctx.getResponse().send("bar"))
.get("/async", ctx ->
Promise.async(f -> f.success("bar")).then(ctx::render)
)
.get("/badrequest", ctx -> ctx.getResponse().status(400).send())
.get("/child", ctx -> {
HttpTracing httpTracing = ctx.get(HttpTracing.class);
httpTracing.tracing().tracer().nextSpan().name("child").start().finish();
ctx.getResponse().send("happy");
})
.get("/extra", ctx -> ctx.getResponse().send("joey"))
.get("/exception", ctx -> {
throw new IOException();
})
.get("/exceptionAsync",
ctx -> Promise.async((f) -> f.error(new IOException())).then(ctx::render)
)
.all(ctx -> ctx.getResponse().status(404).send()))
);
}
@Override
protected String url(final String path) {
URI uri = app.getAddress();
return String
.format("%s://%s:%d/%s", uri.getScheme(), "127.0.0.1", uri.getPort(), path);
}
} |
package ch.x01.fuzzy.api;
import ch.x01.fuzzy.api.FuzzyEngine.InputVariable;
import ch.x01.fuzzy.api.FuzzyEngine.OutputVariable;
import ch.x01.fuzzy.core.FuzzyEngineException;
import org.junit.Test;
import static ch.x01.fuzzy.api.FuzzyModel.LinguisticVariable.lv;
import static ch.x01.fuzzy.api.FuzzyModel.Term.trapezoid;
import static ch.x01.fuzzy.api.FuzzyModel.Term.triangle;
import static ch.x01.fuzzy.api.FuzzyModel.model;
import static org.junit.Assert.assertEquals;
public class FuzzyEngineTest {
/**
* A simple reference system is given, which models the brake behaviour of a car driver
* depending on the car speed. The inference machine should determine the brake force for a
* given car speed. The speed is specified by the two linguistic terms 'low' and 'medium', and
* the brake force by 'moderate' and 'strong'.
*/
@Test
public void testCar() {
FuzzyModel model = model().name("car")
.vars(lv().usage("input")
.name("carSpeed")
.terms(triangle().name("low")
.start(20)
.top(60)
.end(100),
triangle().name("medium")
.start(60)
.top(100)
.end(140)),
lv().usage("output")
.name("brakeForce")
.terms(triangle().name("moderate")
.start(40)
.top(60)
.end(80),
triangle().name("strong")
.start(70)
.top(85)
.end(100)))
.rules("if carSpeed is low then brakeForce is moderate",
"if carSpeed is medium then brakeForce is strong");
FuzzyEngine engine = new FuzzyEngine(model);
OutputVariable output = engine.evaluate(new InputVariable("carSpeed", 70));
// test output value
assertEquals(65.9939, output.getValue(), 0.01);
System.out.println(output);
}
@Test
public void testCarInputValueRange() {
FuzzyModel model = model().name("car")
.vars(lv().usage("input")
.name("carSpeed")
.terms(triangle().name("low")
.start(20)
.top(60)
.end(100),
triangle().name("medium")
.start(60)
.top(100)
.end(140)),
lv().usage("output")
.name("brakeForce")
.terms(triangle().name("moderate")
.start(40)
.top(60)
.end(80),
triangle().name("strong")
.start(70)
.top(85)
.end(100)))
.rules("if carSpeed is low then brakeForce is moderate",
"if carSpeed is medium then brakeForce is strong");
FuzzyEngine engine = new FuzzyEngine(model);
// compute output values for a range of input values
for (int i = 0; i < 50; ++i) {
double speed = 20 + i * (120.0 / 50);
InputVariable input = new InputVariable("carSpeed", speed);
OutputVariable output = engine.evaluate(input);
System.out.println(engine.printResult(input, output, 6, 2));
}
}
@Test
public void testCarTrapezoid() {
FuzzyModel model = model().name("car (trapezoid)")
.vars(lv().usage("input")
.name("carSpeed")
.terms(trapezoid().name("low")
.start(20)
.left_top(60)
.right_top(60)
.end(100),
trapezoid().name("medium")
.start(60)
.left_top(100)
.right_top(1000)
.end(140)),
lv().usage("output")
.name("brakeForce")
.terms(trapezoid().name("moderate")
.start(40)
.left_top(60)
.right_top(60)
.end(80),
trapezoid().name("strong")
.start(70)
.left_top(85)
.right_top(85)
.end(100)))
.rules("if carSpeed is low then brakeForce is moderate",
"if carSpeed is medium then brakeForce is strong");
FuzzyEngine engine = new FuzzyEngine(model);
OutputVariable output = engine.evaluate(new InputVariable("carSpeed", 70));
// test output value
assertEquals(65.9939, output.getValue(), 0.01);
System.out.println(output);
}
@Test(expected = FuzzyEngineException.class)
public void testCarInvalidModel() {
FuzzyModel model = model().name("car")
.vars(lv().usage("input")
.name("carSpeed")
.terms(triangle().name("low")
.start(20)
.top(60)
.end(100),
triangle().name("medium")
.start(60)
.top(100)
.end(140)),
lv().usage("output")
.name("breakForce")
.terms(triangle().name("moderate")
.start(40)
.top(60)
.end(80),
triangle().name("strong")
.start(70)
.top(85)
.end(100)))
.rules("if carSpeed is low then brakeForce is moderate",
"if carSpeed is medium then brakeForce is strong");
FuzzyEngine engine = new FuzzyEngine(model);
engine.evaluate(new InputVariable("carSpeed", 70));
}
@Test
public void testDimmer() {
FuzzyModel model = model().name("dimmer")
.vars(lv().usage("input")
.name("ambient")
.terms(triangle().name("dark")
.start(0)
.top(0.25)
.end(0.5),
triangle().name("medium")
.start(0.25)
.top(0.5)
.end(0.75),
triangle().name("bright")
.start(0.5)
.top(0.75)
.end(1)),
lv().usage("output")
.name("power")
.terms(triangle().name("low")
.start(0)
.top(0.25)
.end(0.5),
triangle().name("medium")
.start(0.25)
.top(0.5)
.end(0.75),
triangle().name("high")
.start(0.5)
.top(0.75)
.end(1)))
.rules("if Ambient is DARK then Power is HIGH",
"if Ambient is MEDIUM then Power is MEDIUM",
"if Ambient is BRIGHT then Power is LOW");
FuzzyEngine engine = new FuzzyEngine(model);
OutputVariable output = engine.evaluate(new InputVariable("ambient", 0.25));
// test output value
assertEquals(0.75, output.getValue(), 0.01);
System.out.println(output);
}
@Test
public void testDimmerInputValueRange() {
FuzzyModel model = model().name("dimmer")
.vars(lv().usage("input")
.name("ambient")
.terms(triangle().name("dark")
.start(0)
.top(0.25)
.end(0.5),
triangle().name("medium")
.start(0.25)
.top(0.5)
.end(0.75),
triangle().name("bright")
.start(0.5)
.top(0.75)
.end(1)),
lv().usage("output")
.name("power")
.terms(triangle().name("low")
.start(0)
.top(0.25)
.end(0.5),
triangle().name("medium")
.start(0.25)
.top(0.5)
.end(0.75),
triangle().name("high")
.start(0.5)
.top(0.75)
.end(1)))
.rules("if Ambient is DARK then Power is HIGH",
"if Ambient is MEDIUM then Power is MEDIUM",
"if Ambient is BRIGHT then Power is LOW");
FuzzyEngine engine = new FuzzyEngine(model);
// compute output values for a range of input values
for (int i = 0; i < 50; i++) {
double light = 0 + i * (1.0 / 50);
InputVariable input = new InputVariable("ambient", light);
OutputVariable output = engine.evaluate(input);
System.out.println(engine.printResult(input, output, 4, 2));
}
}
@Test
public void testDimmerBug() {
FuzzyModel model = model().name("dimmer")
.vars(lv().usage("input")
.name("ambient")
.terms(triangle().name("dark")
.start(0)
.top(0.25)
.end(0.5),
triangle().name("medium")
.start(0.25)
.top(0.5)
.end(0.75),
triangle().name("bright")
.start(0.5)
.top(0.75)
.end(1)),
lv().usage("output")
.name("power")
.terms(triangle().name("low")
.start(0)
.top(0.25)
.end(0.5),
triangle().name("medium")
.start(0.25)
.top(0.5)
.end(0.75),
triangle().name("high")
.start(0.5)
.top(0.75)
.end(1)))
.rules("if Ambient is DARK then Power is HIGH",
"if Ambient is MEDIUM then Power is MEDIUM",
"if Ambient is BRIGHT then Power is LOW");
FuzzyEngine engine = new FuzzyEngine(model);
OutputVariable output = engine.evaluate(new InputVariable("ambient", 0.50));
// test output value
assertEquals(0.49, output.getValue(), 0.01);
System.out.println(output);
}
// @Test
public void testFuzzyEngineMultiInVars() {
FuzzyModel model = null;
FuzzyEngine engine = new FuzzyEngine(model);
OutputVariable output = engine.evaluate(new InputVariable("", 0), new InputVariable("", 0));
System.out.println(output);
}
} |
package com.jcabi.github;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.validation.constraints.NotNull;
import org.hamcrest.CustomTypeSafeMatcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
/**
* Test for nullability.
* Checks that all public methods in clases in package {@code com.jcabi.github }
* have {@code @NotNull} annotation for return value and for input arguments
* (if they are not scalar).
* @todo #661:30min Ensure that all methods return values and input arguments
* are annotated with {@code @NotNull} and remove the {@code @Ignore}
* annotation.
* @author Paul Polishchuk (ppol@ua.fm)
* @version $Id$
*/
public final class NullabilityTest {
/**
* ClasspathRule.
* @checkstyle VisibilityModifierCheck (3 lines)
*/
@Rule
public final transient ClasspathRule classpath = new ClasspathRule();
/**
* Test for nullability.
* Checks that all public methods in clases in package
* {@code com.jcabi.github }have {@code @NotNull} annotation for return
* value and for input arguments(if they are not scalar).
*
* @throws Exception If some problem inside
*/
@Test
@Ignore
public void checkNullability() throws Exception {
MatcherAssert.assertThat(
this.classpath.allPublicMethods(),
Matchers.everyItem(
// @checkstyle LineLength (1 line)
new CustomTypeSafeMatcher<Method>("parameter and return value is annotated with @NonNull") {
@Override
protected boolean matchesSafely(final Method item) {
return item.getReturnType().isPrimitive()
|| item.isAnnotationPresent(NotNull.class)
&& allParamsAnnotated(item);
}
}
)
);
}
/**
* Checks if all params in method have given annotation.
* @param method Method to be checked
* @return True if all parameters of method have given annotation
*/
private boolean allParamsAnnotated(final Method method) {
return Iterables.all(
ContiguousSet.create(
Range.closedOpen(0, method.getParameterTypes().length),
DiscreteDomain.integers()
),
new Predicate<Integer>() {
@Override
public boolean apply(final Integer index) {
return method.getParameterTypes()[index].isPrimitive()
|| (!method.getParameterTypes()[index].isPrimitive()
&& Collections2.transform(
// @checkstyle LineLength (2 lines)
Arrays.asList(method.getParameterAnnotations()[index]),
new Function<Annotation, Class<? extends Annotation>>() {
@Override
public Class<? extends Annotation> apply(
final Annotation input) {
return input.annotationType();
}
}
).contains(NotNull.class));
}
}
);
}
} |
import junit.framework.TestCase;
import org.apache.log4j.Logger;
public class GoldSitesTest extends TestCase {
private static final Logger logger = Logger.getLogger(GoldSitesTest.class);
public void testHuffingtonPost() {
ContentExtractor contentExtractor = new ContentExtractor();
String url = "http:
Article article = contentExtractor.extractContent(url);
assertEquals("Federal Reserve's Low Rate Policy Is A 'Dangerous Gamble,' Says Top Central Bank Official", article.getTitle());
assertEquals("federal, reserve's, low, rate, policy, is, a, 'dangerous, gamble,', says, top, central, bank, official, business", article.getMetaKeywords());
assertEquals("A top regional Federal Reserve official sharply criticized Friday the Fed's ongoing policy of keeping interest rates near zero -- and at record lows -- as a \"dangerous gamble.\"", article.getMetaDescription());
assertTrue(article.getCleanedArticleText().startsWith("A top regional Federal Reserve official sharply"));
}
public void testTechCrunch() {
ContentExtractor contentExtractor = new ContentExtractor();
String url = "http://techcrunch.com/2010/08/13/gantto-takes-on-microsoft-project-with-web-based-project-management-application/";
Article article = contentExtractor.extractContent(url);
assertEquals("Gantto Takes On Microsoft Project With Web-Based Project Management Application", article.getTitle());
assertTrue(article.getCleanedArticleText().startsWith("Y Combinator-backed Gantto is launching"));
assertTrue(article.getTopImage().getImageSrc().equals("http://tctechcrunch.files.wordpress.com/2010/08/tour.jpg"));
}
public void testCNN() {
ContentExtractor contentExtractor = new ContentExtractor();
String url = "http:
Article article = contentExtractor.extractContent(url);
assertEquals("Democrats to use Social Security against GOP this fall", article.getTitle());
assertTrue(article.getCleanedArticleText().startsWith("Washington (CNN) -- Democrats pledged "));
assertTrue(article.getTopImage().getImageSrc().equals("http://i.cdn.turner.com/cnn/2010/POLITICS/08/13/democrats.social.security/story.kaine.gi.jpg"));
}
public void testBusinessWeek() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertEquals("Olivia Munn: Queen of the Uncool", article.getTitle());
assertTrue(article.getCleanedArticleText().startsWith("Six years ago, Olivia Munn arrived in Hollywood with fading ambitions of making it as a sports reporter and set about deploying"));
assertTrue(article.getTopImage().getImageSrc().equals("http://images.businessweek.com/mz/10/34/370/1034_mz_66popmunnessa.jpg"));
}
public void testBusinessWeek2() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("There's discord on Wall Street: Strategists at major American investment banks see a"));
assertTrue(article.getTopImage().getImageSrc().equals("http://images.businessweek.com/mz/covers/current_120x160.jpg"));
}
public void testFoxNews() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Russia's announcement that it will help Iran get nuclear fuel is raising questions"));
assertTrue(article.getTopImage().getImageSrc().equals("http://a57.foxnews.com/static/managed/img/Politics/397/224/startsign.jpg"));
}
public void testAOLNews() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("WASHINGTON (Aug. 13) -- Declaring "the maritime soul of the Marine Corps"));
assertTrue(article.getTopImage().getImageSrc().equals("http://o.aolcdn.com/photo-hub/news_gallery/6/8/680919/1281734929876.JPEG"));
}
public void testWallStreetJournal() {
String url = "http://online.wsj.com/article/SB10001424052748704532204575397061414483040.html";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("The Obama administration has paid out less than a third of the nearly $230 billion"));
assertTrue(article.getTopImage().getImageSrc().equals("http://si.wsj.net/public/resources/images/OB-JO747_stimul_G_20100814113803.jpg"));
}
public void testUSAToday() {
String url = "http://content.usatoday.com/communities/thehuddle/post/2010/08/brett-favre-practices-set-to-speak-about-return-to-minnesota-vikings/1";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Brett Favre couldn't get away from the"));
assertTrue(article.getTopImage().getImageSrc().equals("http://i.usatoday.net/communitymanager/_photos/the-huddle/2010/08/18/favrespeaksx-inset-community.jpg"));
}
public void testUSAToday2() {
String url = "http://content.usatoday.com/communities/driveon/post/2010/08/gm-finally-files-for-ipo/1";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("General Motors just filed with the Securities and Exchange "));
assertTrue(article.getTopImage().getImageSrc().equals("http://i.usatoday.net/communitymanager/_photos/drive-on/2010/08/18/cruzex-wide-community.jpg"));
}
public void testESPN() {
String url = "http://sports.espn.go.com/espn/commentary/news/story?id=5461430";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("If you believe what college football coaches have said about sports"));
assertTrue(article.getTopImage().getImageSrc().equals("http://a.espncdn.com/photo/2010/0813/ncf_i_mpouncey1_300.jpg"));
}
public void testESPN2() {
String url = "http://sports.espn.go.com/golf/pgachampionship10/news/story?id=5463456";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("SHEBOYGAN, Wis. -- The only number that matters at the PGA Championship"));
assertTrue(article.getTopImage().getImageSrc().equals("http://a.espncdn.com/media/motion/2010/0813/dm_100814_pga_rinaldi.jpg"));
}
public void testWashingtonPost() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("The Supreme Court sounded "));
assertTrue(article.getTopImage().getImageSrc().equals("http://media3.washingtonpost.com/wp-dyn/content/photo/2010/10/09/PH2010100904575.jpg"));
}
public void testGizmodo() {
String url = "http://gizmodo.com/#!5616256/xbox-kinect-gets-its-fight-club";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("You love to punch your arms through the air"));
assertTrue(article.getTopImage().getImageSrc().equals("http://cache.gawkerassets.com/assets/images/9/2010/08/500x_fighters_uncaged__screenshot_3b__jawbreaker.jpg"));
}
public void testEngadget() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Streaming and downloading TV content to mobiles is nice"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testBoingBoing() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Dr. Laura Schlessinger is leaving radio to regain"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testWired() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("On November 25, 1980, professional boxing"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
assertTrue(article.getTitle().equals("Stress Hormones Could Predict Boxing Dominance"));
}
public void tetGigaOhm() {
String url = "http://gigaom.com/apple/apples-next-macbook-an-800-mac-for-the-masses/";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("The MacBook Air is a bold move forward "));
assertTrue(article.getTopImage().getImageSrc().equals("http://gigapple.files.wordpress.com/2010/10/macbook-feature.png?w=300&h=200"));
}
public void testMashable() {
String url = "http://mashable.com/2010/08/18/how-tonot-to-ask-someone-out-online/";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Imagine, if you will, a crowded dance floor"));
assertTrue(article.getTopImage().getImageSrc().equals("http://9.mshcdn.com/wp-content/uploads/2010/07/love.jpg"));
}
public void testReadWriteWeb() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("In the heart of downtown Chandler, Arizona"));
assertTrue(article.getTopImage().getImageSrc().equals("http://rww.readwriteweb.netdna-cdn.com/start/images/pagelyscreen_aug10.jpg"));
}
public void testVentureBeat() {
String url = "http://social.venturebeat.com/2010/08/18/facebook-reveals-the-details-behind-places/";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Facebook just confirmed the rumors"));
assertTrue(article.getTopImage().getImageSrc().equals("http://cdn.venturebeat.com/wp-content/uploads/2010/08/mark-zuckerberg-facebook-places.jpg"));
}
public void testTimeMagazine() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("This month, the federal government released"));
assertTrue(article.getTopImage().getImageSrc().equals("http://img.timeinc.net/time/daily/2010/1008/bp_oil_spill_0817.jpg"));
}
public void testCnet() {
String url = "http://news.cnet.com/8301-30686_3-20014053-266.html?tag=topStories1";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("NEW YORK--Verizon Communications is prepping a new"));
assertTrue(article.getTopImage().getImageSrc().equals("http://i.i.com.com/cnwk.1d/i/tim//2010/08/18/Verizon_iPad_and_live_TV_610x458.JPG"));
}
public void testYahooNewsEvenThoughTheyFuckedUpDeliciousWeWillTestThemAnyway() {
String url = "http://news.yahoo.com/s/ap/20110305/ap_on_re_af/af_libya";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("TRIPOLI, Libya – Moammar Gadhafi"));
assertTrue(article.getTopImage().getImageSrc().equals("http://d.yimg.com/a/p/ap/20110305/capt.20433579e6a949189ddb65a8c260183c-20433579e6a949189ddb65a8c260183c-0.jpg?x=213&y=142&xc=1&yc=1&wc=410&hc=273&q=85&sig=i4WKbNKMgqenVsxU3NCbOg--"));
}
public void testPolitico() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("If the newest Census Bureau estimates stay close to form"));
assertTrue(article.getTopImage().getImageSrc().equals("http://images.politico.com/global/news/100927_obama22_ap_328.jpg"));
}
public void testNewsweek() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("At first glance, Kadyrov might seem"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testLifeHacker() {
String url = "http://lifehacker.com/#!5659837/build-a-rocket-stove-to-heat-your-home-with-wood-scraps";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("If you find yourself with lots of leftover wood"));
assertTrue(article.getTopImage().getImageSrc().equals("http://cache.gawker.com/assets/images/lifehacker/2010/10/rocket-stove-finished.jpeg"));
}
public void testNinjaBlog() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Many users around the world Google their queries"));
}
public void testNaturalHomeBlog() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Guide trick or treaters and other friendly spirits to your front"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testSFGate() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Fewer homes in California and"));
assertTrue(article.getTopImage().getImageSrc().equals("http://imgs.sfgate.com/c/pictures/2010/10/26/ba-foreclosures2_SFCG1288130091.jpg"));
}
public void testSportsIllustrated() {
String url = "http://sportsillustrated.cnn.com/2010/football/ncaa/10/15/ohio-state-holmes.ap/index.html?xid=si_ncaaf";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("COLUMBUS, Ohio (AP) -- Ohio State has closed"));
assertTrue(article.getTopImage().getImageSrc().equals("http://i.cdn.turner.com/si/.e1d/img/4.0/global/logos/si_100x100.jpg"));
}
// todo get this one working - I hate star magazine web designers, they put 2 html files into one
// public void testStarMagazine() {
// ContentExtractor contentExtractor = new ContentExtractor();
// Article article = contentExtractor.extractContent(url);
// assertTrue(article.getCleanedArticleText().startsWith("The Real Reason Rihanna Skipped Katy's Wedding: No Cell Phone Reception!"));
// assertTrue(article.getTopImage().getImageSrc().equals("Rihanna has admitted the real reason she was a no show"));
public void testDailyBeast() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Legendary Kennedy speechwriter Ted Sorensen passed"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testBloomberg() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("The Chinese entrepreneur and the Peruvian shopkeeper"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testScientificDaily() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("The common industrial chemical bisphenol A (BPA) "));
assertTrue(article.getTopImage().getImageSrc().equals("http:
assertTrue(article.getTitle().equals("Everyday BPA Exposure Decreases Human Semen Quality"));
}
public void testSlamMagazine() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("When in doubt, rank players and add your findings"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
assertTrue(article.getTitle().equals("NBA Schoolyard Rankings"));
}
public void testTheFrisky() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Rachel Dratch had been keeping the identity of her baby daddy "));
assertTrue(article.getTopImage().getImageSrc().equals("http://cdn.thefrisky.com/images/uploads/rachel_dratch_102810_m.jpg"));
assertTrue(article.getTitle().equals("Rachel Dratch Met Her Baby Daddy At A Bar"));
}
public void testUniverseToday() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("I had the chance to interview LCROSS"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
assertTrue(article.getTitle().equals("More From Tony Colaprete on LCROSS"));
}
public void testCNBC() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("A prominent expert on Chinese works "));
assertTrue(article.getTopImage().getImageSrc().equals("http://media.cnbc.com/i/CNBC/Sections/News_And_Analysis/__Story_Inserts/graphics/__ART/chinese_vase_150.jpg"));
assertTrue(article.getTitle().equals("Chinese Art Expert 'Skeptical' of Record-Setting Vase"));
}
public void testEspnWithFlashVideo() {
String url = "http://sports.espn.go.com/nfl/news/story?id=5971053";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("PHILADELPHIA -- Michael Vick missed practice Thursday"));
assertTrue(article.getTopImage().getImageSrc().equals("http://a.espncdn.com/i/espn/espn_logos/espn_red.png"));
assertTrue(article.getTitle().equals("Michael Vick of Philadelphia Eagles misses practice, unlikely to play vs. Dallas Cowboys"));
}
public void testSportingNews() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("ALAMEDA, Calif. — The Oakland Raiders informed coach Tom Cable"));
assertTrue(article.getTopImage().getImageSrc().equals("http://dy.snimg.com/story-image/0/69/174475/14072-650-366.jpg"));
assertTrue(article.getTitle().equals("Raiders cut ties with Cable"));
}
public void testFoxSports() {
String url = "http://msn.foxsports.com/nfl/story/Tom-Cable-fired-contract-option-Oakland-Raiders-coach-010411";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("The Oakland Raiders informed coach Tom Cable"));
assertTrue(article.getTitle().equals("Oakland Raiders won't bring Tom Cable back as coach - NFL News"));
}
public void testMSNBC() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Prime Minister Brian Cowen announced Saturday"));
assertTrue(article.getTitle().equals("Irish premier resigns as party leader, stays as PM"));
assertTrue(article.getTopImage().getImageSrc().equals("http://msnbcmedia3.msn.com/j/ap/ireland government crisis--687575559_v2.grid-6x2.jpg"));
}
public void testEconomist() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("FOR beleaguered smokers, the world is an increasingly"));
assertTrue(article.getTopImage().getImageSrc().equals("http://media.economist.com/images/images-magazine/2011/01/22/st/20110122_stp004.jpg"));
}
public void testTheAtlantic() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("If James Bond could age, he'd be well into his 90s right now"));
assertTrue(article.getTopImage().getImageSrc().equals("http://assets.theatlantic.com/static/mt/assets/culture_test/James%20Bond_post.jpg"));
}
public void testGawker() {
String url = "http://gawker.com/#!5777023/charlie-sheen-is-going-to-haiti-with-sean-penn";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("With a backlash brewing against the incessant media"));
assertTrue(article.getTopImage().getImageSrc().equals("http://cache.gawkerassets.com/assets/images/7/2011/03/medium_0304_pennsheen.jpg"));
}
public void testNyTimes() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("WASHINGTON — An arms control treaty paring back American"));
assertTrue(article.getTopImage().getImageSrc().equals("http://graphics8.nytimes.com/images/2010/12/22/world/22start-span/Start-articleInline.jpg"));
}
public void testTheVacationGals() {
String url = "http://thevacationgals.com/vacation-rental-homes-are-a-family-reunion-necessity/";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Editors’ Note: We are huge proponents"));
assertTrue(article.getTopImage().getImageSrc().equals("http://thevacationgals.com/wp-content/uploads/2010/11/Gemmel-Family-Reunion-at-a-Vacation-Rental-Home1-300x225.jpg"));
}
// test the extraction of videos from a page
public void testGettingVideosFromGraphVinyl() {
String url = "http://grapevinyl.com/v/84/magnetic-morning/getting-nowhere";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getMovies().get(0).attr("src").equals("http:
}
public void testShockYa() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("New Kids On The Block singer Jonathan Knight has publicly"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testLiveStrong() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Childhood obesity increases a young person"));
assertTrue(article.getTopImage().getImageSrc().equals("http://photos.demandstudios.com/getty/article/184/46/87576279_XS.jpg"));
}
public void testLiveStrong2() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Resistance bands or tubes are named because"));
assertTrue(article.getTopImage().getImageSrc().equals("http://photos.demandstudios.com/getty/article/142/66/86504893_XS.jpg"));
}
public void testCracked() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Social networking is here to stay"));
assertTrue(article.getTopImage().getImageSrc().equals("http://i.crackedcdn.com/phpimages/article/2/1/5/45215.jpg?v=1"));
}
public void testTrailsCom() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Snorkel and view artificial reefs or chase"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testTrailsCom2() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Derived from the old Norse word"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testEhow() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Heat the oil in the"));
assertTrue(article.getTitle().equals("How to Make White Spaghetti"));
}
public void testGolfLink() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Las Vegas, while noted for its glitz"));
assertTrue(article.getTopImage().getImageSrc().equals("http:
}
public void testAnswerBag() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("You're reading True or false"));
}
public void testAnswerBag2() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("You're reading Can chamomille"));
}
public void testTimeMagazine2() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("The traditional Passover song"));
assertTrue(article.getTopImage().getImageSrc().equals("http://img.timeinc.net/time/photoessays/2011/top10_passover/scallions.jpg"));
}
public void testWSJ2() {
String url = "http://online.wsj.com/article/SB10001424052748704004004576270433180029082.html?mod=WSJ_hp_LEFTTopStories";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("NEW YORK—U.S. stocks were on track"));
assertTrue(article.getTopImage().getImageSrc().equals("http://m.wsj.net/video/20110418/041811marketshub2/041811marketshub2_512x288.jpg"));
}
public void testBuzznet() {
String url = "http://wevegotyoucovered.buzznet.com/user/journal/8048821/buzznet-talks-bamboozle-festival-founder/";
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Bamboozle approaches! The three day music megafest"));
assertTrue(article.getTopImage().getImageSrc().equals("http://cdn.buzznet.com/assets/imgx/1/4/0/6/1/1/9/1/orig-14061191.jpg"));
}
public void testTheSuperFicial() {
String url = "http:
ContentExtractor contentExtractor = new ContentExtractor();
Article article = contentExtractor.extractContent(url);
assertTrue(article.getCleanedArticleText().startsWith("Christ, did they all get implants?"));
assertTrue(article.getTopImage().getImageSrc().equals("http://cdn03.cdn.thesuperficial.com/wp-content/uploads/2011/04/0418-teen-mom-leah-messer-divorce-14-480x720.jpg"));
}
} |
package turtle;
import turtle.entity.Game;
import turtle.gui.WindowManager;
public class TurtleGame
{
public static void main(String[] args)
{
Game game = new Game();
Kernel kernel = new Kernel(game);
WindowManager manager = new WindowManager(kernel);
manager.link(game);
}
} |
package dk.itu.kelvin.model;
// JUnit annotations
import org.junit.Test;
import static org.junit.Assert.assertTrue;
// JUnit assertions
/**
* {@link Relation} test suite.
*/
public final class RelationTest {
/**
* Test max. and min. coordinates of the relation.
*/
@Test
public void testCoordinates() {
// Test creation of relation with a number of members.
Relation r1 = new Relation();
Node n1 = new Node(3, 3);
Node n2 = new Node(4, 4);
Node n3 = new Node(5, 5);
r1.add(n1);
r1.add(n2);
r1.add(n3);
// Test largest coordinates of the relation.
assertTrue(3 == r1.minX());
assertTrue(3 == r1.minY());
// Test smallest coordinates of the relation.
assertTrue(5 == r1.maxX());
assertTrue(5 == r1.maxY());
}
/**
* A relation should be able to consist of one or more member elements.
*/
@Test
public void addElement() {
Relation r1 = new Relation();
// test add element = null
assertTrue(0 == r1.members().size());
Node n1 = null;
r1.add(n1);
assertTrue(0 == r1.members().size());
// test add !empty way
Way w1 = new Way();
Node n2 = new Node(3, 3);
w1.add(n2);
r1.add(w1);
// test add empty way
Way w2 = new Way();
r1.add(w2);
}
} |
package ui;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ListCell;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import model.Model;
import model.TurboCollaborator;
import model.TurboIssue;
public class CustomListCell extends ListCell<TurboIssue> {
private static final String STYLE_PARENT_NAME = "-fx-font-size: 11px;";
private static final String STYLE_ISSUE_NAME = "-fx-font-size: 24px;";
private final Stage mainStage;
private final Model model;
public CustomListCell(Stage mainStage, Model logic, IssuePanel parent) {
super();
this.mainStage = mainStage;
this.model = logic;
}
@Override
public void updateItem(TurboIssue issue, boolean empty) {
super.updateItem(issue, empty);
if (issue == null)
return;
Text issueName = new Text("#" + issue.getId() + " " + issue.getTitle());
issueName.setStyle(STYLE_ISSUE_NAME);
issue.titleProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(
ObservableValue<? extends String> stringProperty,
String oldValue, String newValue) {
issueName.setText("#" + issue.getId() + " " + newValue);
}
});
Text parentName = new Text("parent");
parentName.setStyle(STYLE_PARENT_NAME);
LabelDisplayBox labels = new LabelDisplayBox(issue.getLabels());
HBox assignee = new HBox();
assignee.setSpacing(3);
Text assignedToLabel = new Text("Assigned to:");
TurboCollaborator collaborator = issue.getAssignee();
Text assigneeName = new Text(collaborator == null ? "none"
: collaborator.getGithubName());
assignee.getChildren().addAll(assignedToLabel, assigneeName);
VBox everything = new VBox();
everything.setSpacing(2);
everything.getChildren()
.addAll(issueName, parentName, labels, assignee);
// everything.getChildren().stream().forEach((node) ->
// node.setStyle(Demo.STYLE_BORDERS));
setGraphic(everything);
registerEvents(issue);
}
private void registerEvents(TurboIssue issue) {
setOnMouseClicked((MouseEvent mouseEvent) -> {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
onDoubleClick(issue);
}
}
});
}
private void onDoubleClick(TurboIssue issue) {
TurboIssue copy = new TurboIssue(issue);
(new IssueDialog(mainStage, model, issue)).show().thenApply(
response -> {
if (response.equals("ok")) {
model.updateIssue(copy, issue);
}
return true;
});
}
} |
package mho.wheels.ordering;
import mho.wheels.io.Readers;
import mho.wheels.ordering.comparators.StringBasedComparator;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.util.Comparator;
import java.util.List;
import static mho.wheels.ordering.Ordering.*;
import static mho.wheels.testing.Testing.*;
import static org.junit.Assert.fail;
public class OrderingTest {
private static final @NotNull Comparator<Integer> ODDS_BEFORE_EVENS = (i, j) -> {
boolean iEven = (i & 1) == 0;
boolean jEven = (j & 1) == 0;
if (iEven && !jEven) return 1;
if (!iEven && jEven) return -1;
return Integer.compare(i, j);
};
private static final @NotNull Comparator<Character> VOWELS_BEFORE_CONSONANTS =
new StringBasedComparator("aeiouybcdfghjklmnpqrstvwxz");
private static void fromInt_helper(int input, @NotNull String output) {
aeq(fromInt(input), output);
}
@Test
public void testFromInt() {
fromInt_helper(0, "=");
fromInt_helper(1, ">");
fromInt_helper(2, ">");
fromInt_helper(-1, "<");
fromInt_helper(-2, "<");
}
private static void toInt_helper(@NotNull String input, int output) {
aeq(Ordering.readStrict(input).get().toInt(), output);
}
@Test
public void testToInt() {
toInt_helper("=", 0);
toInt_helper(">", 1);
toInt_helper("<", -1);
}
private static void invert_helper(@NotNull String input, @NotNull String output) {
aeq(Ordering.readStrict(input).get().invert(), output);
}
@Test
public void testInvert() {
invert_helper("=", "=");
invert_helper(">", "<");
invert_helper("<", ">");
}
private static void compare_T_T_helper(int i, int j, @NotNull String output) {
aeq(compare(i, j), output);
}
@Test
public void testCompare_T_T() {
compare_T_T_helper(0, 0, "=");
compare_T_T_helper(1, 2, "<");
compare_T_T_helper(4, 3, ">");
}
private static void compare_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
@NotNull String output
) {
aeq(compare(comparator, i, j), output);
}
@Test
public void testCompare_Comparator_T_T() {
compare_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, "=");
compare_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, "<");
compare_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, ">");
}
private static void eq_T_T_helper(int i, int j, boolean output) {
aeq(eq(i, j), output);
}
@Test
public void testEq_T_T() {
eq_T_T_helper(0, 0, true);
eq_T_T_helper(1, 2, false);
eq_T_T_helper(4, 3, false);
}
private static void ne_T_T_helper(int i, int j, boolean output) {
aeq(ne(i, j), output);
}
@Test
public void testNe_T_T() {
ne_T_T_helper(0, 0, false);
ne_T_T_helper(1, 2, true);
ne_T_T_helper(4, 3, true);
}
private static void lt_T_T_helper(int i, int j, boolean output) {
aeq(lt(i, j), output);
}
@Test
public void testLt_T_T() {
lt_T_T_helper(0, 0, false);
lt_T_T_helper(1, 2, true);
lt_T_T_helper(4, 3, false);
}
private static void gt_T_T_helper(int i, int j, boolean output) {
aeq(gt(i, j), output);
}
@Test
public void testGt_T_T() {
gt_T_T_helper(0, 0, false);
gt_T_T_helper(1, 2, false);
gt_T_T_helper(4, 3, true);
}
private static void le_T_T_helper(int i, int j, boolean output) {
aeq(le(i, j), output);
}
@Test
public void testLe_T_T() {
le_T_T_helper(0, 0, true);
le_T_T_helper(1, 2, true);
le_T_T_helper(4, 3, false);
}
private static void ge_T_T_helper(int i, int j, boolean output) {
aeq(ge(i, j), output);
}
@Test
public void testGe_T_T() {
ge_T_T_helper(0, 0, true);
ge_T_T_helper(1, 2, false);
ge_T_T_helper(4, 3, true);
}
private static void eq_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
boolean output
) {
aeq(eq(comparator, i, j), output);
}
@Test
public void testEq_Comparator_T_T() {
eq_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, true);
eq_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, false);
eq_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, false);
}
private static void ne_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
boolean output
) {
aeq(ne(comparator, i, j), output);
}
@Test
public void testNe_Comparator_T_T() {
ne_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, false);
ne_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, true);
ne_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, true);
}
private static void lt_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
boolean output
) {
aeq(lt(comparator, i, j), output);
}
@Test
public void testLt_Comparator_T_T() {
lt_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, false);
lt_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, true);
lt_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, false);
}
private static void gt_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
boolean output
) {
aeq(gt(comparator, i, j), output);
}
@Test
public void testGt_Comparator_T_T() {
gt_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, false);
gt_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, false);
gt_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, true);
}
private static void le_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
boolean output
) {
aeq(le(comparator, i, j), output);
}
@Test
public void testLe_Comparator_T_T() {
le_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, true);
le_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, true);
le_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, false);
}
private static void ge_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
boolean output
) {
aeq(ge(comparator, i, j), output);
}
@Test
public void testGe_Comparator_T_T() {
ge_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, true);
ge_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, false);
ge_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, true);
}
private static void min_T_T_helper(int i, int j, int output) {
aeq(min(i, j), output);
}
@Test
public void testMin_T_T() {
min_T_T_helper(0, 0, 0);
min_T_T_helper(1, 2, 1);
min_T_T_helper(4, 3, 3);
}
private static void max_T_T_helper(int i, int j, int output) {
aeq(max(i, j), output);
}
@Test
public void testMax_T_T() {
max_T_T_helper(0, 0, 0);
max_T_T_helper(1, 2, 2);
max_T_T_helper(4, 3, 4);
}
private static void minMax_T_T_helper(int i, int j, @NotNull String output) {
aeq(minMax(i, j), output);
}
@Test
public void testMinMax_T_T() {
minMax_T_T_helper(0, 0, "(0, 0)");
minMax_T_T_helper(1, 2, "(1, 2)");
minMax_T_T_helper(4, 3, "(3, 4)");
}
private static void min_Comparator_T_T_helper(@NotNull Comparator<Integer> comparator, int i, int j, int output) {
aeq(min(comparator, i, j), output);
}
@Test
public void testMin_Comparator_T_T() {
min_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, 0);
min_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, 5);
min_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, 11);
}
private static void max_Comparator_T_T_helper(@NotNull Comparator<Integer> comparator, int i, int j, int output) {
aeq(max(comparator, i, j), output);
}
@Test
public void testMax_Comparator_T_T() {
max_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, 0);
max_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, 2);
max_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, 4);
}
private static void minMax_Comparator_T_T_helper(
@NotNull Comparator<Integer> comparator,
int i,
int j,
@NotNull String output
) {
aeq(minMax(comparator, i, j), output);
}
@Test
public void testMinMax_Comparator_T_T() {
minMax_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 0, 0, "(0, 0)");
minMax_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 5, 2, "(5, 2)");
minMax_Comparator_T_T_helper(ODDS_BEFORE_EVENS, 4, 11, "(11, 4)");
}
private static void minimum_Iterable_T_helper(@NotNull String xs, int output) {
aeq(minimum(readIntegerList(xs)), output);
}
private static void minimum_Iterable_T_fail_helper(@NotNull String xs) {
try {
minimum(readIntegerListWithNulls(xs));
fail();
} catch (IllegalArgumentException | NullPointerException | IllegalStateException ignored) {}
}
@Test
public void testMinimum_Iterable_T() {
minimum_Iterable_T_helper("[1]", 1);
minimum_Iterable_T_helper("[5, 2, 11, 4]", 2);
minimum_Iterable_T_helper("[5, 1, 12, 4]", 1);
minimum_Iterable_T_fail_helper("[]");
minimum_Iterable_T_fail_helper("[null]");
minimum_Iterable_T_fail_helper("[5, 2, 11, null]");
}
private static void maximum_Iterable_T_helper(@NotNull String xs, int output) {
aeq(maximum(readIntegerList(xs)), output);
}
private static void maximum_Iterable_T_fail_helper(@NotNull String xs) {
try {
maximum(readIntegerListWithNulls(xs));
fail();
} catch (IllegalArgumentException | NullPointerException | IllegalStateException ignored) {}
}
@Test
public void testMaximum_Iterable_T() {
maximum_Iterable_T_helper("[1]", 1);
maximum_Iterable_T_helper("[5, 2, 11, 4]", 11);
maximum_Iterable_T_helper("[5, 1, 12, 4]", 12);
maximum_Iterable_T_fail_helper("[]");
maximum_Iterable_T_fail_helper("[null]");
maximum_Iterable_T_fail_helper("[5, 2, 11, null]");
}
private static void minimumMaximum_Iterable_T_helper(@NotNull String xs, @NotNull String output) {
aeq(minimumMaximum(readIntegerList(xs)), output);
}
private static void minimumMaximum_Iterable_T_fail_helper(@NotNull String xs) {
try {
minimumMaximum(readIntegerListWithNulls(xs));
fail();
} catch (IllegalArgumentException | NullPointerException | IllegalStateException ignored) {}
}
@Test
public void testMinimumMaximum_Iterable_T() {
minimumMaximum_Iterable_T_helper("[1]", "(1, 1)");
minimumMaximum_Iterable_T_helper("[5, 2, 11, 4]", "(2, 11)");
minimumMaximum_Iterable_T_helper("[5, 1, 12, 4]", "(1, 12)");
minimumMaximum_Iterable_T_fail_helper("[]");
minimumMaximum_Iterable_T_fail_helper("[null]");
minimumMaximum_Iterable_T_fail_helper("[5, 2, 11, null]");
}
private static void minimum_Comparator_Iterable_T_helper(
@NotNull Comparator<Integer> comparator,
@NotNull String xs,
int output
) {
aeq(minimum(comparator, readIntegerList(xs)), output);
}
private static void minimum_Comparator_Iterable_T_fail_helper(
@NotNull Comparator<Integer> comparator,
@NotNull String xs
) {
try {
minimum(comparator, readIntegerListWithNulls(xs));
fail();
} catch (IllegalArgumentException | NullPointerException | IllegalStateException ignored) {}
}
@Test
public void testMinimum_Comparator_Iterable_T() {
minimum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[1]", 1);
minimum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[5, 2, 11, 4]", 5);
minimum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[5, 1, 12, 4]", 1);
minimum_Comparator_Iterable_T_fail_helper(ODDS_BEFORE_EVENS, "[]");
minimum_Comparator_Iterable_T_fail_helper(ODDS_BEFORE_EVENS, "[5, 2, 11, null]");
}
private static void maximum_Comparator_Iterable_T_helper(
@NotNull Comparator<Integer> comparator,
@NotNull String xs,
int output
) {
aeq(maximum(comparator, readIntegerList(xs)), output);
}
private static void maximum_Comparator_Iterable_T_fail_helper(
@NotNull Comparator<Integer> comparator,
@NotNull String xs
) {
try {
maximum(comparator, readIntegerListWithNulls(xs));
fail();
} catch (IllegalArgumentException | NullPointerException | IllegalStateException ignored) {}
}
@Test
public void testMaximum_Comparator_Iterable_T() {
maximum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[1]", 1);
maximum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[5, 2, 11, 4]", 4);
maximum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[5, 1, 12, 4]", 12);
maximum_Comparator_Iterable_T_fail_helper(ODDS_BEFORE_EVENS, "[]");
maximum_Comparator_Iterable_T_fail_helper(ODDS_BEFORE_EVENS, "[5, 2, 11, null]");
}
private static void minimumMaximum_Comparator_Iterable_T_helper(
@NotNull Comparator<Integer> comparator,
@NotNull String xs,
@NotNull String output
) {
aeq(minimumMaximum(comparator, readIntegerList(xs)), output);
}
private static void minimumMaximum_Comparator_Iterable_T_fail_helper(
@NotNull Comparator<Integer> comparator,
@NotNull String xs
) {
try {
minimumMaximum(comparator, readIntegerListWithNulls(xs));
fail();
} catch (IllegalArgumentException | NullPointerException | IllegalStateException ignored) {}
}
@Test
public void testMinimumMaximum_Comparator_Iterable_T() {
minimumMaximum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[1]", "(1, 1)");
minimumMaximum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[5, 2, 11, 4]", "(5, 4)");
minimumMaximum_Comparator_Iterable_T_helper(ODDS_BEFORE_EVENS, "[5, 1, 12, 4]", "(1, 12)");
minimumMaximum_Comparator_Iterable_T_fail_helper(ODDS_BEFORE_EVENS, "[]");
minimumMaximum_Comparator_Iterable_T_fail_helper(ODDS_BEFORE_EVENS, "[5, 2, 11, null]");
}
private static void minimum_String_helper(@NotNull String input, char output) {
aeq(minimum(input), output);
}
private static void minimum_String_fail_helper(@NotNull String input) {
try {
minimum(input);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testMinimum_String() {
minimum_String_helper("hello", 'e');
minimum_String_helper("CAT", 'A');
minimum_String_helper("∞", '∞');
minimum_String_fail_helper("");
}
private static void maximum_String_helper(@NotNull String input, char output) {
aeq(maximum(input), output);
}
private static void maximum_String_fail_helper(@NotNull String input) {
try {
maximum(input);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testMaximum_String() {
maximum_String_helper("hello", 'o');
maximum_String_helper("CAT", 'T');
maximum_String_helper("∞", '∞');
maximum_String_fail_helper("");
}
private static void minimumMaximum_String_helper(@NotNull String input, @NotNull String output) {
aeq(minimumMaximum(input), output);
}
private static void minimumMaximum_String_fail_helper(@NotNull String input) {
try {
minimumMaximum(input);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testMinimumMaximum_String() {
minimumMaximum_String_helper("hello", "(e, o)");
minimumMaximum_String_helper("CAT", "(A, T)");
minimumMaximum_String_helper("∞", "(∞, ∞)");
minimumMaximum_String_fail_helper("");
}
private static void minimum_Comparator_String_helper(
@NotNull Comparator<Character> comparator,
@NotNull String input,
char output
) {
aeq(minimum(comparator, input), output);
}
private static void minimum_Comparator_String_fail_helper(
@NotNull Comparator<Character> comparator,
@NotNull String input
) {
try {
minimum(comparator, input);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testMinimum_Comparator_String() {
minimum_Comparator_String_helper(VOWELS_BEFORE_CONSONANTS, "hello", 'e');
minimum_Comparator_String_helper(VOWELS_BEFORE_CONSONANTS, "bug", 'u');
minimum_Comparator_String_fail_helper(VOWELS_BEFORE_CONSONANTS, "");
minimum_Comparator_String_fail_helper(VOWELS_BEFORE_CONSONANTS, "∞∞");
}
private static void maximum_Comparator_String_helper(
@NotNull Comparator<Character> comparator,
@NotNull String input,
char output
) {
aeq(maximum(comparator, input), output);
}
private static void maximum_Comparator_String_fail_helper(
@NotNull Comparator<Character> comparator,
@NotNull String input
) {
try {
maximum(comparator, input);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testMaximum_Comparator_String() {
maximum_Comparator_String_helper(VOWELS_BEFORE_CONSONANTS, "hello", 'l');
maximum_Comparator_String_helper(VOWELS_BEFORE_CONSONANTS, "bug", 'g');
maximum_Comparator_String_fail_helper(VOWELS_BEFORE_CONSONANTS, "");
maximum_Comparator_String_fail_helper(VOWELS_BEFORE_CONSONANTS, "∞∞");
}
private static void minimumMaximum_Comparator_String_helper(
@NotNull Comparator<Character> comparator,
@NotNull String input,
@NotNull String output
) {
aeq(minimumMaximum(comparator, input), output);
}
private static void minimumMaximum_Comparator_String_fail_helper(
@NotNull Comparator<Character> comparator,
@NotNull String input
) {
try {
minimumMaximum(comparator, input);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testMinimumMaximum_Comparator_String() {
minimumMaximum_Comparator_String_helper(VOWELS_BEFORE_CONSONANTS, "hello", "(e, l)");
minimumMaximum_Comparator_String_helper(VOWELS_BEFORE_CONSONANTS, "bug", "(u, g)");
minimumMaximum_Comparator_String_fail_helper(VOWELS_BEFORE_CONSONANTS, "");
minimumMaximum_Comparator_String_fail_helper(VOWELS_BEFORE_CONSONANTS, "∞∞");
}
private static void readStrict_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input), output);
}
@Test
public void testReadStrict() {
readStrict_helper("<", "Optional[<]");
readStrict_helper("=", "Optional[=]");
readStrict_helper(">", "Optional[>]");
readStrict_helper(" <", "Optional.empty");
readStrict_helper("eq", "Optional.empty");
readStrict_helper("gt ", "Optional.empty");
readStrict_helper("GT ", "Optional.empty");
readStrict_helper("", "Optional.empty");
readStrict_helper("dsfs<fgd", "Optional.empty");
}
private static @NotNull List<Integer> readIntegerList(@NotNull String s) {
return Readers.readListStrict(Readers::readIntegerStrict).apply(s).get();
}
private static @NotNull List<Integer> readIntegerListWithNulls(@NotNull String s) {
return Readers.readListWithNullsStrict(Readers::readIntegerStrict).apply(s).get();
}
} |
package org.ak80.akkabase;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
import akka.testkit.TestActorRef;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.ak80.akkabase.test.Builder.aKey;
import static org.ak80.akkabase.test.Builder.anUniqueInt;
import static org.ak80.akkabase.test.LogAssert.assertLogInfo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class AkkabaseDbTest {
static ActorSystem system;
@BeforeClass
public static void setup() {
system = ActorSystem.create();
}
@AfterClass
public static void teardown() {
JavaTestKit.shutdownActorSystem(system);
system = null;
}
@Test
public void receive_SetMessage_then_place_key_value_in_map() {
// Given
TestActorRef<AkkabaseDb> actorRef = TestActorRef.create(system, Props.create(AkkabaseDb.class));
String key = aKey();
Integer value = anUniqueInt();
// When
actorRef.tell(new SetMessage(key, value), ActorRef.noSender());
// Then
AkkabaseDb akkabaseDb = actorRef.underlyingActor();
assertThat(akkabaseDb.getMap().get(key), is(value));
}
@Test
public void receive_SetMessage_with_same_key_again_then_replace_key_value_in_map() {
// Given
TestActorRef<AkkabaseDb> actorRef = TestActorRef.create(system, Props.create(AkkabaseDb.class));
String key = aKey();
Integer value0 = anUniqueInt();
Integer value1 = anUniqueInt();
actorRef.tell(new SetMessage(key, value0), ActorRef.noSender());
// When
actorRef.tell(new SetMessage(key, value1), ActorRef.noSender());
// Then
AkkabaseDb akkabaseDb = actorRef.underlyingActor();
assertThat(akkabaseDb.getMap().get(key), is(value1));
}
@Test
public void receive_SetMessage_with_other_key_then_have_key_value_in_map() {
// Given
TestActorRef<AkkabaseDb> actorRef = TestActorRef.create(system, Props.create(AkkabaseDb.class));
String key0 = aKey();
String key1 = aKey();
Integer value0 = anUniqueInt();
Integer value1 = anUniqueInt();
actorRef.tell(new SetMessage(key0, value0), ActorRef.noSender());
// When
actorRef.tell(new SetMessage(key1, value1), ActorRef.noSender());
// Then
AkkabaseDb akkabaseDb = actorRef.underlyingActor();
assertThat(akkabaseDb.getMap().get(key0), is(value0));
assertThat(akkabaseDb.getMap().get(key1), is(value1));
}
@Test
public void receive_SetMessage_then_log() {
// Given
SetMessage setMessage = new SetMessage(aKey(), anUniqueInt());
ActorRef actorRef = system.actorOf(Props.create(AkkabaseDb.class));
// When
Runnable when = () -> actorRef.tell(setMessage, ActorRef.noSender());
// Then
assertLogInfo(when, "received set request: " + setMessage, actorRef, system);
}
@Test
public void receive_unknown_message_then_log() {
// Given
ActorRef actorRef = system.actorOf(Props.create(AkkabaseDb.class));
// When
Runnable when = () -> actorRef.tell(aKey(), ActorRef.noSender());
// Then
assertLogInfo(when, "received unknown message ", actorRef, system);
}
} |
package org.cactoos.iterable;
import org.cactoos.list.ListOf;
import org.hamcrest.collection.IsEmptyIterable;
import org.hamcrest.core.IsEqual;
import org.junit.Test;
import org.llorllale.cactoos.matchers.Assertion;
/**
* Test Case for {@link Skipped}.
*
* @since 0.34
* @checkstyle JavadocMethodCheck (500 lines)
*/
public final class SkippedTest {
@Test
public void skipIterable() {
final String one = "one";
final String two = "two";
final String three = "three";
final String four = "four";
new Assertion<>(
"Must skip elements in iterable",
new Skipped<>(
2,
new IterableOf<>(one, two, three, four)
),
new IsEqual<>(
new IterableOf<>(
three,
four
)
)
).affirm();
}
@Test
public void skipArray() {
final String five = "five";
final String six = "six";
final String seven = "seven";
final String eight = "eight";
new Assertion<>(
"Must skip elements in array",
new Skipped<>(
2,
five, six, seven, eight
),
new IsEqual<>(
new IterableOf<>(
seven,
eight
)
)
).affirm();
}
@Test
public void skipCollection() {
final String nine = "nine";
final String eleven = "eleven";
final String twelve = "twelve";
final String hundred = "hundred";
new Assertion<>(
"Must skip elements in collection",
new Skipped<>(
2,
new ListOf<>(nine, eleven, twelve, hundred)
),
new IsEqual<>(
new IterableOf<>(twelve, hundred)
)
).affirm();
}
@Test
public void skippedAllElements() {
new Assertion<>(
"Must skip all elements",
new Skipped<>(
2,
"Frodo", "Gandalf"
),
new IsEmptyIterable<>()
).affirm();
}
@Test
public void skippedMoreThanExists() {
new Assertion<>(
"Can't skip more than exists",
new Skipped<>(
Integer.MAX_VALUE,
"Sauron", "Morgoth"
),
new IsEmptyIterable<>()
).affirm();
}
@Test
public void skippedNegativeSize() {
final String varda = "varda";
final String yavanna = "yavanna";
final String nessa = "nessa";
final String vaire = "vaire";
new Assertion<>(
"Must process negative skipped size",
new Skipped<>(
-1,
varda, yavanna, nessa, vaire
),
new IsEqual<>(
new IterableOf<>(varda, yavanna, nessa, vaire)
)
).affirm();
}
} |
package org.htmlcleaner;
import junit.framework.TestCase;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import java.io.*;
/**
* Tests parsing and tag balancing.
*/
public class TagBalancingTest extends TestCase {
protected void setUp() throws Exception {
}
public void testBalancing() throws XPatherException, IOException {
assertHtml(
"<u>aa<i>a<b>at</u> fi</i>rst</b> text",
"<html><head /><body><u>aa<i>a<b>at</b></i></u><i><b>fi</b></i><b>rst</b>text</body></html>"
);
assertHtml(
"<u>a<big>a<i>a<b>at<sup></u> fi</big>rst</b> text",
"<html><head /><body><u>a<big>a<i>a<b>at<sup /></b></i></big></u><big><i><b><sup>fi</sup>" +
"</b></i></big><i><b><sup>rst</sup></b><sup>text</sup></i></body></html>"
);
assertHtml(new File("src/test/resources/test3.html"), "/head/noscript/meta/@http-equiv", "Refresh"); |
package tap.core;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import tap.*;
import tap.core.MapOnlyTest.Record1;
import tap.formats.tapproto.Testmsg;
public class GroupingAndSortingTests {
/*
@Test
public void Test1() {
String[] args = {"GroupingAndSortingTest1", "-i", "share/test_data2.avro", "-o", "/tmp/out", "-f"};
CommandOptions o = new CommandOptions(args);
Tap tap = new Tap(o).named(o.program);
Phase phase1 = tap.createPhase().of(Record.class).reads(o.input).sortBy("group, extra, subsort");
int rc = tap.make();
Assert.assertEquals(0, rc);
File f = new File(o.output+"/part-00000.avro");
System.out.println(f.length());
Assert.assertTrue(f.exists());
//should compare against pre-defined output.
}
@Test
public void Test2() {
String[] args = {"GroupingAndSortingTest2", "-i", "share/test_data2.avro", "-o", "/tmp/out", "-f"};
CommandOptions o = new CommandOptions(args);
Tap tap = new Tap(o).named(o.program);
Phase phase1 = tap.createPhase().of(Record.class).reads(o.input).groupBy("group").sortBy("extra, subsort");
int rc = tap.make();
Assert.assertEquals(0, rc);
File f = new File(o.output+"/part-00000.avro");
System.out.println(f.length());
Assert.assertTrue(f.exists());
//should compare against pre-defined output.
}
@Test
public void Test3() {
String[] args = {"GroupingAndSortingTest3", "-i", "share/test_data2.avro", "-o", "/tmp/out", "-f"};
CommandOptions o = new CommandOptions(args);
Tap tap = new Tap(o).named(o.program);
Phase phase1 = tap.createPhase().of(Record.class).reads(o.input).reduce(Reducer.class).sortBy("group, extra, subsort").groupBy("group");
int rc = tap.make();
Assert.assertEquals(0, rc);
File f = new File(o.output+"/part-00000.avro");
System.out.println(f.length());
Assert.assertTrue(f.exists());
//should compare against pre-defined output.
}
@Test
public void Test4() {
String[] args = {"GroupingAndSortingTest4", "-i", "share/test_data.tapproto", "-o", "/tmp/out", "-f"};
CommandOptions o = new CommandOptions(args);
Tap tap = new Tap(o).named(o.program);
Phase phase1 = tap.createPhase().of(Testmsg.TestRecord.class).reads(o.input).reduce(Reducer2.class).groupBy("group, extra").sortBy("subsort");
int rc = tap.make();
Assert.assertEquals(0, rc);
File f = new File(o.output+"/part-00000.tapproto");
System.out.println(f.length());
Assert.assertTrue(f.exists());
//should compare against pre-defined output.
}
*/
@Test
/*
* nb can not put enums in the key for now
*/
public void Test5() {
String[] args = {"GroupingAndSortingTest5", "-i", "share/securities_data.tapproto", "-o", "/tmp/out", "-f"};
CommandOptions o = new CommandOptions(args);
Tap tap = new Tap(o).named(o.program);
Phase phase1 = tap.createPhase().of(Testmsg.SecuritiesRecord.class).reads(o.input).reduce(Reducer3.class).sortBy("timestamp, exchange, id");
int rc = tap.make();
Assert.assertEquals(0, rc);
File f = new File(o.output+"/part-00000.tapproto");
System.out.println(f.length());
Assert.assertTrue(f.exists());
//should compare against pre-defined output.
}
public static class Record {
public String group;
public String extra;
public String subsort;
public int value;
}
public static class SummaryRecord
{
public String group;
public int total;
}
public static class Reducer extends TapReducer<Record, SummaryRecord>
{
static SummaryRecord outrec = new SummaryRecord();
public void reduce(Pipe<Record> in, Pipe<SummaryRecord> out)
{
outrec.total = 0;
for(Record rec : in)
{
outrec.group = rec.group;
outrec.total++;
}
out.put(outrec);
System.out.println(outrec.group + " " + outrec.total);
}
}
public static class Reducer2 extends TapReducer<Testmsg.TestRecord, Testmsg.TestRecord>
{
public void reduce(Pipe<Testmsg.TestRecord> in, Pipe<Testmsg.TestRecord> out)
{
for(Testmsg.TestRecord rec : in)
{
//System.out.println(rec.getGroup() + " " + rec.getExtra() + " " + rec.getSubsort());
}
}
}
public static class Reducer3 extends TapReducer<Testmsg.SecuritiesRecord, Testmsg.SecuritiesRecord>
{
public void reduce(Pipe<Testmsg.SecuritiesRecord> in, Pipe<Testmsg.SecuritiesRecord> out)
{
for(Testmsg.SecuritiesRecord rec : in)
{
//System.out.println(rec.getTimestamp() + " " + rec.getExchange() + " " + rec.getId() + " " + rec.getDesc() + " " + rec.getStrike() + " " +
//rec.getExpiry());
}
}
}
} |
package org.jdesktop.swingx;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXMonthView.SelectionMode;
import org.jdesktop.swingx.action.AbstractActionExt;
import org.jdesktop.swingx.event.DateSelectionEvent.EventType;
import org.jdesktop.swingx.test.DateSelectionReport;
import org.jdesktop.swingx.test.XTestUtils;
/**
* Test to expose known issues with JXMonthView.
*
* @author Jeanette Winzenburg
*/
public class JXMonthViewIssues extends InteractiveTestCase {
@SuppressWarnings("all")
private static final Logger LOG = Logger.getLogger(JXMonthViewIssues.class
.getName());
// Constants used internally; unit is milliseconds
@SuppressWarnings("unused")
private static final int ONE_MINUTE = 60*1000;
@SuppressWarnings("unused")
private static final int ONE_HOUR = 60*ONE_MINUTE;
@SuppressWarnings("unused")
private static final int THREE_HOURS = 3 * ONE_HOUR;
@SuppressWarnings("unused")
private static final int ONE_DAY = 24*ONE_HOUR;
public static void main(String[] args) {
// setSystemLF(true);
JXMonthViewIssues test = new JXMonthViewIssues();
try {
// test.runInteractiveTests();
test.runInteractiveTests("interactive.*First.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private Calendar calendar;
/**
* #681-swingx: first row overlaps days.
*/
public void interactiveFirstRowOfMonth() {
JXMonthView monthView = new JXMonthView();
calendar.set(2008, 1, 1);
monthView.setSelectedDate(calendar.getTime());
showInFrame(monthView, "first row");
}
/**
* Issue #618-swingx: JXMonthView displays problems with non-default
* timezones.
*
*/
public void interactiveUpdateOnTimeZone() {
JPanel panel = new JPanel();
final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs());
final JXDatePicker picker = new JXDatePicker();
final JXMonthView monthView = new JXMonthView();
monthView.setSelectedDate(picker.getDate());
monthView.setTraversable(true);
// Synchronize the picker and selector's zones.
zoneSelector.setSelectedItem(picker.getTimeZone().getID());
// Set the picker's time zone based on the selected time zone.
zoneSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String zone = (String) zoneSelector.getSelectedItem();
TimeZone tz = TimeZone.getTimeZone(zone);
picker.setTimeZone(tz);
monthView.setTimeZone(tz);
assertEquals(tz, monthView.getCalendar().getTimeZone());
}
});
panel.add(zoneSelector);
panel.add(picker);
panel.add(monthView);
JXFrame frame = showInFrame(panel, "display problems with non-default timezones");
Action assertAction = new AbstractActionExt("assert dates") {
public void actionPerformed(ActionEvent e) {
Calendar cal = monthView.getCalendar();
LOG.info("cal/firstDisplayed" +
cal.getTime() +"/" + new Date(monthView.getFirstDisplayedDate()));
}
};
addAction(frame, assertAction);
frame.pack();
}
/**
* Issue #618-swingx: JXMonthView displays problems with non-default
* timezones.
*
*/
public void interactiveUpdateOnTimeZoneJP() {
JComponent panel = Box.createVerticalBox();
final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs());
final JXMonthView monthView = new JXMonthView();
monthView.setTraversable(true);
// Synchronize the picker and selector's zones.
zoneSelector.setSelectedItem(monthView.getTimeZone().getID());
// Set the picker's time zone based on the selected time zone.
zoneSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String zone = (String) zoneSelector.getSelectedItem();
TimeZone tz = TimeZone.getTimeZone(zone);
monthView.setTimeZone(tz);
assertEquals(tz, monthView.getCalendar().getTimeZone());
}
});
panel.add(monthView);
// JPanel bar = new JPanel();
JLabel label = new JLabel("Select TimeZone:");
label.setHorizontalAlignment(JLabel.CENTER);
// panel.add(label);
panel.add(zoneSelector);
JXFrame frame = wrapInFrame(panel, "TimeZone");
frame.pack();
frame.setVisible(true);
}
/**
* Issue #618-swingx: JXMonthView displays problems with non-default
* timezones.
*
*/
public void interactiveTimeZoneClearDateState() {
JPanel panel = new JPanel();
final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs());
final JXDatePicker picker = new JXDatePicker();
final JXMonthView monthView = new JXMonthView();
monthView.setSelectedDate(picker.getDate());
monthView.setLowerBound(XTestUtils.getStartOfToday(-10));
monthView.setUpperBound(XTestUtils.getStartOfToday(10));
monthView.setUnselectableDates(XTestUtils.getStartOfToday(2));
monthView.setFlaggedDates(new long[] {XTestUtils.getStartOfToday(4).getTime()});
monthView.setTraversable(true);
// Synchronize the picker and selector's zones.
zoneSelector.setSelectedItem(picker.getTimeZone().getID());
// Set the picker's time zone based on the selected time zone.
zoneSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String zone = (String) zoneSelector.getSelectedItem();
TimeZone tz = TimeZone.getTimeZone(zone);
picker.setTimeZone(tz);
monthView.setTimeZone(tz);
assertEquals(tz, monthView.getCalendar().getTimeZone());
}
});
panel.add(zoneSelector);
panel.add(picker);
panel.add(monthView);
JXFrame frame = showInFrame(panel, "clear internal date-related state");
Action assertAction = new AbstractActionExt("assert dates") {
public void actionPerformed(ActionEvent e) {
Calendar cal = monthView.getCalendar();
LOG.info("cal/firstDisplayed" +
cal.getTime() +"/" + new Date(monthView.getFirstDisplayedDate()));
}
};
addAction(frame, assertAction);
frame.pack();
}
/**
* Issue #659-swingx: lastDisplayedDate must be synched.
*
*/
public void interactiveLastDisplayed() {
final JXMonthView month = new JXMonthView();
month.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION);
month.setTraversable(true);
Action action = new AbstractActionExt("check lastDisplayed") {
public void actionPerformed(ActionEvent e) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(month.getLastDisplayedDate());
Date viewLast = cal.getTime();
cal.setTimeInMillis(month.getUI().getLastDisplayedDate());
Date uiLast = cal.getTime();
LOG.info("last(view/ui): " + viewLast + "/" + uiLast);
}
};
JXFrame frame = wrapInFrame(month, "default - for debugging only");
addAction(frame, action);
frame.setVisible(true);
}
/**
* characterize calendar: minimal days in first week
* Different for US (1) and Europe (4)
*/
public void testCalendarMinimalDaysInFirstWeek() {
Calendar us = Calendar.getInstance(Locale.US);
assertEquals(1, us.getMinimalDaysInFirstWeek());
Calendar french = Calendar.getInstance(Locale.FRENCH);
assertEquals("french/european calendar", 4, french.getMinimalDaysInFirstWeek());
fail("Revisit: monthView should respect locale setting? (need to test)");
}
/**
* characterize calendar: first day of week
* Can be set arbitrarily. Hmmm ... when is that useful?
*/
public void testCalendarFirstDayOfWeek() {
Calendar french = Calendar.getInstance(Locale.FRENCH);
assertEquals(Calendar.MONDAY, french.getFirstDayOfWeek());
Calendar us = Calendar.getInstance(Locale.US);
assertEquals(Calendar.SUNDAY, us.getFirstDayOfWeek());
// JW: when would we want that?
us.setFirstDayOfWeek(Calendar.FRIDAY);
assertEquals(Calendar.FRIDAY, us.getFirstDayOfWeek());
fail("Revisit: why expose setting of firstDayOfWeek? Auto-set with locale");
}
/**
* BasicMonthViewUI: use adjusting api in keyboard actions.
* Here: test add selection action.
*
* TODO: this fails (unrelated to the adjusting) because the
* the selectionn changing event type is DATES_SET instead of
* the expected DATES_ADDED. What's wrong - expectation or type?
*/
public void testAdjustingSetOnAdd() {
JXMonthView view = new JXMonthView();
// otherwise the add action isn't called
view.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION);
DateSelectionReport report = new DateSelectionReport();
view.getSelectionModel().addDateSelectionListener(report);
Action select = view.getActionMap().get("adjustSelectionNextDay");
select.actionPerformed(null);
assertTrue("ui keyboard action must have started model adjusting",
view.getSelectionModel().isAdjusting());
assertEquals(2, report.getEventCount());
// assert that the adjusting is fired before the add
// only: the ui fires a set instead - bug or feature?
assertEquals(EventType.DATES_ADDED, report.getLastEvent().getEventType());
}
/**
* Returns a timezone with a rawoffset with a different offset.
*
*
* PENDING: this is acutally for european time, not really thought of
* negative/rolling +/- problem?
*
* @param timeZone the timezone to start with
* @param diffRawOffset the raw offset difference.
* @return
*/
@SuppressWarnings("unused")
private TimeZone getTimeZone(TimeZone timeZone, int diffRawOffset) {
int offset = timeZone.getRawOffset();
int newOffset = offset < 0 ? offset + diffRawOffset : offset - diffRawOffset;
String[] availableIDs = TimeZone.getAvailableIDs(newOffset);
TimeZone newTimeZone = TimeZone.getTimeZone(availableIDs[0]);
return newTimeZone;
}
@SuppressWarnings("unused")
private String[] getTimeZoneIDs() {
List<String> zoneIds = new ArrayList<String>();
for (int i = -12; i <= 12; i++) {
String sign = i < 0 ? "-" : "+";
zoneIds.add("GMT" + sign + i);
}
return zoneIds.toArray(new String[zoneIds.size()]);
}
@Override
protected void setUp() throws Exception {
calendar = Calendar.getInstance();
}
} |
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.table.TableColumnExt;
public class JXTableHeaderTest extends InteractiveTestCase {
private static final Logger LOG = Logger.getLogger(JXTableHeaderTest.class
.getName());
public void testDraggedColumnRemoved() {
JXTable table = new JXTable(10, 2);
TableColumnExt columnExt = table.getColumnExt(0);
table.getTableHeader().setDraggedColumn(columnExt);
// sanity assert
assertEquals(columnExt, table.getTableHeader().getDraggedColumn());
table.getColumnModel().removeColumn(columnExt);
assertNull("draggedColumn must be null if removed", table.getTableHeader().getDraggedColumn());
}
public void testDraggedColumnVisible() {
JXTable table = new JXTable(10, 2);
TableColumnExt columnExt = table.getColumnExt(0);
table.getTableHeader().setDraggedColumn(columnExt);
// sanity assert
assertEquals(columnExt, table.getTableHeader().getDraggedColumn());
columnExt.setVisible(false);
assertNull("dragged column must visible or null", table.getTableHeader().getDraggedColumn());
}
/**
* Issue #390-swingx: JXTableHeader: throws AIOOB on removing dragged column.
* Characterization of header#isVisible(TableColumn).
*
* PENDING JW: should column be contained in model to be evaluated as
* visible in the header context? This is a bit moot, because needed
* mainly in context with the draggedColumn which is dirty anyway.
*/
public void testColumnVisible() {
JXTableHeader header = new JXTableHeader();
assertFalse("null column must not be visible", header.isVisible(null));
assertTrue("TableColumn must be visible", header.isVisible(new TableColumn()));
TableColumnExt columnExt = new TableColumnExt();
assertEquals("TableColumnExt visible property",
columnExt.isVisible(), header.isVisible(columnExt));
columnExt.setVisible(!columnExt.isVisible());
assertEquals("TableColumnExt visible property",
columnExt.isVisible(), header.isVisible(columnExt));
}
/**
* Issue 334-swingx: BasicTableHeaderUI.getPrefSize doesn't respect
* all renderere's size requirements.
*
*/
public void testPreferredHeight() {
JXTable table = new JXTable(10, 2);
TableColumnExt columnExt = table.getColumnExt(1);
columnExt.setTitle("<html><center>Line 1<br>Line 2</center></html>");
JXTableHeader tableHeader = (JXTableHeader) table.getTableHeader();
TableCellRenderer renderer = tableHeader.getCellRenderer(1);
Component comp = renderer.getTableCellRendererComponent(table,
columnExt.getHeaderValue(), false, false, -1, 1);
Dimension prefRendererSize = comp.getPreferredSize();
assertEquals("Header pref height must respect renderer",
prefRendererSize.height, tableHeader.getPreferredSize().height);
}
/**
* test doc'ed xheader.getToolTipText(MouseEvent) behaviour.
*
*/
public void testColumnToolTip() {
JXTable table = new JXTable(10, 2);
TableColumnExt columnExt = table.getColumnExt(0);
JXTableHeader tableHeader = (JXTableHeader) table.getTableHeader();
MouseEvent event = new MouseEvent(tableHeader, 0,
0, 0, 40, 5, 0, false);
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
String rendererToolTip = "rendererToolTip";
renderer.setToolTipText(rendererToolTip);
columnExt.setHeaderRenderer(renderer);
assertEquals(rendererToolTip, tableHeader.getToolTipText(event));
String columnToolTip = "columnToolTip";
columnExt.setToolTipText(columnToolTip);
assertEquals(columnToolTip, tableHeader.getToolTipText(event));
}
/**
* #212-swingx: second last column cannot be set to invisible programatically.
*
* One reason for the "trick" of reselecting the last is that
* the header and with it the columnControl vanishes if there is
* no visible column.
*
*
*
*/
public void testHeaderVisibleWithoutColumns() {
// This test will not work in a headless configuration.
if (GraphicsEnvironment.isHeadless()) {
LOG.info("cannot run headerVisible - headless environment");
return;
}
JXTable table = new JXTable();
table.setColumnControlVisible(true);
wrapWithScrollingInFrame(table, "");
assertEquals("headerHeight must be > 0", 16, table.getTableHeader().getHeight());
assertEquals("headerWidth must be table width",
table.getWidth(), table.getTableHeader().getWidth());
}
/**
* #212-swingx: second last column cannot be set to invisible programatically.
*
* One reason for the "trick" of reselecting the last is that
* the header and with it the columnControl vanishes if there is
* no visible column.
*
*
*
*/
public void testHeaderVisibleWithColumns() {
// This test will not work in a headless configuration.
if (GraphicsEnvironment.isHeadless()) {
LOG.info("cannot run headerVisible - headless environment");
return;
}
JXTable table = new JXTable(10, 2);
table.setColumnControlVisible(true);
wrapWithScrollingInFrame(table, "");
assertEquals("headerHeight must be > 0", 16, table.getTableHeader().getHeight());
table.setModel(new DefaultTableModel());
assertEquals("headerHeight must be > 0", 16, table.getTableHeader().getHeight());
}
/**
* Issue #390-swingx: JXTableHeader: throws AIOOB on removing dragged column.
*
*/
public void interactiveDraggedColumnRemoved() {
final JXTable table = new JXTable(10, 5);
Action deleteColumn = new AbstractAction("deleteCurrentColumn") {
public void actionPerformed(ActionEvent e) {
TableColumn column = table.getTableHeader().getDraggedColumn();
if (column == null) return;
table.getColumnModel().removeColumn(column);
}
};
KeyStroke keyStroke = KeyStroke.getKeyStroke("F1");
table.getInputMap(JTable.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "f1");
table.getActionMap().put("f1", deleteColumn);
JXFrame frame = wrapWithScrollingInFrame(table, "Remove dragged column with F1");
frame.setVisible(true);
}
/**
* Visual demo that header is always visible.
*/
public void interactiveHeaderVisible() {
final JXTable table = new JXTable();
table.setColumnControlVisible(true);
JXFrame frame = wrapWithScrollingInFrame(table, "header always visible");
Action action = new AbstractAction("toggle model") {
public void actionPerformed(ActionEvent e) {
int columnCount = table.getColumnCount(true);
table.setModel(columnCount > 0 ?
new DefaultTableModel() : new DefaultTableModel(10, 2));
}
};
addAction(frame, action);
frame.setVisible(true);
}
public static void main(String args[]) {
JXTableHeaderTest test = new JXTableHeaderTest();
try {
test.runInteractiveTests();
// test.runInteractiveTests("interactive.*Siz.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
} |
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.util.Vector;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.CellEditor;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import org.jdesktop.swingx.action.AbstractActionExt;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.jdesktop.swingx.hyperlink.LinkAction;
import org.jdesktop.swingx.renderer.CellContext;
import org.jdesktop.swingx.renderer.CheckBoxProvider;
import org.jdesktop.swingx.renderer.ComponentProvider;
import org.jdesktop.swingx.renderer.DefaultTableRenderer;
import org.jdesktop.swingx.renderer.DefaultTreeRenderer;
import org.jdesktop.swingx.renderer.HyperlinkProvider;
import org.jdesktop.swingx.renderer.LabelProvider;
import org.jdesktop.swingx.renderer.StringValue;
import org.jdesktop.swingx.renderer.WrappingIconPanel;
import org.jdesktop.swingx.renderer.WrappingProvider;
import org.jdesktop.swingx.renderer.RendererVisualCheck.TextAreaProvider;
import org.jdesktop.swingx.test.ActionMapTreeTableModel;
import org.jdesktop.swingx.test.ComponentTreeTableModel;
import org.jdesktop.swingx.test.TreeTableUtils;
import org.jdesktop.swingx.treetable.AbstractMutableTreeTableNode;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
import org.jdesktop.swingx.treetable.DefaultTreeTableModel;
import org.jdesktop.swingx.treetable.FileSystemModel;
import org.jdesktop.swingx.treetable.MutableTreeTableNode;
import org.jdesktop.swingx.treetable.TreeTableModel;
import org.jdesktop.swingx.treetable.TreeTableNode;
import org.jdesktop.test.TableModelReport;
/**
* Test to exposed known issues of <code>JXTreeTable</code>. <p>
*
* Ideally, there would be at least one failing test method per open
* issue in the issue tracker. Plus additional failing test methods for
* not fully specified or not yet decided upon features/behaviour.<p>
*
* Once the issues are fixed and the corresponding methods are passing, they
* should be moved over to the XXTest.
*
* @author Jeanette Winzenburg
*/
public class JXTreeTableIssues extends InteractiveTestCase {
private static final Logger LOG = Logger.getLogger(JXTreeTableIssues.class
.getName());
public static void main(String[] args) {
setSystemLF(true);
JXTreeTableIssues test = new JXTreeTableIssues();
try {
// test.runInteractiveTests();
// test.runInteractiveTests(".*AdapterDeleteUpdate.*");
// test.runInteractiveTests(".*Text.*");
// test.runInteractiveTests(".*TreeExpand.*");
test.runInteractiveTests("interactive.*Clip.*");
// test.runInteractiveTests("interactive.*CustomColor.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
/**
* Custom renderer colors of Swingx DefaultTreeRenderer not respected.
* (same in J/X/Tree).
*
* A bit surprising - probably due to the half-hearted support (backward
* compatibility) of per-provider colors: they are set by the glueing
* renderer to the provider's default visuals. Which is useless if the
* provider is a wrapping provider - the wrappee's default visuals are unchanged.
*
* PENDING JW: think about complete removal. Client code should move over
* completely to highlighter/renderer separation anyway.
*
*
*/
public void interactiveXRendererCustomColor() {
JXTreeTable treeTable = new JXTreeTable(new FileSystemModel());
treeTable.addHighlighter(HighlighterFactory.createSimpleStriping());
DefaultTreeRenderer swingx = new DefaultTreeRenderer();
// in a treetable this has no effect: treetable.applyRenderer
// internally resets them to the same colors as tree itself
// (configured by the table's highlighters
swingx.setBackground(Color.YELLOW);
treeTable.setTreeCellRenderer(swingx);
JTree tree = new JXTree(treeTable.getTreeTableModel());
DefaultTreeRenderer other = new DefaultTreeRenderer();
other.setBackground(Color.YELLOW);
// other.setBackgroundSelectionColor(Color.RED);
tree.setCellRenderer(other);
JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "swingx renderers - highlight complete cell");
frame.setVisible(true);
}
/**
* Custom renderer colors of core DefaultTreeCellRenderer not respected.
* This is intentional: treeTable's highlighters must rule, so the
* renderer colors are used to force the treecellrenderer to use the
* correct values.
*/
public void interactiveCoreRendererCustomColor() {
JXTreeTable treeTable = new JXTreeTable(new FileSystemModel());
treeTable.addHighlighter(HighlighterFactory.createSimpleStriping());
DefaultTreeCellRenderer legacy = createBackgroundTreeRenderer();
// in a treetable this has no effect: treetable.applyRenderer
// internally resets them to the same colors as tree itself
// (configured by the table's highlighters
legacy.setBackgroundNonSelectionColor(Color.YELLOW);
legacy.setBackgroundSelectionColor(Color.RED);
treeTable.setTreeCellRenderer(legacy);
JTree tree = new JXTree(treeTable.getTreeTableModel());
DefaultTreeCellRenderer other = createBackgroundTreeRenderer();
other.setBackgroundNonSelectionColor(Color.YELLOW);
other.setBackgroundSelectionColor(Color.RED);
tree.setCellRenderer(other);
JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "legacy renderers - highlight complete cell");
frame.setVisible(true);
}
private DefaultTreeCellRenderer createBackgroundTreeRenderer() {
DefaultTreeCellRenderer legacy = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean sel, boolean expanded, boolean leaf,
int row, boolean hasFocus) {
Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
row, hasFocus);
if (sel) {
comp.setBackground(getBackgroundSelectionColor());
} else {
comp.setBackground(getBackgroundNonSelectionColor());
}
return comp;
}
};
return legacy;
}
/**
* Issue #766-swingx: drop image is blinking over hierarchical column.
*
* Not sure how to enable in 1.5 (TransferSupport is 1.6 api). But looks
* terrible in 1.6. Probably related to our mouse tricksery? Any ideas anybody?
*
*/
public void interactiveDropOnHierachicalColumnBlinks() {
JXTreeTable xTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame()));
TransferHandler tableTransfer = new TransferHandler() {
// @Override
// public boolean canImport (TransferSupport support) {
// return true;
// @Override
// public boolean importData (TransferSupport support) {
// return super.importData(support);
};
xTable.setTransferHandler(tableTransfer);
xTable.expandAll();
xTable.setVisibleColumnCount(10);
JXFrame frame = wrapWithScrollingInFrame(xTable, "TreeTable: null icons?");
JTextField textField = new JTextField("drag");
textField.setDragEnabled(true);
addStatusComponent(frame, textField);
frame.setVisible(true);
}
/**
* Issue #730-swingx: editor's stop not always called.
*
* - start edit a cell in the hierarchical column,
* - click into another cell of the hierarchical column
* - edit sometimes canceled instead of stopped
*
* seems to happen if click into text of cell, okay if outside
*
*/
public void interactiveEditingCanceledStopped() {
final JTextField field = new JTextField();
JXTreeTable xTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame()));
xTable.expandAll();
xTable.setVisibleColumnCount(10);
xTable.packColumn(0, -1);
CellEditor editor = xTable.getCellEditor(0, 0);
CellEditorListener l = new CellEditorListener() {
public void editingCanceled(ChangeEvent e) {
field.setText("canceled");
LOG.info("canceled");
}
public void editingStopped(ChangeEvent e) {
field.setText("stopped");
LOG.info("stopped");
}};
editor.addCellEditorListener(l);
JXFrame frame = wrapWithScrollingInFrame(xTable, "#730-swingx: click sometimes cancels");
frame.add(field, BorderLayout.SOUTH);
frame.setVisible(true);
}
/**
* Issue #493-swingx: incorrect table events fired.
* Issue #592-swingx: (no structureChanged table events) is a special
* case of the former.
*
* Here: add support to prevent a structureChanged even when setting
* the root. May be required if the columns are stable and the
* model lazily loaded. Quick hack would be to add a clientProperty?
*
* @throws InvocationTargetException
* @throws InterruptedException
*/
public void testTableEventOnSetRootNoStructureChange() throws InterruptedException, InvocationTargetException {
TreeTableModel model = createCustomTreeTableModelFromDefault();
final JXTreeTable table = new JXTreeTable(model);
table.setRootVisible(true);
table.expandAll();
final TableModelReport report = new TableModelReport();
table.getModel().addTableModelListener(report);
((DefaultTreeTableModel) model).setRoot(new DefaultMutableTreeTableNode("other"));
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
assertEquals("tableModel must have fired", 1, report.getEventCount());
assertTrue("event type must be dataChanged " + TableModelReport.printEvent(report.getLastEvent()),
report.isDataChanged(report.getLastEvent()));
}
});
}
/**
* Issue #576-swingx: sluggish scrolling (?).
* Here - use default model
*/
public void interactiveScrollAlternateHighlightDefaultModel() {
final JXTable table = new JXTable(0, 6);
DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root");
for (int i = 0; i < 5000; i++) {
root.insert(new DefaultMutableTreeTableNode(i), i);
}
final JXTreeTable treeTable = new JXTreeTable(new DefaultTreeTableModel(root));
treeTable.expandAll();
table.setModel(treeTable.getModel());
final Highlighter hl =
HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"),
Color.WHITE);
treeTable.setHighlighters(hl);
table.setHighlighters(hl);
final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling");
Action toggleHighlighter = new AbstractActionExt("toggle highlighter") {
public void actionPerformed(ActionEvent e) {
if (treeTable.getHighlighters().length == 0) {
treeTable.addHighlighter(hl);
table.addHighlighter(hl);
} else {
treeTable.removeHighlighter(hl);
table.removeHighlighter(hl);
}
}
};
Action scroll = new AbstractActionExt("start scroll") {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.scrollRowToVisible(i);
treeTable.scrollRowToVisible(i);
}
}
};
addAction(frame, toggleHighlighter);
addAction(frame, scroll);
frame.setVisible(true);
}
/**
* Issue #576-swingx: sluggish scrolling (?)
*
* Here: use FileSystemModel
*/
public void interactiveScrollAlternateHighlight() {
final JXTable table = new JXTable(0, 6);
final JXTreeTable treeTable = new JXTreeTable(new FileSystemModel());
final Highlighter hl =
HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"),
Color.WHITE);
treeTable.setHighlighters(hl);
table.setHighlighters(hl);
final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling");
Action expand = new AbstractActionExt("start expand") {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 5000; i++) {
treeTable.expandRow(i);
}
table.setModel(treeTable.getModel());
}
};
Action toggleHighlighter = new AbstractActionExt("toggle highlighter") {
public void actionPerformed(ActionEvent e) {
if (treeTable.getHighlighters().length == 0) {
treeTable.addHighlighter(hl);
table.addHighlighter(hl);
} else {
treeTable.removeHighlighter(hl);
table.removeHighlighter(hl);
}
}
};
Action scroll = new AbstractActionExt("start scroll") {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.scrollRowToVisible(i);
treeTable.scrollRowToVisible(i);
}
}
};
addAction(frame, expand);
addAction(frame, toggleHighlighter);
addAction(frame, scroll);
frame.setVisible(true);
}
/**
* Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency
* firing update.
*
* Test update events after updating table.
*
* from tiberiu@dev.java.net
*
* @throws InvocationTargetException
* @throws InterruptedException
*/
public void testTableEventUpdateOnTreeTableSetValueForRoot() throws InterruptedException, InvocationTargetException {
TreeTableModel model = createCustomTreeTableModelFromDefault();
final JXTreeTable table = new JXTreeTable(model);
table.setRootVisible(true);
table.expandAll();
final int row = 0;
// sanity
assertEquals("JTree", table.getValueAt(row, 0).toString());
assertTrue("root must be editable", table.getModel().isCellEditable(0, 0));
final TableModelReport report = new TableModelReport();
table.getModel().addTableModelListener(report);
// doesn't fire or isn't detectable?
// Problem was: model was not-editable.
table.setValueAt("games", row, 0);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
assertEquals("tableModel must have fired", 1, report.getEventCount());
assertEquals("the event type must be update " + TableModelReport.printEvent(report.getLastEvent())
, 1, report.getUpdateEventCount());
TableModelEvent event = report.getLastUpdateEvent();
assertEquals("the updated row ", row, event.getFirstRow());
}
});
}
/**
* Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency
* firing update on a recursive delete on a parent node.
*
* By recursive delete on a parent node it is understood that first we
* remove its children and then the parent node. After each child removed
* we are making an update over the parent. During this update the problem
* occurs: the index row for the parent is -1 and hence it is made an update
* over the row -1 (the header) and as it can be seen the preffered widths
* of column header are not respected anymore and are restored to the default
* preferences (all equal).
*
* from tiberiu@dev.java.net
*/
public void interactiveTreeTableModelAdapterDeleteUpdate() {
final DefaultTreeTableModel customTreeTableModel = (DefaultTreeTableModel)
createCustomTreeTableModelFromDefault();
final JXTreeTable table = new JXTreeTable(customTreeTableModel);
table.setRootVisible(true);
table.expandAll();
table.getColumn("A").setPreferredWidth(100);
table.getColumn("A").setMinWidth(100);
table.getColumn("A").setMaxWidth(100);
JXTree xtree = new JXTree(customTreeTableModel);
xtree.setRootVisible(true);
xtree.expandAll();
final JXFrame frame = wrapWithScrollingInFrame(table, xtree,
"JXTreeTable.TreeTableModelAdapter: Inconsistency firing update on recursive delete");
final MutableTreeTableNode deletedNode = (MutableTreeTableNode) table.getPathForRow(6).getLastPathComponent();
MutableTreeTableNode child1 = (MutableTreeTableNode) table.getPathForRow(6+1).getLastPathComponent();
MutableTreeTableNode child2 = (MutableTreeTableNode) table.getPathForRow(6+2).getLastPathComponent();
MutableTreeTableNode child3 = (MutableTreeTableNode) table.getPathForRow(6+3).getLastPathComponent();
MutableTreeTableNode child4 = (MutableTreeTableNode) table.getPathForRow(6+4).getLastPathComponent();
final MutableTreeTableNode[] children = {child1, child2, child3, child4 };
final String[] values = {"v1", "v2", "v3", "v4"};
final ActionListener l = new ActionListener() {
int count = 0;
public void actionPerformed(ActionEvent e) {
if (count > values.length) return;
if (count == values.length) {
customTreeTableModel.removeNodeFromParent(deletedNode);
count++;
} else {
// one in each run
removeChild(customTreeTableModel, deletedNode, children, values);
count++;
// all in one
// for (int i = 0; i < values.length; i++) {
// removeChild(customTreeTableModel, deletedNode, children, values);
// count++;
}
}
/**
* @param customTreeTableModel
* @param deletedNode
* @param children
* @param values
*/
private void removeChild(final DefaultTreeTableModel customTreeTableModel, final MutableTreeTableNode deletedNode, final MutableTreeTableNode[] children, final String[] values) {
customTreeTableModel.removeNodeFromParent(children[count]);
customTreeTableModel.setValueAt(values[count], deletedNode, 0);
}
};
Action changeValue = new AbstractAction("delete node sports recursively") {
Timer timer;
public void actionPerformed(ActionEvent e) {
if (timer == null) {
timer = new Timer(10, l);
timer.start();
} else {
timer.stop();
setEnabled(false);
}
}
};
addAction(frame, changeValue);
frame.setVisible(true);
}
/**
* Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency
* firing update. Use the second child of root - first is accidentally okay.
*
* from tiberiu@dev.java.net
*
* TODO DefaultMutableTreeTableNodes do not allow value changes, so this
* test will never work
*/
public void interactiveTreeTableModelAdapterUpdate() {
TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault();
final JXTreeTable table = new JXTreeTable(customTreeTableModel);
table.setRootVisible(true);
table.expandAll();
table.setLargeModel(true);
JXTree xtree = new JXTree(customTreeTableModel);
xtree.setRootVisible(true);
xtree.expandAll();
final JXFrame frame = wrapWithScrollingInFrame(table, xtree,
"JXTreeTable.TreeTableModelAdapter: Inconsistency firing update");
Action changeValue = new AbstractAction("change sports to games") {
public void actionPerformed(ActionEvent e) {
String newValue = "games";
table.getTreeTableModel().setValueAt(newValue,
table.getPathForRow(6).getLastPathComponent(), 0);
}
};
addAction(frame, changeValue);
Action changeRoot = new AbstractAction("change root") {
public void actionPerformed(ActionEvent e) {
DefaultMutableTreeTableNode newRoot = new DefaultMutableTreeTableNode("new Root");
((DefaultTreeTableModel) table.getTreeTableModel()).setRoot(newRoot);
}
};
addAction(frame, changeRoot);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency
* firing delete.
*
* from tiberiu@dev.java.net
*/
public void interactiveTreeTableModelAdapterDelete() {
final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault();
final JXTreeTable table = new JXTreeTable(customTreeTableModel);
table.setRootVisible(true);
table.expandAll();
JXTree xtree = new JXTree(customTreeTableModel);
xtree.setRootVisible(true);
xtree.expandAll();
final JXFrame frame = wrapWithScrollingInFrame(table, xtree,
"JXTreeTable.TreeTableModelAdapter: Inconsistency firing update");
Action changeValue = new AbstractAction("delete first child of sports") {
public void actionPerformed(ActionEvent e) {
MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(6 +1).getLastPathComponent();
((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild);
}
};
addAction(frame, changeValue);
frame.setVisible(true);
}
/**
* Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency
* firing delete.
*
* from tiberiu@dev.java.net
*/
public void interactiveTreeTableModelAdapterMutateSelected() {
final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault();
final JXTreeTable table = new JXTreeTable(customTreeTableModel);
table.setRootVisible(true);
table.expandAll();
JXTree xtree = new JXTree(customTreeTableModel);
xtree.setRootVisible(true);
xtree.expandAll();
final JXFrame frame = wrapWithScrollingInFrame(table, xtree,
"JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder");
Action changeValue = new AbstractAction("delete selected node") {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row < 0) return;
MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent();
((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild);
}
};
addAction(frame, changeValue);
Action changeValue1 = new AbstractAction("insert as first child of selected node") {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row < 0) return;
MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent();
MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted");
((DefaultTreeTableModel) customTreeTableModel)
.insertNodeInto(newChild, firstChild, 0);
}
};
addAction(frame, changeValue1);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency
* firing delete.
*
* from tiberiu@dev.java.net
*/
public void interactiveTreeTableModelAdapterMutateSelectedDiscontinous() {
final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault();
final JXTreeTable table = new JXTreeTable(customTreeTableModel);
table.setRootVisible(true);
table.expandAll();
JXTree xtree = new JXTree(customTreeTableModel);
xtree.setRootVisible(true);
xtree.expandAll();
final JXFrame frame = wrapWithScrollingInFrame(table, xtree,
"JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder");
Action changeValue = new AbstractAction("delete selected node + sibling") {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row < 0) return;
MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent();
MutableTreeTableNode parent = (MutableTreeTableNode) firstChild.getParent();
MutableTreeTableNode secondNextSibling = null;
int firstIndex = parent.getIndex(firstChild);
if (firstIndex + 2 < parent.getChildCount()) {
secondNextSibling = (MutableTreeTableNode) parent.getChildAt(firstIndex + 2);
}
if (secondNextSibling != null) {
((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(secondNextSibling);
}
((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild);
}
};
addAction(frame, changeValue);
Action changeValue1 = new AbstractAction("insert as first child of selected node") {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row < 0) return;
MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent();
MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted");
((DefaultTreeTableModel) customTreeTableModel)
.insertNodeInto(newChild, firstChild, 0);
}
};
addAction(frame, changeValue1);
frame.pack();
frame.setVisible(true);
}
/**
* Creates and returns a custom model from JXTree default model. The model
* is of type DefaultTreeModel, allowing for easy insert/remove.
*
* @return
*/
private TreeTableModel createCustomTreeTableModelFromDefault() {
JXTree tree = new JXTree();
DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
TreeTableModel customTreeTableModel = TreeTableUtils
.convertDefaultTreeModel(treeModel);
return customTreeTableModel;
}
/**
* A TreeTableModel inheriting from DefaultTreeModel (to ease
* insert/delete).
*/
public static class CustomTreeTableModel extends DefaultTreeTableModel {
/**
* @param root
*/
public CustomTreeTableModel(TreeTableNode root) {
super(root);
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public String getColumnName(int column) {
return "User Object";
}
@Override
public Object getValueAt(Object node, int column) {
return ((DefaultMutableTreeNode) node).getUserObject();
}
@Override
public boolean isCellEditable(Object node, int column) {
return true;
}
@Override
public void setValueAt(Object value, Object node, int column) {
((MutableTreeTableNode) node).setUserObject(value);
modelSupport.firePathChanged(new TreePath(getPathToRoot((TreeTableNode) node)));
}
}
/**
* Issue #??-swingx: hyperlink in JXTreeTable hierarchical column not
* active.
*
*/
public void interactiveTreeTableLinkRendererSimpleText() {
LinkAction simpleAction = new LinkAction<Object>(null) {
public void actionPerformed(ActionEvent e) {
LOG.info("hit: " + getTarget());
}
};
JXTreeTable tree = new JXTreeTable(new FileSystemModel());
HyperlinkProvider provider = new HyperlinkProvider(simpleAction);
tree.getColumn(2).setCellRenderer(new DefaultTableRenderer(provider));
tree.setTreeCellRenderer(new DefaultTreeRenderer( //provider));
new WrappingProvider(provider)));
// tree.setCellRenderer(new LinkRenderer(simpleAction));
tree.setHighlighters(HighlighterFactory.createSimpleStriping());
JFrame frame = wrapWithScrollingInFrame(tree, "table and simple links");
frame.setVisible(true);
}
/**
* Issue ??-swingx: hyperlink/rollover in hierarchical column.
*
*/
public void testTreeRendererInitialRollover() {
JXTreeTable tree = new JXTreeTable(new FileSystemModel());
assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled());
}
/**
* Issue ??-swingx: hyperlink/rollover in hierarchical column.
*
*/
public void testTreeRendererModifiedRollover() {
JXTreeTable tree = new JXTreeTable(new FileSystemModel());
tree.setRolloverEnabled(!tree.isRolloverEnabled());
assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled());
}
/**
* example how to use a custom component as
* renderer in tree column of TreeTable.
*
*/
public void interactiveTreeTableCustomRenderer() {
JXTreeTable tree = new JXTreeTable(new FileSystemModel());
StringValue sv = new StringValue( ){
public String getString(Object value) {
return "..." + TO_STRING.getString(value);
}
};
ComponentProvider provider = new CheckBoxProvider(sv);
// /**
// * custom tooltip: show row. Note: the context is that
// * of the rendering tree. No way to get at table state?
// */
// @Override
// protected void configureState(CellContext context) {
// super.configureState(context);
// rendererComponent.setToolTipText("Row: " + context.getRow());
tree.setTreeCellRenderer(new DefaultTreeRenderer(provider));
tree.setHighlighters(HighlighterFactory.createSimpleStriping());
JFrame frame = wrapWithScrollingInFrame(tree, "treetable and custom renderer");
frame.setVisible(true);
}
/**
* Quick example to use a TextArea in the hierarchical column
* of a treeTable. Not really working .. the wrap is not reliable?.
*
*/
public void interactiveTextAreaTreeTable() {
TreeTableModel model = createTreeTableModelWithLongNode();
JXTreeTable treeTable = new JXTreeTable(model);
treeTable.setVisibleRowCount(5);
treeTable.setRowHeight(50);
treeTable.getColumnExt(0).setPreferredWidth(200);
TreeCellRenderer renderer = new DefaultTreeRenderer(
new WrappingProvider(new TextAreaProvider()));
treeTable.setTreeCellRenderer(renderer);
showWithScrollingInFrame(treeTable, "TreeTable with text wrapping");
}
/**
* @return
*/
private TreeTableModel createTreeTableModelWithLongNode() {
MutableTreeTableNode root = createLongNode("some really, maybe really really long text - "
+ "wrappit .... where needed ");
root.insert(createLongNode("another really, maybe really really long text - "
+ "with nothing but junk. wrappit .... where needed"), 0);
root.insert(createLongNode("another really, maybe really really long text - "
+ "with nothing but junk. wrappit .... where needed"), 0);
MutableTreeTableNode node = createLongNode("some really, maybe really really long text - "
+ "wrappit .... where needed ");
node.insert(createLongNode("another really, maybe really really long text - "
+ "with nothing but junk. wrappit .... where needed"), 0);
root.insert(node, 0);
root.insert(createLongNode("another really, maybe really really long text - "
+ "with nothing but junk. wrappit .... where needed"), 0);
Vector<String> ids = new Vector<String>();
ids.add("long text");
ids.add("dummy");
return new DefaultTreeTableModel(root, ids);
}
/**
* @param string
* @return
*/
private MutableTreeTableNode createLongNode(final String string) {
AbstractMutableTreeTableNode node = new AbstractMutableTreeTableNode() {
Object rnd = Math.random();
public int getColumnCount() {
return 2;
}
public Object getValueAt(int column) {
if (column == 0) {
return string;
}
return rnd;
}
};
node.setUserObject(string);
return node;
}
/**
* Experiments to try and understand clipping issues: occasionally, the text
* in the tree column is clipped even if there is enough space available.
*
* To visualize the rendering component's size we use a WrappingIconProvider
* which sets a red border.
*
* Calling packxx might pose a problem: for non-large models the node size
* is cached. In this case, packing before replacing the renderer will lead
* to incorrect sizes which are hard to invalidate (no way except faking a
* structural tree event? temporaryly set large model and back, plus repaint
* works).
*
*/
public void interactiveTreeTableClipIssueWrappingProvider() {
final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel());
treeTable.setHorizontalScrollEnabled(true);
treeTable.setColumnControlVisible(true);
// BEWARE: do not pack before setting the renderer
treeTable.packColumn(0, -1);
StringValue format = new StringValue() {
public String getString(Object value) {
if (value instanceof Action) {
return ((Action) value).getValue(Action.NAME) + "xx";
}
return StringValue.TO_STRING.getString(value);
}
};
ComponentProvider tableProvider = new LabelProvider(format);
WrappingProvider wrappingProvider = new WrappingProvider(tableProvider) {
Border redBorder = BorderFactory.createLineBorder(Color.RED);
@Override
public WrappingIconPanel getRendererComponent(CellContext context) {
super.getRendererComponent(context);
rendererComponent.setBorder(redBorder);
return rendererComponent;
}
};
DefaultTreeRenderer treeCellRenderer = new DefaultTreeRenderer(
wrappingProvider);
treeTable.setTreeCellRenderer(treeCellRenderer);
treeTable.setHighlighters(HighlighterFactory.createSimpleStriping());
// at this point a pack is okay, caching will get the correct values
// treeTable.packColumn(0, -1);
final JXTree tree = new JXTree(treeTable.getTreeTableModel());
tree.setCellRenderer(treeCellRenderer);
tree.setScrollsOnExpand(false);
JXFrame frame = wrapWithScrollingInFrame(treeTable, tree,
"treetable and tree with wrapping provider");
// revalidate doesn't help
Action revalidate = new AbstractActionExt("revalidate") {
public void actionPerformed(ActionEvent e) {
treeTable.revalidate();
tree.revalidate();
treeTable.repaint();
}
};
// hack around incorrect cached node sizes
Action large = new AbstractActionExt("large-circle") {
public void actionPerformed(ActionEvent e) {
treeTable.setLargeModel(true);
treeTable.setLargeModel(false);
treeTable.repaint();
}
};
addAction(frame, revalidate);
addAction(frame, large);
show(frame);
}
/**
* Experiments to try and understand clipping issues: occasionally, the text
* in the tree column is clipped even if there is enough space available.
*
* Here we don't change any renderers.
*/
public void interactiveTreeTableClipIssueDefaultRenderer() {
final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel());
treeTable.setHorizontalScrollEnabled(true);
treeTable.setRootVisible(true);
treeTable.collapseAll();
treeTable.packColumn(0, -1);
final JTree tree = new JTree(treeTable.getTreeTableModel());
tree.collapseRow(0);
JXFrame frame = wrapWithScrollingInFrame(treeTable,
tree, "JXTreeTable vs. JTree: default renderer");
Action revalidate = new AbstractActionExt("revalidate") {
public void actionPerformed(ActionEvent e) {
treeTable.revalidate();
tree.revalidate();
} };
addAction(frame, revalidate);
frame.setVisible(true);
}
/**
* Experiments to try and understand clipping issues: occasionally, the text
* in the tree column is clipped even if there is enough space available.
* Here we set a custom (unchanged default) treeCellRenderer which
* removes ellipses altogether.
*
*/
public void interactiveTreeTableClipIssueCustomDefaultRenderer() {
TreeCellRenderer renderer = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean sel, boolean expanded, boolean leaf,
int row, boolean hasFocus) {
return super.getTreeCellRendererComponent(tree, value, sel,
expanded, leaf, row, hasFocus);
}
};
final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel());
treeTable.setTreeCellRenderer(renderer);
treeTable.setHorizontalScrollEnabled(true);
treeTable.setRootVisible(true);
treeTable.collapseAll();
treeTable.packColumn(0, -1);
final JTree tree = new JTree(treeTable.getTreeTableModel());
tree.setCellRenderer(renderer);
tree.collapseRow(0);
JXFrame frame = wrapWithScrollingInFrame(treeTable, tree,
"JXTreeTable vs. JTree: custom default renderer");
Action revalidate = new AbstractActionExt("revalidate") {
public void actionPerformed(ActionEvent e) {
treeTable.revalidate();
tree.revalidate();
}
};
addAction(frame, revalidate);
frame.setVisible(true);
}
/**
* Dirty example how to configure a custom renderer to use
* treeTableModel.getValueAt(...) for showing.
*
*/
public void interactiveTreeTableGetValueRenderer() {
JXTreeTable tree = new JXTreeTable(new ComponentTreeTableModel(new JXFrame()));
ComponentProvider provider = new CheckBoxProvider(StringValue.TO_STRING) {
@Override
protected String getValueAsString(CellContext context) {
// this is dirty because the design idea was to keep the renderer
// unaware of the context type
TreeTableModel model = (TreeTableModel) ((JXTree) context.getComponent()).getModel();
// beware: currently works only if the node is not a DefaultMutableTreeNode
// otherwise the WrappingProvider tries to be smart and replaces the node
// by the userObject before passing on to the wrappee!
Object nodeValue = model.getValueAt(context.getValue(), 0);
return formatter.getString(nodeValue);
}
};
tree.setTreeCellRenderer(new DefaultTreeRenderer(provider));
tree.expandAll();
tree.setHighlighters(HighlighterFactory.createSimpleStriping());
JFrame frame = wrapWithScrollingInFrame(tree, "treeTable and getValueAt renderer");
frame.setVisible(true);
}
/**
* Issue #399-swingx: editing terminated by selecting editing row.
*
*/
public void testSelectionKeepsEditingWithExpandsTrue() {
JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()) {
@Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
// sanity: default value of expandsSelectedPath
assertTrue(treeTable.getExpandsSelectedPaths());
boolean canEdit = treeTable.editCellAt(1, 2);
// sanity: editing started
assertTrue(canEdit);
// sanity: nothing selected
assertTrue(treeTable.getSelectionModel().isSelectionEmpty());
int editingRow = treeTable.getEditingRow();
treeTable.setRowSelectionInterval(editingRow, editingRow);
assertEquals("after selection treeTable editing state must be unchanged", canEdit, treeTable.isEditing());
}
/**
* Issue #212-jdnc: reuse editor, install only once.
*
*/
public void testReuseEditor() {
//TODO rework this test, since we no longer use TreeTableModel.class
// JXTreeTable treeTable = new JXTreeTable(treeTableModel);
// CellEditor editor = treeTable.getDefaultEditor(TreeTableModel.class);
// assertTrue(editor instanceof TreeTableCellEditor);
// treeTable.setTreeTableModel(simpleTreeTableModel);
// assertSame("hierarchical editor must be unchanged", editor,
// treeTable.getDefaultEditor(TreeTableModel.class));
fail("#212-jdnc - must be revisited after treeTableModel overhaul");
}
/**
* sanity: toggling select/unselect via mouse the lead is
* always painted, doing unselect via model (clear/remove path)
* seems to clear the lead?
*
*/
public void testBasicTreeLeadSelection() {
JXTree tree = new JXTree();
TreePath path = tree.getPathForRow(0);
tree.setSelectionPath(path);
assertEquals(0, tree.getSelectionModel().getLeadSelectionRow());
assertEquals(path, tree.getLeadSelectionPath());
tree.removeSelectionPath(path);
assertNotNull(tree.getLeadSelectionPath());
assertEquals(0, tree.getSelectionModel().getLeadSelectionRow());
}
/**
* Issue #341-swingx: missing synch of lead.
* test lead after setting selection via table.
*
* PENDING: this passes locally, fails on server
*/
public void testLeadSelectionFromTable() {
JXTreeTable treeTable = prepareTreeTable(false);
assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex());
assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow());
treeTable.setRowSelectionInterval(0, 0);
assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(),
treeTable.getTreeSelectionModel().getLeadSelectionRow());
}
/**
* Issue #341-swingx: missing synch of lead.
* test lead after setting selection via treeSelection.
* PENDING: this passes locally, fails on server
*
*/
public void testLeadSelectionFromTree() {
JXTreeTable treeTable = prepareTreeTable(false);
assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex());
assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow());
treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0));
assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(),
treeTable.getTreeSelectionModel().getLeadSelectionRow());
assertEquals(0, treeTable.getTreeSelectionModel().getLeadSelectionRow());
}
/**
* Issue #341-swingx: missing synch of lead.
* test lead after remove selection via tree.
*
*/
public void testLeadAfterRemoveSelectionFromTree() {
JXTreeTable treeTable = prepareTreeTable(true);
treeTable.getTreeSelectionModel().removeSelectionPath(
treeTable.getTreeSelectionModel().getLeadSelectionPath());
assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(),
treeTable.getTreeSelectionModel().getLeadSelectionRow());
}
/**
* Issue #341-swingx: missing synch of lead.
* test lead after clear selection via table.
*
*/
public void testLeadAfterClearSelectionFromTable() {
JXTreeTable treeTable = prepareTreeTable(true);
treeTable.clearSelection();
assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(),
treeTable.getTreeSelectionModel().getLeadSelectionRow());
}
/**
* Issue #341-swingx: missing synch of lead.
* test lead after clear selection via table.
*
*/
public void testLeadAfterClearSelectionFromTree() {
JXTreeTable treeTable = prepareTreeTable(true);
treeTable.getTreeSelectionModel().clearSelection();
assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(),
treeTable.getTreeSelectionModel().getLeadSelectionRow());
}
/**
* creates and configures a treetable for usage in selection tests.
*
* @param selectFirstRow boolean to indicate if the first row should
* be selected.
* @return
*/
protected JXTreeTable prepareTreeTable(boolean selectFirstRow) {
JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame()));
treeTable.setRootVisible(true);
// sanity: assert that we have at least two rows to change selection
assertTrue(treeTable.getRowCount() > 1);
if (selectFirstRow) {
treeTable.setRowSelectionInterval(0, 0);
}
return treeTable;
}
public void testDummy() {
}
/**
* @return
*/
private TreeTableModel createActionTreeModel() {
JXTable table = new JXTable(10, 10);
table.setHorizontalScrollEnabled(true);
return new ActionMapTreeTableModel(table);
}
} |
package city;
import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import utilities.DataModel;
import utilities.TrafficControl;
import city.Application.BUILDING;
import city.agents.BusAgent;
import city.agents.CarAgent;
import city.agents.PersonAgent;
import city.agents.interfaces.Person;
import city.animations.BusAnimation;
import city.animations.CarAnimation;
import city.animations.PersonAnimation;
import city.animations.WalkerAnimation;
import city.bases.Building;
import city.bases.interfaces.AnimationInterface;
import city.bases.interfaces.BuildingInterface;
import city.buildings.AptBuilding;
import city.buildings.BankBuilding;
import city.buildings.BusStopBuilding;
import city.buildings.HouseBuilding;
import city.buildings.MarketBuilding;
import city.buildings.RestaurantChoiBuilding;
import city.buildings.RestaurantChungBuilding;
import city.buildings.RestaurantJPBuilding;
import city.buildings.RestaurantTimmsBuilding;
import city.buildings.RestaurantZhangBuilding;
import city.gui.BuildingCard;
import city.gui.CityRoad;
import city.gui.CityRoad.STOPLIGHTTYPE;
import city.gui.CityRoadIntersection;
import city.gui.CitySidewalkLayout;
import city.gui.MainFrame;
import city.gui.exteriors.CityViewApt;
import city.gui.exteriors.CityViewBank;
import city.gui.exteriors.CityViewBuilding;
import city.gui.exteriors.CityViewBusStop;
import city.gui.exteriors.CityViewHouse;
import city.gui.exteriors.CityViewMarket;
import city.gui.exteriors.CityViewRestaurantChoi;
import city.gui.exteriors.CityViewRestaurantChung;
import city.gui.exteriors.CityViewRestaurantJP;
import city.gui.exteriors.CityViewRestaurantTimms;
import city.gui.exteriors.CityViewRestaurantZhang;
import city.gui.interiors.AptPanel;
import city.gui.interiors.BankPanel;
import city.gui.interiors.BusStopPanel;
import city.gui.interiors.HousePanel;
import city.gui.interiors.MarketPanel;
import city.gui.interiors.RestaurantChoiPanel;
import city.gui.interiors.RestaurantChungPanel;
import city.gui.interiors.RestaurantJPPanel;
import city.gui.interiors.RestaurantTimmsPanel;
import city.gui.interiors.RestaurantZhangPanel;
import city.roles.BankManagerRole;
import city.roles.BankTellerRole;
import city.roles.LandlordRole;
import city.roles.MarketCashierRole;
import city.roles.MarketDeliveryPersonRole;
import city.roles.MarketEmployeeRole;
import city.roles.MarketManagerRole;
import city.roles.RestaurantChoiCashierRole;
import city.roles.RestaurantChoiCookRole;
import city.roles.RestaurantChoiHostRole;
import city.roles.RestaurantChoiWaiterDirectRole;
import city.roles.RestaurantChoiWaiterQueueRole;
import city.roles.RestaurantChungCashierRole;
import city.roles.RestaurantChungCookRole;
import city.roles.RestaurantChungHostRole;
import city.roles.RestaurantChungWaiterMessageCookRole;
import city.roles.RestaurantChungWaiterRevolvingStandRole;
import city.roles.RestaurantJPCashierRole;
import city.roles.RestaurantJPCookRole;
import city.roles.RestaurantJPHostRole;
import city.roles.RestaurantJPWaiterRole;
import city.roles.RestaurantJPWaiterSharedDataRole;
import city.roles.RestaurantTimmsCashierRole;
import city.roles.RestaurantTimmsCookRole;
import city.roles.RestaurantTimmsHostRole;
import city.roles.RestaurantTimmsWaiterRole;
import city.roles.RestaurantZhangCashierRole;
import city.roles.RestaurantZhangCookRole;
import city.roles.RestaurantZhangHostRole;
import city.roles.RestaurantZhangWaiterRegularRole;
import city.roles.RestaurantZhangWaiterSharedDataRole;
public class Application {
private static MainFrame mainFrame;
private static Timer timer = new Timer();
private static Date date = new Date(0);
public static final int HALF_HOUR = 1800000; // A half hour in milliseconds
public static final int INTERVAL = 1000; // One interval is the simulation's equivalent of a half-hour
public static final int PAYCHECK_INTERVAL = 0; // TODO set the global interval at which people are paid
public static enum BANK_SERVICE {none, deposit, moneyWithdraw, atmDeposit};
public static enum TRANSACTION_TYPE {personal, business};
public static enum FOOD_ITEMS {steak, chicken, salad, pizza};
public static enum BUILDING {bank, busStop, house, apartment, market, restaurant};
static List<CityRoad> roads = new ArrayList<CityRoad>();
public static TrafficControl trafficControl;
public static CitySidewalkLayout sidewalks;
private static final DataModel model = new DataModel();
private static List<PersonAgent> people = new ArrayList<PersonAgent>();
/**
* Main routine to start the program.
*
* When the program is started, this is the first call. It opens the GUI window, loads
* configuration files, and causes the program to run.
*/
public static void main(String[] args) {
// Open the animation GUI
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
mainFrame = new MainFrame();
// Load a scenario
parseConfig();
// Start the simulation
final DateFormat df = new SimpleDateFormat("MMMM dd HHmm");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
TimerTask tt = new TimerTask() {
public void run() {
date.setTime(date.getTime() + HALF_HOUR);
mainFrame.setDisplayDate(df.format(date));
for (Person p : model.getPeople()) {
p.setDate(date);
}
}
};
timer.scheduleAtFixedRate(tt, 0, INTERVAL);
}
/**
* This will eventually load some type of configuration file that specifies how many
* people to create and what roles to create them in.
*/
private static void parseConfig() {
// Create roads
// North roads
for(int i = 375; i >= 100; i -= 25) {
if(i == 225)
continue;
CityRoad tempRoad = new CityRoad(i, 75, 25, 25, -1, 0, true, Color.black);
roads.add(tempRoad);
}
// West roads
for(int i = 75; i <= 350; i+=25) {
if(i == 225)
continue;
CityRoad tempRoad = new CityRoad(75, i, 25, 25, 0, 1, false, Color.black);
roads.add(tempRoad);
}
// South roads
for(int i = 75; i <= 350; i+=25) {
if(i == 225)
continue;
CityRoad tempRoad = new CityRoad(i, 375, 25, 25, 1, 0, true, Color.black);
roads.add(tempRoad);
}
// East roads
for(int i = 375; i >= 100; i-=25) {
if(i == 225)
continue;
CityRoad tempRoad = new CityRoad(375, i, 25, 25, 0, -1, false, Color.black);
roads.add(tempRoad);
}
// North/South middle roads
for(int i = 350; i >= 100; i-=25) {
if(i == 225)
continue;
CityRoad tempRoad = new CityRoad(225, i, 25, 25, 0, -1, false, Color.black);
roads.add(tempRoad);
}
// East/West middle roads
for(int i = 350; i >= 100; i -= 25) {
if(i == 225)
continue;
CityRoad tempRoad = new CityRoad(i, 225, 25, 25, -1, 0, true, Color.black);
roads.add(tempRoad);
}
// North intersection
CityRoadIntersection intersectionNorth = new CityRoadIntersection(225, 75, 25, 25, Color.gray);
roads.add(intersectionNorth);
// West intersection
CityRoadIntersection intersectionWest = new CityRoadIntersection(75, 225, 25, 25, Color.gray);
roads.add(intersectionWest);
// South intersection
CityRoadIntersection intersectionSouth = new CityRoadIntersection(225, 375, 25, 25, Color.gray);
roads.add(intersectionSouth);
// East intersection
CityRoadIntersection intersectionEast = new CityRoadIntersection(375, 225, 25, 25, Color.gray);
roads.add(intersectionEast);
// Center intersection
CityRoadIntersection intersectionCenter = new CityRoadIntersection(225, 225, 25, 25, Color.gray);
roads.add(intersectionCenter);
// Connect all roads
for(int i = 0; i < roads.size() - 1; i++) {
if(roads.get(i).getX() == intersectionNorth.getX() + 25 && roads.get(i).getY() == intersectionNorth.getY()) { // Set nextRoad of road to east of north intersection
roads.get(i).setNextRoad(intersectionNorth);
continue;
} else if(roads.get(i).getX() == intersectionNorth.getX() + 50 && roads.get(i).getY() == intersectionNorth.getY()) { // Set stoplight to east of north intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.HORIZONTALOFF);
} else if(roads.get(i).getY() == intersectionNorth.getY() + 25 && roads.get(i).getX() == intersectionNorth.getX()) { // Set nextRoad of road to south of north intersection
roads.get(i).setNextRoad(intersectionNorth);
continue;
} else if(roads.get(i).getY() == intersectionNorth.getY() + 50 && roads.get(i).getX() == intersectionNorth.getX()) { // Set stoplight of road to south of north intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.VERTICALOFF);
} else if(roads.get(i).getX() == intersectionNorth.getX() - 25 && roads.get(i).getY() == intersectionNorth.getY()) { // Set nextRoad of road to west of north intersection
intersectionNorth.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getY() == intersectionWest.getY() - 25 && roads.get(i).getX() == intersectionWest.getX()) { // Set nextRoad of road to north of west intersection
roads.get(i).setNextRoad(intersectionWest);
continue;
} else if(roads.get(i).getY() == intersectionWest.getY() - 50 && roads.get(i).getX() == intersectionWest.getX()) { // Set stoplight of road to north of west intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.VERTICALOFF);
} else if(roads.get(i).getY() == intersectionWest.getY() + 25 && roads.get(i).getX() == intersectionWest.getX()) { // Set nextRoad of road to south of west intersection
intersectionWest.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getX() == intersectionWest.getX() + 25 && roads.get(i).getY() == intersectionWest.getY()) { // Set nextRoad of road to east of west intersection
roads.get(i).setNextRoad(intersectionWest);
continue;
} else if(roads.get(i).getX() == intersectionWest.getX() + 50 && roads.get(i).getY() == intersectionWest.getY()) { // Set stoplight of road to east of west intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.HORIZONTALOFF);
} else if(roads.get(i).getY() == intersectionSouth.getY() - 25 && roads.get(i).getX() == intersectionSouth.getX()) { // Set nextRoad of road to north of south intersection
intersectionSouth.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getX() == intersectionSouth.getX() - 25 && roads.get(i).getY() == intersectionSouth.getY()) { // Set nextRoad of road to west of south intersection
roads.get(i).setNextRoad(intersectionSouth);
continue;
} else if(roads.get(i).getX() == intersectionSouth.getX() - 50 && roads.get(i).getY() == intersectionSouth.getY()) { // Set stoplight of road to west of south intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.HORIZONTALOFF);
} else if(roads.get(i).getX() == intersectionSouth.getX() + 25 && roads.get(i).getY() == intersectionSouth.getY()) { // Set nextRoad of road to east of south intersection
intersectionSouth.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getY() == intersectionEast.getY() - 25 && roads.get(i).getX() == intersectionEast.getX()) { // Set nextRoad of road to north of east intersection
intersectionEast.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getX() == intersectionEast.getX() - 25 && roads.get(i).getY() == intersectionEast.getY()) { // Set nextRoad of road to west of east intersection
intersectionEast.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getY() == intersectionEast.getY() + 25 && roads.get(i).getX() == intersectionEast.getX()) { // Set nextRoad of road to south of east intersection
roads.get(i).setNextRoad(intersectionEast);
continue;
} else if(roads.get(i).getY() == intersectionEast.getY() + 50 && roads.get(i).getX() == intersectionEast.getX()) { // Set stoplight of road to south of east intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.VERTICALOFF);
} else if(roads.get(i).getY() == intersectionCenter.getY() - 25 && roads.get(i).getX() == intersectionCenter.getX()) { // Set nextRoad of road to north of center intersection
intersectionCenter.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getX() == intersectionCenter.getX() + 25 && roads.get(i).getY() == intersectionCenter.getY()) { // Set nextRoad of road to east of center intersection
roads.get(i).setNextRoad(intersectionCenter);
continue;
} else if(roads.get(i).getX() == intersectionCenter.getX() + 50 && roads.get(i).getY() == intersectionCenter.getY()) { // Set stoplight of road to east of center intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.HORIZONTALOFF);
} else if(roads.get(i).getX() == intersectionCenter.getX() - 25 && roads.get(i).getY() == intersectionCenter.getY()) { // Set nextRoad of road to west of center intersection
intersectionCenter.setNextRoad(roads.get(i));
roads.get(i).setNextRoad(roads.get(i + 1));
continue;
} else if(roads.get(i).getY() == intersectionCenter.getY() + 25 && roads.get(i).getX() == intersectionCenter.getX()) { // Set nextRoad of road to south of center intersection
roads.get(i).setNextRoad(intersectionCenter);
continue;
} else if(roads.get(i).getY() == intersectionCenter.getY() + 50 && roads.get(i).getX() == intersectionCenter.getX()) { // Set stoplight of road to south of center intersection
roads.get(i).setStopLightType(STOPLIGHTTYPE.VERTICALOFF);
} else if(roads.get(i).getX() == 375 && roads.get(i).getY() == 100) { // Last road in the outer loop
roads.get(i).setNextRoad(roads.get(0));
continue;
}
// Straight road
if(roads.get(i).getClass() != CityRoadIntersection.class)
roads.get(i).setNextRoad(roads.get(i+1));
}
trafficControl = new TrafficControl(roads);
// Create Sidewalks
ArrayList<Rectangle> nonSidewalkArea = new ArrayList<Rectangle>();
nonSidewalkArea.add(new Rectangle(2, 2, 14, 2)); // Top left
nonSidewalkArea.add(new Rectangle(18, 2, 10, 2)); // Top right
nonSidewalkArea.add(new Rectangle(2, 4, 2, 8)); // Topmid left
nonSidewalkArea.add(new Rectangle(14, 6, 2, 10)); // Topmid center
nonSidewalkArea.add(new Rectangle(26, 4, 2, 12)); // Topmid right
nonSidewalkArea.add(new Rectangle(6, 14, 10, 2)); // Center left
nonSidewalkArea.add(new Rectangle(18, 14, 10, 2)); // Center right
nonSidewalkArea.add(new Rectangle(2, 14, 2, 12)); // Bottommid left
nonSidewalkArea.add(new Rectangle(14, 18, 2, 8)); // Bottommid center
nonSidewalkArea.add(new Rectangle(26, 18, 2, 8)); // Bottommid right
nonSidewalkArea.add(new Rectangle(2, 26, 10, 2)); // Bottom left
nonSidewalkArea.add(new Rectangle(14, 26, 14, 2)); // Bottom right
nonSidewalkArea.add(new Rectangle(6, 6, 6, 6)); // Top left square
nonSidewalkArea.add(new Rectangle(18, 6, 6, 6)); // Top right square
nonSidewalkArea.add(new Rectangle(6, 18, 6, 6)); // Bottom left square
nonSidewalkArea.add(new Rectangle(18, 18, 6, 6)); // Bottom right square
sidewalks = new CitySidewalkLayout(mainFrame, 30, 30, 50, 50, 12.5, Color.orange, nonSidewalkArea, trafficControl);
//Create Bus Stops
BusStopPanel bsp1 = new BusStopPanel(Color.white);
CityViewBusStop cityViewBusStop1 = new CityViewBusStop(325, 125, "Bus Stop 1", Color.white, bsp1);
BusStopBuilding busStop1 = new BusStopBuilding("Bus Stop 1", bsp1, cityViewBusStop1);
setBuilding(bsp1, cityViewBusStop1, busStop1);
BusStopPanel bsp2 = new BusStopPanel(Color.white);
CityViewBusStop cityViewBusStop2 = new CityViewBusStop(125, 125, "Bus Stop 2", Color.white, bsp2);
BusStopBuilding busStop2 = new BusStopBuilding("Bus Stop 2", bsp2, cityViewBusStop2);
setBuilding(bsp2, cityViewBusStop2, busStop2);
BusStopPanel bsp3 = new BusStopPanel(Color.white);
CityViewBusStop cityViewBusStop3 = new CityViewBusStop(325, 325, "Bus Stop 3", Color.white, bsp3);
BusStopBuilding busStop3 = new BusStopBuilding("Bus Stop 3", bsp3, cityViewBusStop3);
setBuilding(bsp3, cityViewBusStop3, busStop3);
BusStopPanel bsp4 = new BusStopPanel(Color.white);
CityViewBusStop cityViewBusStop4 = new CityViewBusStop(125, 325, "Bus Stop 4", Color.white, bsp4);
BusStopBuilding busStop4 = new BusStopBuilding("Bus Stop 4", bsp4, cityViewBusStop4);
setBuilding(bsp4, cityViewBusStop4, busStop4);
busStop1.setNextStop(busStop2);
busStop1.setPreviousStop(busStop4);
busStop2.setNextStop(busStop3);
busStop2.setPreviousStop(busStop1);
busStop3.setNextStop(busStop4);
busStop3.setPreviousStop(busStop2);
busStop4.setNextStop(busStop1);
busStop4.setPreviousStop(busStop3);
BusAgent bus1 = new BusAgent(busStop1, busStop2);
BusAnimation b1Anim = new BusAnimation(bus1, busStop1);
bus1.setAnimation(b1Anim);
mainFrame.cityView.addAnimation(b1Anim);
CityMap.findClosestRoad(busStop1).setVehicle(b1Anim);
bus1.startThread();
// Create buildings
AptBuilding Apartment1 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 75);
AptBuilding Apartment2 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 100);
AptBuilding Apartment3 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 150);
AptBuilding Apartment4 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 200);
AptBuilding Apartment5 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 250);
AptBuilding Apartment6 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 300);
AptBuilding Apartment7 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 350);
AptBuilding Apartment8 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 25, 375);
AptBuilding Apartment9 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 75, 425);
AptBuilding Apartment10 = (AptBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.APT, 100, 425);
BankBuilding bank1 = (BankBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.BANK, 425, 75);
MarketBuilding market1 = (MarketBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.MARKET, 425, 100);
RestaurantTimmsBuilding restaurantTimms = (RestaurantTimmsBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.RESTAURANTTIMMS, 425, 150);
RestaurantZhangBuilding restaurantZhang = (RestaurantZhangBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.RESTAURANTZHANG, 425, 200);
RestaurantChoiBuilding restaurantChoi = (RestaurantChoiBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.RESTAURANTCHOI, 425, 250);
RestaurantChungBuilding restaurantChung = (RestaurantChungBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.RESTAURANTCHUNG, 425, 300);
RestaurantJPBuilding restaurantJP = (RestaurantJPBuilding)createBuilding(CityViewBuilding.BUILDINGTYPE.RESTAURANTJP, 425, 350);
// Create People
PersonAgent p1 = new PersonAgent("Timms Host", date, new PersonAnimation(), Apartment1);
PersonAgent p2 = new PersonAgent("Timms Cashier", date, new PersonAnimation(), Apartment1);
PersonAgent p3 = new PersonAgent("Timms Cook", date, new PersonAnimation(), Apartment1);
PersonAgent p4 = new PersonAgent("Timms Waiter1", date, new PersonAnimation(), Apartment1);
PersonAgent p5 = new PersonAgent("Timms Waiter2", date, new PersonAnimation(), Apartment1);
PersonAgent p6 = new PersonAgent("Chung Host", date, new PersonAnimation(), Apartment2);
PersonAgent p7 = new PersonAgent("Chung Cashier", date, new PersonAnimation(), Apartment2);
PersonAgent p8 = new PersonAgent("Chung Cook", date, new PersonAnimation(), Apartment2);
PersonAgent p9 = new PersonAgent("Chung Waiter1", date, new PersonAnimation(), Apartment2);
PersonAgent p10 = new PersonAgent("Chung Waiter2", date, new PersonAnimation(), Apartment2);
PersonAgent p11 = new PersonAgent("Zhang Host", date, new PersonAnimation(), Apartment3);
PersonAgent p12 = new PersonAgent("Zhang Cashier", date, new PersonAnimation(), Apartment3);
PersonAgent p13 = new PersonAgent("Zhang Cook", date, new PersonAnimation(), Apartment3);
PersonAgent p14 = new PersonAgent("Zhang Waiter1", date, new PersonAnimation(), Apartment3);
PersonAgent p15 = new PersonAgent("Zhang Waiter2", date, new PersonAnimation(), Apartment3);
PersonAgent p16 = new PersonAgent("Choi Host", date, new PersonAnimation(), Apartment4);
PersonAgent p17 = new PersonAgent("Choi Cashier", date, new PersonAnimation(), Apartment4);
PersonAgent p18 = new PersonAgent("Choi Cook", date, new PersonAnimation(), Apartment4);
PersonAgent p19 = new PersonAgent("Choi Waiter1", date, new PersonAnimation(), Apartment4);
PersonAgent p20 = new PersonAgent("Choi Waiter2", date, new PersonAnimation(), Apartment4);
PersonAgent p21 = new PersonAgent("JP Host", date, new PersonAnimation(), Apartment5);
PersonAgent p22 = new PersonAgent("JP Cashier", date, new PersonAnimation(), Apartment5);
PersonAgent p23 = new PersonAgent("JP Cook", date, new PersonAnimation(), Apartment5);
PersonAgent p24 = new PersonAgent("JP Waiter1", date, new PersonAnimation(), Apartment5);
PersonAgent p25 = new PersonAgent("JP Waiter2", date, new PersonAnimation(), Apartment5);
PersonAgent p26 = new PersonAgent("Bank Manager", date, new PersonAnimation(), Apartment6);
PersonAgent p27 = new PersonAgent("Bank Teller1", date, new PersonAnimation(), Apartment6);
PersonAgent p28 = new PersonAgent("Bank Teller2", date, new PersonAnimation(), Apartment6);
PersonAgent p29 = new PersonAgent("Bank Teller3", date, new PersonAnimation(), Apartment6);
PersonAgent p30 = new PersonAgent("Bank Robber", date, new PersonAnimation(), Apartment6);
PersonAgent p31 = new PersonAgent("Market Manager", date, new PersonAnimation(), Apartment7);
PersonAgent p32 = new PersonAgent("Market Cashier", date, new PersonAnimation(), Apartment7);
PersonAgent p33 = new PersonAgent("Market Delivery Man", date, new PersonAnimation(), Apartment7);
PersonAgent p34 = new PersonAgent("Market Employee1", date, new PersonAnimation(), Apartment7);
PersonAgent p35 = new PersonAgent("Market Employee2", date, new PersonAnimation(), Apartment7);
PersonAgent p36 = new PersonAgent("Consumer1", date, new PersonAnimation(), Apartment8);
PersonAgent p37 = new PersonAgent("Consumer2", date, new PersonAnimation(), Apartment8);
PersonAgent p38 = new PersonAgent("Consumer3", date, new PersonAnimation(), Apartment8);
PersonAgent p39 = new PersonAgent("Consumer4", date, new PersonAnimation(), Apartment8);
PersonAgent p40 = new PersonAgent("Consumer5", date, new PersonAnimation(), Apartment8);
PersonAgent p41 = new PersonAgent("Consumer6", date, new PersonAnimation(), Apartment9);
PersonAgent p42 = new PersonAgent("Consumer7", date, new PersonAnimation(), Apartment9);
PersonAgent p43 = new PersonAgent("Consumer8", date, new PersonAnimation(), Apartment9);
PersonAgent p44 = new PersonAgent("Consumer9", date, new PersonAnimation(), Apartment9);
PersonAgent p45 = new PersonAgent("Consumer10", date, new PersonAnimation(), Apartment9);
PersonAgent p46 = new PersonAgent("Consumer11", date, new PersonAnimation(), Apartment10);
PersonAgent p47 = new PersonAgent("Consumer12", date, new PersonAnimation(), Apartment10);
PersonAgent p48 = new PersonAgent("Consumer13", date, new PersonAnimation(), Apartment10);
PersonAgent p49 = new PersonAgent("Consumer14", date, new PersonAnimation(), Apartment10);
PersonAgent p50 = new PersonAgent("Consumer15", date, new PersonAnimation(), Apartment10);
//Create Landlords
LandlordRole landlord1 = new LandlordRole();
p1.addRole(landlord1);
Apartment1.setLandlord(landlord1);
landlord1.setActive();
LandlordRole landlord2 = new LandlordRole();
p6.addRole(landlord2);
Apartment2.setLandlord(landlord2);
landlord2.setActive();
LandlordRole landlord3 = new LandlordRole();
p11.addRole(landlord3);
Apartment3.setLandlord(landlord3);
landlord3.setActive();
LandlordRole landlord4 = new LandlordRole();
p16.addRole(landlord4);
Apartment4.setLandlord(landlord4);
landlord4.setActive();
LandlordRole landlord5 = new LandlordRole();
p21.addRole(landlord5);
Apartment5.setLandlord(landlord5);
landlord5.setActive();
LandlordRole landlord6 = new LandlordRole();
p26.addRole(landlord6);
Apartment6.setLandlord(landlord6);
landlord6.setActive();
LandlordRole landlord7 = new LandlordRole();
p31.addRole(landlord7);
Apartment7.setLandlord(landlord7);
landlord7.setActive();
LandlordRole landlord8 = new LandlordRole();
p36.addRole(landlord8);
Apartment8.setLandlord(landlord8);
landlord8.setActive();
LandlordRole landlord9 = new LandlordRole();
p41.addRole(landlord9);
Apartment9.setLandlord(landlord9);
landlord9.setActive();
LandlordRole landlord10 = new LandlordRole();
p46.addRole(landlord10);
Apartment10.setLandlord(landlord10);
landlord10.setActive();
// Create occupations
//RESTAURANTS
//RestaurantTimms
RestaurantTimmsHostRole timmsHost = new RestaurantTimmsHostRole(restaurantTimms, 0, 24);
restaurantTimms.addOccupyingRole(timmsHost);
p1.setOccupation(timmsHost);
RestaurantTimmsCashierRole timmsCashier = new RestaurantTimmsCashierRole(restaurantTimms, 0, 24);
restaurantTimms.addOccupyingRole(timmsCashier);
p2.setOccupation(timmsCashier);
RestaurantTimmsCookRole timmsCook = new RestaurantTimmsCookRole(restaurantTimms, 0, 24);
restaurantTimms.addOccupyingRole(timmsCook);
p3.setOccupation(timmsCook);
RestaurantTimmsWaiterRole timmsWaiter1 = new RestaurantTimmsWaiterRole(restaurantTimms, 0, 24);
restaurantTimms.addOccupyingRole(timmsWaiter1);
p4.setOccupation(timmsWaiter1);
RestaurantTimmsWaiterRole timmsWaiter2 = new RestaurantTimmsWaiterRole(restaurantTimms, 0, 24);
restaurantTimms.addOccupyingRole(timmsWaiter2);
p5.setOccupation(timmsWaiter2);
//Chung Restaurant
RestaurantChungHostRole chungHost = new RestaurantChungHostRole(restaurantChung, 0, 24);
restaurantChung.addOccupyingRole(chungHost);
p6.setOccupation(chungHost);
RestaurantChungCashierRole chungCashier = new RestaurantChungCashierRole(restaurantChung, 0, 24);
restaurantChung.addOccupyingRole(chungCashier);
p7.setOccupation(chungCashier);
RestaurantChungCookRole chungCook = new RestaurantChungCookRole(restaurantChung, 0, 24);
restaurantChung.addOccupyingRole(chungCook);
p8.setOccupation(chungCook);
RestaurantChungWaiterMessageCookRole chungWaiter1 = new RestaurantChungWaiterMessageCookRole(restaurantChung, 0, 24);
restaurantChung.addOccupyingRole(chungWaiter1);
p9.setOccupation(chungWaiter1);
RestaurantChungWaiterRevolvingStandRole chungWaiter2 = new RestaurantChungWaiterRevolvingStandRole(restaurantChung, 0, 24);
restaurantChung.addOccupyingRole(chungWaiter2);
p10.setOccupation(chungWaiter2);
//RestaurantZhang
RestaurantZhangHostRole zhangHost = new RestaurantZhangHostRole(restaurantZhang, 0, 24);
restaurantZhang.addOccupyingRole(zhangHost);
p11.setOccupation(zhangHost);
RestaurantZhangCashierRole zhangCashier = new RestaurantZhangCashierRole(restaurantZhang, 0, 24);
restaurantZhang.addOccupyingRole(zhangCashier);
p12.setOccupation(zhangCashier);
RestaurantZhangCookRole zhangCook = new RestaurantZhangCookRole(restaurantZhang, 0, 24);
restaurantZhang.addOccupyingRole(zhangCook);
p13.setOccupation(zhangCook);
RestaurantZhangWaiterRegularRole zhangWaiter1 = new RestaurantZhangWaiterRegularRole(restaurantZhang, 0, 24);
restaurantZhang.addOccupyingRole(zhangWaiter1);
p14.setOccupation(zhangWaiter1);
RestaurantZhangWaiterSharedDataRole zhangWaiter2 = new RestaurantZhangWaiterSharedDataRole(restaurantZhang, 0, 24);
restaurantZhang.addOccupyingRole(zhangWaiter2);
p15.setOccupation(zhangWaiter2);
//RestaurantChoi
RestaurantChoiHostRole choiHost = new RestaurantChoiHostRole(restaurantChoi, 0, 24);
restaurantChoi.addOccupyingRole(choiHost);
p16.setOccupation(choiHost);
RestaurantChoiCashierRole choiCashier = new RestaurantChoiCashierRole(restaurantChoi, 0, 24);
restaurantChoi.addOccupyingRole(choiCashier);
p17.setOccupation(choiCashier);
RestaurantChoiCookRole choiCook = new RestaurantChoiCookRole(restaurantChoi, 0, 24);
restaurantChoi.addOccupyingRole(choiCook);
p18.setOccupation(choiCook);
RestaurantChoiWaiterDirectRole choiWaiter1 = new RestaurantChoiWaiterDirectRole(restaurantChoi, 0, 24);
restaurantChoi.addOccupyingRole(choiWaiter1);
p19.setOccupation(choiWaiter1);
RestaurantChoiWaiterQueueRole choiWaiter2 = new RestaurantChoiWaiterQueueRole(restaurantChoi, 0, 24);
restaurantChoi.addOccupyingRole(choiWaiter2);
p20.setOccupation(choiWaiter2);
//RestaurantJP
RestaurantJPHostRole jpHost = new RestaurantJPHostRole(restaurantJP, 0, 24);
restaurantJP.addOccupyingRole(jpHost);
p21.setOccupation(jpHost);
RestaurantJPCashierRole jpCashier = new RestaurantJPCashierRole(restaurantJP, 0, 24);
restaurantJP.addOccupyingRole(jpCashier);
p22.setOccupation(jpCashier);
RestaurantJPCookRole jpCook = new RestaurantJPCookRole(restaurantJP, 0, 24);
restaurantJP.addOccupyingRole(jpCook);
p23.setOccupation(jpCook);
RestaurantJPWaiterRole jpWaiter1 = new RestaurantJPWaiterRole(restaurantJP, 0, 24);
restaurantJP.addOccupyingRole(jpWaiter1);
p24.setOccupation(jpWaiter1);
RestaurantJPWaiterSharedDataRole jpWaiter2 = new RestaurantJPWaiterSharedDataRole(restaurantJP, 0, 24);
restaurantJP.addOccupyingRole(jpWaiter2);
p25.setOccupation(jpWaiter2);
//BANK
BankManagerRole bankManager = new BankManagerRole(bank1, 0, 24);
bank1.addOccupyingRole(bankManager);
p26.setOccupation(bankManager);
BankTellerRole bankTeller1 = new BankTellerRole(bank1, 0, 24);
bank1.addOccupyingRole(bankTeller1);
p27.setOccupation(bankTeller1);
BankTellerRole bankTeller2 = new BankTellerRole(bank1, 0, 24);
bank1.addOccupyingRole(bankTeller2);
p28.setOccupation(bankTeller2);
BankTellerRole bankTeller3 = new BankTellerRole(bank1, 0, 24);
bank1.addOccupyingRole(bankTeller3);
p29.setOccupation(bankTeller3);
//MARKET
MarketManagerRole marketManager = new MarketManagerRole(market1, 0, 24);
market1.addOccupyingRole(marketManager);
p31.setOccupation(marketManager);
MarketDeliveryPersonRole marketDelivery = new MarketDeliveryPersonRole(market1, 0, 24);
market1.addOccupyingRole(marketDelivery);
p32.setOccupation(marketDelivery);
MarketCashierRole marketCashier = new MarketCashierRole(market1, 0, 24);
market1.addOccupyingRole(marketCashier);
p33.setOccupation(marketCashier);
MarketEmployeeRole marketEmployee1 = new MarketEmployeeRole(market1, 0, 24);
market1.addOccupyingRole(marketEmployee1);
p34.setOccupation(marketEmployee1);
MarketEmployeeRole marketEmployee2 = new MarketEmployeeRole(market1, 0, 24);
market1.addOccupyingRole(marketEmployee2);
p35.setOccupation(marketEmployee2);
people.add(p1);
people.add(p2);
people.add(p3);
people.add(p4);
people.add(p5);
people.add(p6);
people.add(p7);
people.add(p8);
people.add(p9);
people.add(p10);
people.add(p11);
people.add(p12);
people.add(p13);
people.add(p14);
people.add(p15);
people.add(p16);
people.add(p17);
people.add(p18);
people.add(p19);
people.add(p20);
people.add(p21);
people.add(p22);
people.add(p23);
people.add(p24);
people.add(p25);
people.add(p26);
people.add(p27);
people.add(p28);
people.add(p29);
people.add(p30);
people.add(p31);
people.add(p32);
people.add(p33);
people.add(p34);
people.add(p35);
people.add(p36);
people.add(p37);
people.add(p38);
people.add(p39);
people.add(p40);
people.add(p41);
people.add(p42);
people.add(p43);
people.add(p44);
people.add(p45);
people.add(p46);
people.add(p47);
people.add(p48);
people.add(p49);
people.add(p50);
for(PersonAgent p : people){
model.addPerson(p);
}
for(PersonAgent p : people){
p.setCash(200);
}
// delivery Person's car
CarAgent carDelivery = new CarAgent(market1, marketDelivery); // setting b to be the current location of the car
CarAnimation carAnim = new CarAnimation(carDelivery, market1);
carDelivery.setAnimation(carAnim);
mainFrame.cityView.addAnimation(carAnim);
marketDelivery.setDeliveryCar(carDelivery);
carDelivery.startThread();
CarAgent c1 = new CarAgent(Apartment1, p1);
CarAnimation c1Anim = new CarAnimation(c1, Apartment1);
c1.setAnimation(c1Anim);
mainFrame.cityView.addAnimation(c1Anim);
CarAgent c2 = new CarAgent(Apartment1, p2);
CarAnimation c2Anim = new CarAnimation(c2, Apartment1);
c2.setAnimation(c2Anim);
mainFrame.cityView.addAnimation(c2Anim);
CarAgent c3 = new CarAgent(Apartment1, p3);
CarAnimation c3Anim = new CarAnimation(c3, Apartment1);
c3.setAnimation(c3Anim);
mainFrame.cityView.addAnimation(c3Anim);
CarAgent c4 = new CarAgent(Apartment1, p4);
CarAnimation c4Anim = new CarAnimation(c4, Apartment1);
c4.setAnimation(c4Anim);
mainFrame.cityView.addAnimation(c4Anim);
CarAgent c5 = new CarAgent(Apartment1, p5);
CarAnimation c5Anim = new CarAnimation(c5, Apartment1);
c5.setAnimation(c5Anim);
mainFrame.cityView.addAnimation(c5Anim);
CarAgent c6 = new CarAgent(Apartment2, p6);
CarAnimation c6Anim = new CarAnimation(c6, Apartment2);
c6.setAnimation(c6Anim);
mainFrame.cityView.addAnimation(c6Anim);
CarAgent c7 = new CarAgent(Apartment2, p7);
CarAnimation c7Anim = new CarAnimation(c7, Apartment1);
c7.setAnimation(c7Anim);
mainFrame.cityView.addAnimation(c7Anim);
CarAgent c8 = new CarAgent(Apartment2, p8);
CarAnimation c8Anim = new CarAnimation(c8, Apartment2);
c8.setAnimation(c8Anim);
mainFrame.cityView.addAnimation(c8Anim);
CarAgent c9 = new CarAgent(Apartment2, p9);
CarAnimation c9Anim = new CarAnimation(c9, Apartment2);
c9.setAnimation(c9Anim);
mainFrame.cityView.addAnimation(c9Anim);
CarAgent c10 = new CarAgent(Apartment2, p10);
CarAnimation c10Anim = new CarAnimation(c10, Apartment2);
c10.setAnimation(c10Anim);
mainFrame.cityView.addAnimation(c10Anim);
CarAgent c11 = new CarAgent(Apartment3, p11);
CarAnimation c11Anim = new CarAnimation(c11, Apartment3);
c11.setAnimation(c11Anim);
mainFrame.cityView.addAnimation(c11Anim);
CarAgent c12 = new CarAgent(Apartment3, p12);
CarAnimation c12Anim = new CarAnimation(c12, Apartment3);
c12.setAnimation(c12Anim);
mainFrame.cityView.addAnimation(c12Anim);
CarAgent c13 = new CarAgent(Apartment3, p13);
CarAnimation c13Anim = new CarAnimation(c13, Apartment3);
c13.setAnimation(c13Anim);
mainFrame.cityView.addAnimation(c13Anim);
CarAgent c14 = new CarAgent(Apartment3, p14);
CarAnimation c14Anim = new CarAnimation(c14, Apartment3);
c14.setAnimation(c14Anim);
mainFrame.cityView.addAnimation(c14Anim);
CarAgent c15 = new CarAgent(Apartment3, p15);
CarAnimation c15Anim = new CarAnimation(c15, Apartment3);
c15.setAnimation(c15Anim);
mainFrame.cityView.addAnimation(c15Anim);
CarAgent c16 = new CarAgent(Apartment4, p16);
CarAnimation c16Anim = new CarAnimation(c16, Apartment4);
c16.setAnimation(c16Anim);
mainFrame.cityView.addAnimation(c16Anim);
CarAgent c17 = new CarAgent(Apartment4, p17);
CarAnimation c17Anim = new CarAnimation(c17, Apartment4);
c17.setAnimation(c17Anim);
mainFrame.cityView.addAnimation(c17Anim);
CarAgent c18 = new CarAgent(Apartment4, p18);
CarAnimation c18Anim = new CarAnimation(c18, Apartment4);
c18.setAnimation(c18Anim);
mainFrame.cityView.addAnimation(c18Anim);
CarAgent c19 = new CarAgent(Apartment4, p19);
CarAnimation c19Anim = new CarAnimation(c19, Apartment4);
c19.setAnimation(c19Anim);
mainFrame.cityView.addAnimation(c19Anim);
CarAgent c20 = new CarAgent(Apartment4, p20);
CarAnimation c20Anim = new CarAnimation(c20, Apartment4);
c20.setAnimation(c20Anim);
mainFrame.cityView.addAnimation(c20Anim);
CarAgent c21 = new CarAgent(Apartment5, p21);
CarAnimation c21Anim = new CarAnimation(c21, Apartment5);
c21.setAnimation(c21Anim);
mainFrame.cityView.addAnimation(c21Anim);
CarAgent c22 = new CarAgent(Apartment5, p22);
CarAnimation c22Anim = new CarAnimation(c22, Apartment5);
c22.setAnimation(c22Anim);
mainFrame.cityView.addAnimation(c22Anim);
CarAgent c23 = new CarAgent(Apartment5, p23);
CarAnimation c23Anim = new CarAnimation(c23, Apartment5);
c23.setAnimation(c23Anim);
mainFrame.cityView.addAnimation(c23Anim);
CarAgent c24 = new CarAgent(Apartment5, p24);
CarAnimation c24Anim = new CarAnimation(c24, Apartment5);
c24.setAnimation(c24Anim);
mainFrame.cityView.addAnimation(c24Anim);
CarAgent c25 = new CarAgent(Apartment5, p25);
CarAnimation c25Anim = new CarAnimation(c25, Apartment5);
c25.setAnimation(c25Anim);
mainFrame.cityView.addAnimation(c25Anim);
CarAgent c26 = new CarAgent(Apartment6, p26);
CarAnimation c26Anim = new CarAnimation(c26, Apartment6);
c26.setAnimation(c26Anim);
mainFrame.cityView.addAnimation(c26Anim);
CarAgent c27 = new CarAgent(Apartment6, p27);
CarAnimation c27Anim = new CarAnimation(c27, Apartment6);
c27.setAnimation(c27Anim);
mainFrame.cityView.addAnimation(c27Anim);
CarAgent c28 = new CarAgent(Apartment6, p28);
CarAnimation c28Anim = new CarAnimation(c28, Apartment6);
c28.setAnimation(c28Anim);
mainFrame.cityView.addAnimation(c28Anim);
CarAgent c29 = new CarAgent(Apartment6, p29);
CarAnimation c29Anim = new CarAnimation(c29, Apartment6);
c29.setAnimation(c29Anim);
mainFrame.cityView.addAnimation(c29Anim);
CarAgent c31 = new CarAgent(Apartment7, p31);
CarAnimation c31Anim = new CarAnimation(c31, Apartment7);
c31.setAnimation(c31Anim);
mainFrame.cityView.addAnimation(c31Anim);
CarAgent c32 = new CarAgent(Apartment7, p32);
CarAnimation c32Anim = new CarAnimation(c32, Apartment7);
c32.setAnimation(c32Anim);
mainFrame.cityView.addAnimation(c32Anim);
CarAgent c33 = new CarAgent(Apartment7, p33);
CarAnimation c33Anim = new CarAnimation(c33, Apartment7);
c33.setAnimation(c33Anim);
mainFrame.cityView.addAnimation(c33Anim);
CarAgent c34 = new CarAgent(Apartment7, p34);
CarAnimation c34Anim = new CarAnimation(c34, Apartment7);
c34.setAnimation(c34Anim);
mainFrame.cityView.addAnimation(c34Anim);
CarAgent c35 = new CarAgent(Apartment7, p35);
CarAnimation c35Anim = new CarAnimation(c35, Apartment1);
c35.setAnimation(c35Anim);
mainFrame.cityView.addAnimation(c35Anim);
p1.setCar(c1);
p2.setCar(c2);
p3.setCar(c3);
p4.setCar(c4);
p5.setCar(c5);
p6.setCar(c6);
p7.setCar(c7);
p8.setCar(c8);
p9.setCar(c9);
p10.setCar(c10);
p11.setCar(c11);
p12.setCar(c12);
p13.setCar(c13);
p14.setCar(c14);
p15.setCar(c15);
p16.setCar(c16);
p17.setCar(c17);
p18.setCar(c18);
p19.setCar(c19);
p20.setCar(c20);
p21.setCar(c21);
p22.setCar(c22);
p23.setCar(c23);
p24.setCar(c24);
p25.setCar(c25);
p26.setCar(c26);
p27.setCar(c27);
p28.setCar(c28);
p29.setCar(c29);
p31.setCar(c31);
p32.setCar(c32);
p33.setCar(c33);
p34.setCar(c34);
p35.setCar(c35);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
c1.startThread();
c2.startThread();
c3.startThread();
c4.startThread();
c5.startThread();
c6.startThread();
c7.startThread();
c8.startThread();
c9.startThread();
c10.startThread();
c11.startThread();
c12.startThread();
c13.startThread();
c14.startThread();
c15.startThread();
c16.startThread();
c17.startThread();
c18.startThread();
c19.startThread();
c20.startThread();
c21.startThread();
c22.startThread();
c23.startThread();
c24.startThread();
c25.startThread();
c26.startThread();
c27.startThread();
c28.startThread();
c29.startThread();
c31.startThread();
c32.startThread();
c33.startThread();
c34.startThread();
c35.startThread();
p1.startThread();
p2.startThread();
p3.startThread();
p4.startThread();
p5.startThread();
p6.startThread();
p7.startThread();
p8.startThread();
p9.startThread();
p10.startThread();
p11.startThread();
p12.startThread();
p13.startThread();
p14.startThread();
p15.startThread();
p16.startThread();
p17.startThread();
p18.startThread();
p19.startThread();
p20.startThread();
p21.startThread();
p22.startThread();
p23.startThread();
p24.startThread();
p25.startThread();
p26.startThread();
p27.startThread();
p28.startThread();
p29.startThread();
p30.startThread();
p31.startThread();
p32.startThread();
p33.startThread();
p34.startThread();
/*p35.startThread();
p36.startThread();
p37.startThread();
p38.startThread();
p39.startThread();
p40.startThread();
p41.startThread();
p42.startThread();
p43.startThread();
p44.startThread();
p45.startThread();
p46.startThread();
p47.startThread();
p48.startThread();
p49.startThread();
p50.startThread();*/
for(int j = 0; j < 0; j++) {
WalkerAnimation testPersonAnimation = new WalkerAnimation(null, CityMap.findRandomBuilding(BUILDING.busStop), sidewalks);
testPersonAnimation.setVisible(true);
mainFrame.cityView.addAnimation(testPersonAnimation);
testPersonAnimation.goToDestination(CityMap.findRandomBuilding(BUILDING.busStop));
}
}
public static DataModel getModel() {
return model;
}
public static MainFrame getMainFrame() {
return mainFrame;
}
public static Date getDate() {
return new Date(date.getTime());
}
public static void setBuilding(BuildingCard panel, CityViewBuilding cityView, Building building) {
mainFrame.cityView.addStatic(cityView);
mainFrame.buildingView.addView(panel, cityView.getID());
if(building.getClass().getName().contains("Restaurant")) {
CityMap.addBuilding(BUILDING.restaurant, building);
} else if(building.getClass().getName().contains("Bank")) {
CityMap.addBuilding(BUILDING.bank, building);
} else if(building.getClass().getName().contains("Market")) {
CityMap.addBuilding(BUILDING.market, building);
} else if(building.getClass().getName().contains("BusStop")) {
CityMap.addBuilding(BUILDING.busStop, building);
} else if(building.getClass().getName().contains("House")) {
CityMap.addBuilding(BUILDING.house, building);
} else if(building.getClass().getName().contains("Apt")) {
CityMap.addBuilding(BUILDING.apartment, building);
}
}
public static Point findNextOpenLocation() {
for(int i = 25; i < 450; i += 25) {
for(int j = 25; j < 450; j += 25) {
if(i == 25 && (j == 25 || j == 425))
i+= 25;
if(i == 425 && (j == 25 || j == 425))
break;
if(mainFrame.cityView.getBuildingAt(i, j) != null)
continue;
else
return new Point(i, j);
}
}
return null;
}
/*
* Creates a building at the given x and y coordinates. Can and will overlap buildings
*/
public static void runGhostTown(){
}
public static void runVehicleCollision(){
}
public static void runPersonCollision(){
}
public static void runWeekend(){
}
public static void runShiftChange(){
}
public static void addAnim(AnimationInterface anim) {
mainFrame.cityView.addAnimation(anim);
}
public static Point findNextOpenLocation(int x, int y) {
for(int i = x; i < 450; i += 25) {
for(int j = y; j < 450; j += 25) {
if(i <= 25 && (j <= 25 || j >= 425))
i+= 25;
if(i >= 425 && (j <= 25 || j >= 425))
break;
if(mainFrame.cityView.getBuildingAt(i, j) != null)
continue;
else
return new Point(i, j);
}
}
return null;
}
/*
* Creates a building at the next available location
*/
public static BuildingInterface createBuilding(CityViewBuilding.BUILDINGTYPE type) {
Point nextLocation = findNextOpenLocation(0, 0);
if(nextLocation == null)
return null;
return createBuilding(type, (int)(nextLocation.getX()), (int)(nextLocation.getY()));
}
/*
* Creates a building at the given x and y coordinates. Can and will overlap buildings
*/
public static BuildingInterface createBuilding(CityViewBuilding.BUILDINGTYPE type, int potentialX, int potentialY) {
Point nextLocation = findNextOpenLocation(potentialX, potentialY);
if(nextLocation == null)
return null;
int x = nextLocation.x;
int y = nextLocation.y;
CityViewBuilding cityViewBuilding;
Building building;
switch (type) {
case APT:
cityViewBuilding = new CityViewApt(x, y, "Apartment " + (mainFrame.cityView.statics.size()), Color.darkGray, new AptPanel(Color.darkGray));
building = new AptBuilding("Apartment " + mainFrame.cityView.statics.size(), null, (AptPanel)cityViewBuilding.getBuilding(), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case HOUSE:
cityViewBuilding = new CityViewHouse(x, y, "House " + (mainFrame.cityView.statics.size()), Color.pink, new HousePanel(Color.pink));
building = new HouseBuilding("House " + mainFrame.cityView.statics.size(), null, (HousePanel)cityViewBuilding.getBuilding(), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case RESTAURANTZHANG:
cityViewBuilding = new CityViewRestaurantZhang(x, y, "RestaurantZhang " + (mainFrame.cityView.statics.size()), Color.magenta, new RestaurantZhangPanel(Color.magenta));
building = new RestaurantZhangBuilding("RestaurantZhang " + mainFrame.cityView.statics.size(), (RestaurantZhangPanel)cityViewBuilding.getBuilding(), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case RESTAURANTCHOI:
cityViewBuilding = new CityViewRestaurantChoi(x, y, "RestaurantChoi " + mainFrame.cityView.statics.size(), Color.cyan, new RestaurantChoiPanel(Color.cyan));
building = new RestaurantChoiBuilding("RestaurantChoi " + mainFrame.cityView.statics.size(),
(RestaurantChoiPanel)(cityViewBuilding.getBuilding()), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case RESTAURANTJP:
cityViewBuilding = new CityViewRestaurantJP(x, y, "RestaurantJP " + mainFrame.cityView.statics.size(), Color.orange, new RestaurantJPPanel(Color.darkGray));
building = new RestaurantJPBuilding("RestaurantJP " + mainFrame.cityView.statics.size(),
(RestaurantJPPanel)(cityViewBuilding.getBuilding()), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case RESTAURANTTIMMS:
cityViewBuilding = new CityViewRestaurantTimms(x, y, "RestaurantTimms " + mainFrame.cityView.statics.size(), Color.yellow, new RestaurantTimmsPanel(Color.yellow));
building = new RestaurantTimmsBuilding("RestaurantTimms " + mainFrame.cityView.statics.size(),
(RestaurantTimmsPanel)(cityViewBuilding.getBuilding()), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case RESTAURANTCHUNG:
cityViewBuilding = new CityViewRestaurantChung(x, y, "RestaurantChung " + mainFrame.cityView.statics.size(), Color.red, new RestaurantChungPanel(Color.red));
building = new RestaurantChungBuilding("RestaurantChung " + mainFrame.cityView.statics.size(),
(RestaurantChungPanel)(cityViewBuilding.getBuilding()), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case BANK:
cityViewBuilding = new CityViewBank(x, y, "Bank " + mainFrame.cityView.statics.size(), Color.green, new BankPanel(Color.green));
building = new BankBuilding("Bank " + mainFrame.cityView.statics.size(),
(BankPanel)(cityViewBuilding.getBuilding()), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
case MARKET:
cityViewBuilding = new CityViewMarket(x, y, "Market " + mainFrame.cityView.statics.size(), Color.LIGHT_GRAY, new MarketPanel(Color.LIGHT_GRAY));
building = new MarketBuilding("Bank " + mainFrame.cityView.statics.size(),
(MarketPanel)(cityViewBuilding.getBuilding()), cityViewBuilding);
setBuilding(cityViewBuilding.getBuilding(), cityViewBuilding, building);
return building;
default:
return null;
}
}
public static class CityMap {
private static HashMap<BUILDING, List<BuildingInterface>> map = new HashMap<BUILDING, List<BuildingInterface>>();
/**
* Adds a new building to the HashMap
*
* If the map already has a key for the type of building, it adds the new building to that key's
* list. If the key for that type does not exist, it creates the key and gives it a list of
* length one that contains the new building.
*
* @param type the type of building from the BUILDING enumeration
* @param b the building to add
*/
public static BuildingInterface addBuilding(BUILDING type, BuildingInterface b) {
if(map.containsKey(type)) {
map.get(type).add(b);
} else {
List<BuildingInterface> list = new ArrayList<BuildingInterface>();
list.add(b);
map.put(type, list);
}
model.addBuilding(b);
return b;
}
/**
* Returns a random building of type
*/
public static BuildingInterface findRandomBuilding(BUILDING type) {
List<BuildingInterface> list = map.get(type);
if(list == null)
return null;
Collections.shuffle(list);
return list.get(0);
}
/**
* Find the building of type closest to the destination building
*/
public static BuildingInterface findClosestBuilding(BUILDING type, BuildingInterface b) {
int x = b.getCityViewBuilding().getX();
int y = b.getCityViewBuilding().getY();
double closestDistance = 1000000;
BuildingInterface returnBuilding = null;
for(BuildingInterface tempBuilding : map.get(type)) {
double distance = Math.sqrt((double)(Math.pow(tempBuilding.getCityViewBuilding().getX() - x, 2) + Math.pow(tempBuilding.getCityViewBuilding().getY() - y, 2)));
if( distance < closestDistance) {
closestDistance = distance;
returnBuilding = tempBuilding;
}
}
return returnBuilding;
}
/**
* Find the building of type closest to the person's location
*/
public static BuildingInterface findClosestBuilding(BUILDING type, Person p) {
int x = p.getCurrentLocation().getCityViewBuilding().getX();
int y = p.getCurrentLocation().getCityViewBuilding().getY();
double closestDistance = 1000000;
BuildingInterface returnBuilding = null;
for(BuildingInterface b : map.get(type)) {
double distance = Math.sqrt((double)(Math.pow(b.getCityViewBuilding().getX() - x, 2) + Math.pow(b.getCityViewBuilding().getY() - y, 2)));
if( distance < closestDistance) {
closestDistance = distance;
returnBuilding = b;
}
}
return returnBuilding;
}
/**
*
* @param b
* @return
*/
public static CityRoad findClosestRoad(BuildingInterface b) {
int x = b.getCityViewBuilding().getX();
int y = b.getCityViewBuilding().getY();
double closestDistance = 1000000;
CityRoad returnRoad = null;
for(CityRoad r : roads) {
double distance = Math.sqrt((double)(Math.pow(r.getX() - x, 2) + Math.pow(r.getY() - y, 2)));
if( distance < closestDistance) {
closestDistance = distance;
returnRoad = r;
}
}
return returnRoad;
}
/**
* Clears the map of all buildings.
* Convenience function for tests.
*/
public static void clearMap() {
map.clear();
}
/**
* Returns a list of all buildings in the CityMap
*/
public static ArrayList<BuildingInterface> getBuildings() {
ArrayList<BuildingInterface> list = new ArrayList<BuildingInterface>();
for (List<BuildingInterface> l : map.values()) {
list.addAll(l);
}
return list;
}
}
} |
package c5db.log;
import c5db.C5ServerConstants;
import c5db.generated.OLogHeader;
import c5db.replication.QuorumConfiguration;
import c5db.util.KeySerializingExecutor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.CountingInputStream;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static c5db.log.EntryEncodingUtil.decodeAndCheckCrc;
import static c5db.log.EntryEncodingUtil.encodeWithLengthAndCrc;
import static c5db.log.LogPersistenceService.BytePersistence;
import static c5db.log.LogPersistenceService.PersistenceNavigator;
import static c5db.log.LogPersistenceService.PersistenceNavigatorFactory;
import static c5db.log.LogPersistenceService.PersistenceReader;
import static c5db.log.OLogEntryOracle.OLogEntryOracleFactory;
import static c5db.log.OLogEntryOracle.QuorumConfigurationWithSeqNum;
/**
* OLog that delegates each quorum's logging tasks to a separate SequentialLog for that quorum,
* executing the tasks on a KeySerializingExecutor, with quorumId as the key. It is safe for use
* by multiple threads, but each quorum's sequence numbers must be ascending with no gaps within
* that quorum; so having multiple unsynchronized threads writing for the same quorum is unlikely
* to work.
*/
public class QuorumDelegatingLog implements OLog, AutoCloseable {
private final LogPersistenceService<?> persistenceService;
private final KeySerializingExecutor taskExecutor;
private final Map<String, PerQuorum> quorumMap = new ConcurrentHashMap<>();
private final OLogEntryOracleFactory OLogEntryOracleFactory;
private final PersistenceNavigatorFactory persistenceNavigatorFactory;
public QuorumDelegatingLog(LogPersistenceService<?> persistenceService,
KeySerializingExecutor taskExecutor,
OLogEntryOracleFactory OLogEntryOracleFactory,
PersistenceNavigatorFactory persistenceNavigatorFactory
) {
this.persistenceService = persistenceService;
this.taskExecutor = taskExecutor;
this.OLogEntryOracleFactory = OLogEntryOracleFactory;
this.persistenceNavigatorFactory = persistenceNavigatorFactory;
}
private class PerQuorum {
public final SequentialLog<OLogEntry> quorumLog;
public final OLogEntryOracle oLogEntryOracle = OLogEntryOracleFactory.create();
public volatile boolean opened;
private final SequentialEntryCodec<OLogEntry> entryCodec = new OLogEntry.Codec();
private final PersistenceNavigator navigator;
private final OLogHeader header;
private final long headerSize;
private long expectedNextSequenceNumber;
public PerQuorum(String quorumId)
throws IOException {
BytePersistence persistence = persistenceService.getCurrent(quorumId);
if (persistence == null) {
header = new OLogHeader(0, 0, QuorumConfiguration.EMPTY.toProtostuff());
headerSize = addNewPersistenceWithHeader(quorumId, header, persistenceService);
} else {
CountingInputStream input = getCountingInputStream(persistence.getReader());
header = decodeAndCheckCrc(input, OLogHeader.getSchema());
headerSize = input.getCount();
}
navigator = persistenceNavigatorFactory.create(persistence, entryCodec, headerSize);
quorumLog = new EncodedSequentialLog<>(persistence, entryCodec, navigator);
prepareInMemoryObjects();
opened = true;
}
public void validateConsecutiveEntries(List<OLogEntry> entries) {
for (OLogEntry e : entries) {
long seqNum = e.getSeqNum();
if (seqNum != expectedNextSequenceNumber) {
throw new IllegalArgumentException("Unexpected sequence number in entries requested to be logged");
}
expectedNextSequenceNumber++;
}
}
public void setExpectedNextSequenceNumber(long seqNum) {
this.expectedNextSequenceNumber = seqNum;
}
private CountingInputStream getCountingInputStream(PersistenceReader reader) throws IOException {
return new CountingInputStream(Channels.newInputStream(reader));
}
private void prepareInMemoryObjects() throws IOException {
setExpectedNextSequenceNumber(header.getBaseSeqNum() + 1);
navigator.addToIndex(header.getBaseSeqNum() + 1, headerSize);
quorumLog.forEach((entry) -> {
oLogEntryOracle.notifyLogging(entry);
setExpectedNextSequenceNumber(entry.getSeqNum() + 1);
});
}
}
@Override
public ListenableFuture<Void> openAsync(String quorumId) {
return taskExecutor.submit(quorumId, () -> {
createAndPrepareQuorumStructures(quorumId);
return null;
});
}
@Override
public ListenableFuture<Boolean> logEntry(List<OLogEntry> passedInEntries, String quorumId) {
List<OLogEntry> entries = validateAndMakeDefensiveCopy(passedInEntries);
getQuorumStructure(quorumId).validateConsecutiveEntries(entries);
updateOracleWithNewEntries(entries, quorumId);
// TODO group commit / sync
return taskExecutor.submit(quorumId, () -> {
quorumLog(quorumId).append(entries);
return true;
});
}
@Override
public ListenableFuture<List<OLogEntry>> getLogEntries(long start, long end, String quorumId) {
if (end < start) {
throw new IllegalArgumentException("getLogEntries: end < start");
} else if (end == start) {
return Futures.immediateFuture(new ArrayList<>());
}
return taskExecutor.submit(quorumId, () -> quorumLog(quorumId).subSequence(start, end));
}
@Override
public ListenableFuture<Boolean> truncateLog(long seqNum, String quorumId) {
getQuorumStructure(quorumId).setExpectedNextSequenceNumber(seqNum);
oLogEntryOracle(quorumId).notifyTruncation(seqNum);
return taskExecutor.submit(quorumId, () -> {
quorumLog(quorumId).truncate(seqNum);
return true;
});
}
@Override
public long getNextSeqNum(String quorumId) {
return getQuorumStructure(quorumId).expectedNextSequenceNumber;
}
@Override
public long getLastTerm(String quorumId) {
return oLogEntryOracle(quorumId).getLastTerm();
}
@Override
public long getLogTerm(long seqNum, String quorumId) {
return oLogEntryOracle(quorumId).getTermAtSeqNum(seqNum);
}
@Override
public QuorumConfigurationWithSeqNum getLastQuorumConfig(String quorumId) {
return oLogEntryOracle(quorumId).getLastQuorumConfig();
}
@Override
public ListenableFuture<Void> roll(String quorumId) throws IOException {
return null;
}
@Override
public void close() throws IOException {
try {
taskExecutor.shutdownAndAwaitTermination(C5ServerConstants.WAL_CLOSE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
}
for (PerQuorum quorum : quorumMap.values()) {
quorum.quorumLog.close();
}
}
private List<OLogEntry> validateAndMakeDefensiveCopy(List<OLogEntry> entries) {
if (entries.isEmpty()) {
throw new IllegalArgumentException("Attempting to log an empty entry list");
}
return ImmutableList.copyOf(entries);
}
private SequentialLog<OLogEntry> quorumLog(String quorumId) {
return getQuorumStructure(quorumId).quorumLog;
}
private OLogEntryOracle oLogEntryOracle(String quorumId) {
return getQuorumStructure(quorumId).oLogEntryOracle;
}
private PerQuorum getQuorumStructure(String quorumId) {
PerQuorum perQuorum = quorumMap.get(quorumId);
if (perQuorum == null || !perQuorum.opened) {
quorumNotOpen(quorumId);
}
return perQuorum;
}
private void createAndPrepareQuorumStructures(String quorumId) {
quorumMap.computeIfAbsent(quorumId, q -> {
try {
return new PerQuorum(quorumId);
} catch (IOException e) {
// Translate exception because computeIfAbsent 's Function declares no checked exception
throw new RuntimeException(e);
}
});
}
/**
* Create and save a new persistence, with the given header, for the given quorum.
*
* @param quorumId Quorum ID
* @param header OLogHeader to be written to the beginning of the new persistence
* @param persistenceService The LogPersistenceService, included as a parameter here in order to
* capture a wildcard
* @param <P> Captured wildcard; the type of the BytePersistence to create and write
* @return The length of the written header
* @throws IOException
*/
private <P extends BytePersistence> long addNewPersistenceWithHeader(String quorumId,
OLogHeader header,
LogPersistenceService<P> persistenceService)
throws IOException {
P persistence = persistenceService.create(quorumId);
List<ByteBuffer> buffers = encodeWithLengthAndCrc(OLogHeader.getSchema(), header);
persistence.append(Iterables.toArray(buffers, ByteBuffer.class));
persistenceService.append(quorumId, persistence);
return persistence.size();
}
private void updateOracleWithNewEntries(List<OLogEntry> entries, String quorumId) {
OLogEntryOracle oLogEntryOracle = oLogEntryOracle(quorumId);
for (OLogEntry e : entries) {
oLogEntryOracle.notifyLogging(e);
}
}
private void quorumNotOpen(String quorumId) {
throw new QuorumNotOpen("QuorumDelegatingLog#getQuorumStructure: quorum " + quorumId + " not open");
}
} |
package org.bedework.calsvc;
import org.bedework.calenv.CalEnv;
import org.bedework.calfacade.CalFacadeUtil.GetPeriodsPars;
import org.bedework.calfacade.base.BwOwnedDbentity;
import org.bedework.calfacade.base.BwShareableDbentity;
import org.bedework.calfacade.BwAlarm;
import org.bedework.calfacade.BwCalendar;
import org.bedework.calfacade.BwCategory;
import org.bedework.calfacade.BwDateTime;
import org.bedework.calfacade.BwDuration;
import org.bedework.calfacade.BwEvent;
import org.bedework.calfacade.BwEventAlarm;
import org.bedework.calfacade.BwEventAnnotation;
import org.bedework.calfacade.BwEventProxy;
import org.bedework.calfacade.BwFreeBusy;
import org.bedework.calfacade.BwFreeBusyComponent;
import org.bedework.calfacade.BwLocation;
import org.bedework.calfacade.BwPrincipal;
import org.bedework.calfacade.BwSponsor;
import org.bedework.calfacade.BwStats;
import org.bedework.calfacade.BwSynchInfo;
import org.bedework.calfacade.BwSynchState;
import org.bedework.calfacade.BwSystem;
import org.bedework.calfacade.BwUser;
import org.bedework.calfacade.CalFacadeAccessException;
import org.bedework.calfacade.CalFacadeDefs;
import org.bedework.calfacade.CalFacadeException;
import org.bedework.calfacade.CalFacadeUtil;
import org.bedework.calfacade.CoreEventInfo;
import org.bedework.calfacade.filter.BwFilter;
import org.bedework.calfacade.ifs.CalTimezones;
import org.bedework.calfacade.ifs.Calintf;
import org.bedework.calfacade.ifs.Groups;
import org.bedework.calfacade.svc.BwAuthUser;
import org.bedework.calfacade.svc.BwPreferences;
import org.bedework.calfacade.svc.BwSubscription;
import org.bedework.calfacade.svc.BwView;
import org.bedework.calfacade.svc.EventInfo;
import org.bedework.calfacade.svc.UserAuth;
import org.bedework.calsvci.CalSvcI;
import org.bedework.calsvci.CalSvcIPars;
import org.bedework.icalendar.IcalCallback;
import org.bedework.icalendar.TimeZoneRegistryImpl;
import org.bedework.icalendar.URIgen;
//import org.bedework.mail.MailerIntf;
import edu.rpi.cct.misc.indexing.Index;
import edu.rpi.cct.uwcal.access.PrivilegeDefs;
import edu.rpi.cct.uwcal.access.Acl.CurrentAccess;
import edu.rpi.cct.uwcal.resources.Resources;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.model.property.Created;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.LastModified;
import org.apache.log4j.Logger;
/** This is an implementation of the service level interface to the calendar
* suite.
*
* @author Mike Douglass douglm@rpi.edu
*/
public class CalSvc extends CalSvcI {
private CalSvcIPars pars;
private Index indexer;
private boolean debug;
private boolean open;
private boolean superUser;
//private BwFilter currentFilter;
/* The account that owns public entities
*/
private BwUser publicUser;
// Set up by call to getCal()
private String publicUserAccount;
private BwView currentView;
private Collection currentSubscriptions;
/** Used to see if applications need to force a refresh
*/
private long publicLastmod;
/** Core calendar interface
*/
private transient Calintf cali;
/** Db interface for our own data structures.
*/
private CalSvcDb dbi;
/** handles timezone info.
*/
private CalTimezones timezones;
/** The user authorisation object
*/
private UserAuth userAuth;
private transient UserAuth.CallBack uacb;
private transient Groups.CallBack gcb;
/* If we're doing admin this is the authorised user entry
*/
BwAuthUser adminUser;
/** Class used by UseAuth to do calls into CalSvci
*
*/
public static class UserAuthCallBack extends UserAuth.CallBack {
CalSvc svci;
UserAuthCallBack(CalSvc svci) {
this.svci = svci;
}
public BwUser getUser(String account) throws CalFacadeException {
return svci.getCal().getUser(account);
}
public BwUser getUser(int id) throws CalFacadeException {
return svci.getCal().getUser(id);
}
public void addUser(BwUser user) throws CalFacadeException {
svci.addUser(user);
}
public UserAuth getUserAuth() throws CalFacadeException {
return svci.getUserAuth();
}
/* (non-Javadoc)
* @see org.bedework.calfacade.svc.UserAuth.CallBack#getDbSession()
*/
public Object getDbSession() throws CalFacadeException {
return svci.getCal().getDbSession();
}
}
/** Class used by groups implementations for calls into CalSvci
*
*/
public static class GroupsCallBack extends Groups.CallBack {
CalSvc svci;
GroupsCallBack(CalSvc svci) {
this.svci = svci;
}
public BwUser getUser(String account) throws CalFacadeException {
return svci.getCal().getUser(account);
}
public BwUser getUser(int id) throws CalFacadeException {
return svci.getCal().getUser(id);
}
/* (non-Javadoc)
* @see org.bedework.calfacade.svc.UserAuth.CallBack#getDbSession()
*/
public Object getDbSession() throws CalFacadeException {
return svci.getCal().getDbSession();
}
}
/** The user groups object.
*/
private Groups userGroups;
/** The admin groups object.
*/
private Groups adminGroups;
/* The mailer object.
*/
//private MailerIntf mailer;
private IcalCallback icalcb;
/* These are only relevant for the public admin client.
*/
//private boolean adminAutoDeleteSponsors;
//private boolean adminAutoDeleteLocations;
private boolean adminCanEditAllPublicCategories;
private boolean adminCanEditAllPublicLocations;
private boolean adminCanEditAllPublicSponsors;
private transient Logger log;
private CalEnv env;
private Resources res = new Resources();
/* (non-Javadoc)
* @see org.bedework.calsvci.CalSvcI#init(org.bedework.calsvci.CalSvcIPars)
*/
public void init(CalSvcIPars parsParam) throws CalFacadeException {
pars = (CalSvcIPars)parsParam.clone();
debug = pars.getDebug();
//if (userAuth != null) {
// userAuth.reinitialise(getUserAuthCallBack());
if (userGroups != null) {
userGroups.init(getGroupsCallBack());
}
if (adminGroups != null) {
adminGroups.init(getGroupsCallBack());
}
try {
env = new CalEnv(pars.getEnvPrefix(), debug);
if (pars.isGuest() && (pars.getUser() == null)) {
pars.setUser(env.getAppProperty("run.as.user"));
}
if (pars.getPublicAdmin()) {
//adminAutoDeleteSponsors = env.getAppBoolProperty("app.autodeletesponsors");
//adminAutoDeleteLocations = env.getAppBoolProperty("app.autodeletelocations");
adminCanEditAllPublicCategories = env.getAppBoolProperty("allowEditAllCategories");
adminCanEditAllPublicLocations = env.getAppBoolProperty("allowEditAllLocations");
adminCanEditAllPublicSponsors = env.getAppBoolProperty("allowEditAllSponsors");
}
timezones = getCal().getTimezones();
/* Nominate our timezone registry */
System.setProperty("net.fortuna.ical4j.timezone.registry",
"org.bedework.icalendar.TimeZoneRegistryFactoryImpl");
} catch (CalFacadeException cfe) {
throw cfe;
} catch (Throwable t) {
throw new CalFacadeException(t);
}
}
public void setSuperUser(boolean val) {
superUser = val;
}
public boolean getSuperUser() {
return superUser;
}
public BwStats getStats() throws CalFacadeException {
//if (!pars.getPublicAdmin()) {
// throw new CalFacadeAccessException();
return getCal().getStats();
}
public void setDbStatsEnabled(boolean enable) throws CalFacadeException {
//if (!pars.getPublicAdmin()) {
// throw new CalFacadeAccessException();
getCal().setDbStatsEnabled(enable);
}
public boolean getDbStatsEnabled() throws CalFacadeException {
return getCal().getDbStatsEnabled();
}
public void dumpDbStats() throws CalFacadeException {
//if (!pars.getPublicAdmin()) {
// throw new CalFacadeAccessException();
trace(getStats().toString());
getCal().dumpDbStats();
}
public Collection getDbStats() throws CalFacadeException {
//if (!pars.getPublicAdmin()) {
// throw new CalFacadeAccessException();
return getCal().getDbStats();
}
public BwSystem getSyspars() throws CalFacadeException {
return getCal().getSyspars();
}
public void updateSyspars(BwSystem val) throws CalFacadeException {
if (!isSuper()) {
throw new CalFacadeAccessException();
}
getCal().updateSyspars(val);
}
public CalTimezones getTimezones() throws CalFacadeException {
return getCal().getTimezones();
}
public void logStats() throws CalFacadeException {
logIt(getStats().toString());
}
public void setUser(String val) throws CalFacadeException {
getCal().setUser(val);
}
public BwUser findUser(String val) throws CalFacadeException {
return getCal().getUser(val);
}
public void addUser(BwUser user) throws CalFacadeException {
getCal().addUser(user);
initUser(getCal().getUser(user.getAccount()), getCal());
}
public void flushAll() throws CalFacadeException {
getCal().flushAll();
}
public void open() throws CalFacadeException {
open = true;
TimeZoneRegistryImpl.setThreadCb(getIcalCallback());
getCal().open();
dbi.open();
}
public boolean isOpen() {
return open;
}
public void close() throws CalFacadeException {
open = false;
getCal().close();
dbi.close();
}
public void beginTransaction() throws CalFacadeException {
getCal().beginTransaction();
}
public void endTransaction() throws CalFacadeException {
getCal().endTransaction();
}
public void rollbackTransaction() throws CalFacadeException {
getCal().rollbackTransaction();
}
public IcalCallback getIcalCallback() {
if (icalcb == null) {
icalcb = new IcalCallbackcb();
}
return icalcb;
}
public String getEnvProperty(String name) throws CalFacadeException {
try {
return CalEnv.getProperty(name);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
}
public Resources getResources() {
return res;
}
public String getSysid() throws CalFacadeException {
return getCal().getSysid();
}
public BwUser getUser() throws CalFacadeException {
if (pars.isGuest()) {
return getPublicUser();
}
return getCal().getUser();
}
public Collection getInstanceOwners() throws CalFacadeException {
return getCal().getInstanceOwners();
}
private BwUser getPublicUser() throws CalFacadeException {
if (publicUser == null) {
publicUser = getCal().getUser(publicUserAccount);
}
if (publicUser == null) {
throw new CalFacadeException("No guest user proxy account - expected " + publicUserAccount);
}
return publicUser;
}
public UserAuth getUserAuth(String user, Object par) throws CalFacadeException {
if (userAuth != null) {
//userAuth.reinitialise(getUserAuthCallBack());
return userAuth;
}
try {
userAuth = (UserAuth)CalFacadeUtil.getObject(getSyspars().getUserauthClass(),
UserAuth.class);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
userAuth.initialise(user, getUserAuthCallBack(), par, debug);
return userAuth;
}
public UserAuth getUserAuth() throws CalFacadeException {
if (userAuth != null) {
//userAuth.reinitialise(getUserAuthCallBack());
return userAuth;
}
return getUserAuth(pars.getAuthUser(), null);
}
public Groups getGroups() throws CalFacadeException {
if (isPublicAdmin()) {
return getAdminGroups();
}
return getUserGroups();
}
public Groups getUserGroups() throws CalFacadeException {
if (userGroups != null) {
return userGroups;
}
try {
userGroups = (Groups)CalFacadeUtil.getObject(getSyspars().getUsergroupsClass(), Groups.class);
userGroups.init(getGroupsCallBack());
} catch (Throwable t) {
throw new CalFacadeException(t);
}
return userGroups;
}
public Groups getAdminGroups() throws CalFacadeException {
if (adminGroups != null) {
return adminGroups;
}
try {
adminGroups = (Groups)CalFacadeUtil.getObject(getSyspars().getAdmingroupsClass(), Groups.class);
adminGroups.init(getGroupsCallBack());
} catch (Throwable t) {
throw new CalFacadeException(t);
}
return adminGroups;
}
public void refreshEvents() throws CalFacadeException {
getCal().refreshEvents();
}
public boolean refreshNeeded() throws CalFacadeException {
/* See if the events were updated */
long lastmod;
lastmod = getCal().getPublicLastmod();
if (lastmod == publicLastmod) {
return false;
}
publicLastmod = lastmod;
return true;
}
public BwPreferences getUserPrefs() throws CalFacadeException {
return dbi.getPreferences();
}
public BwPreferences getUserPrefs(BwUser user) throws CalFacadeException {
return dbi.fetchPreferences(user);
}
public void updateUserPrefs(BwPreferences val) throws CalFacadeException {
dbi.updatePreferences(val);
}
public void changeAccess(BwShareableDbentity ent,
Collection aces) throws CalFacadeException {
getCal().changeAccess(ent, aces);
}
public void saveTimeZone(String tzid, VTimeZone vtz)
throws CalFacadeException {
// Not sure we want this. public admins may want to add timezones
if (isPublicAdmin() && !isSuper()) {
throw new CalFacadeAccessException();
}
timezones.saveTimeZone(tzid, vtz);
}
public void registerTimeZone(String id, TimeZone timezone)
throws CalFacadeException {
timezones.registerTimeZone(id, timezone);
}
public TimeZone getTimeZone(final String id) throws CalFacadeException {
return timezones.getTimeZone(id);
}
public VTimeZone findTimeZone(final String id, BwUser owner) throws CalFacadeException {
return timezones.findTimeZone(id, owner);
}
public void clearPublicTimezones() throws CalFacadeException {
if (isPublicAdmin() && !isSuper()) {
throw new CalFacadeAccessException();
}
timezones.clearPublicTimezones();
}
public void refreshTimezones() throws CalFacadeException {
timezones.refreshTimezones();
}
public BwCalendar getPublicCalendars() throws CalFacadeException {
return getCal().getPublicCalendars();
}
public Collection getPublicCalendarCollections() throws CalFacadeException {
return getCal().getPublicCalendarCollections();
}
public boolean getCalendarInuse(BwCalendar val) throws CalFacadeException {
return getCal().checkCalendarRefs(val);
}
public BwCalendar getCalendars() throws CalFacadeException {
if (pars.isGuest() || isPublicAdmin()) {
return getCal().getPublicCalendars();
}
return getCal().getCalendars();
}
public Collection getCalendarCollections() throws CalFacadeException {
return getCal().getCalendarCollections();
}
public Collection getAddContentCalendarCollections()
throws CalFacadeException {
if (isPublicAdmin()) {
return getCal().getAddContentPublicCalendarCollections();
}
return getCal().getAddContentCalendarCollections();
}
public BwCalendar getCalendar(int val) throws CalFacadeException {
return getCal().getCalendar(val);
}
public BwCalendar getCalendar(String path) throws CalFacadeException{
if (path == null) {
return null;
}
if ((path.length() > 1) &&
(path.startsWith(CalFacadeDefs.bwUriPrefix))) {
path = path.substring(CalFacadeDefs.bwUriPrefix.length());
}
if ((path.length() > 1) && path.endsWith("/")) {
return getCal().getCalendar(path.substring(0, path.length() - 1));
}
return getCal().getCalendar(path);
}
/** set the default calendar for the current user.
*
* @param val BwCalendar
* @throws CalFacadeException
*/
public void setPreferredCalendar(BwCalendar val) throws CalFacadeException {
getPreferences().setDefaultCalendar(val);
}
public BwCalendar getPreferredCalendar() throws CalFacadeException {
return getPreferences().getDefaultCalendar();
}
public void addCalendar(BwCalendar val, BwCalendar parent) throws CalFacadeException {
updateOK(val);
setupSharableEntity(val);
getCal().addCalendar(val, parent);
}
public void updateCalendar(BwCalendar val) throws CalFacadeException {
// Ensure it's not in prefs if it's a folder
if (!val.getCalendarCollection()) {
if (pars.getPublicAdmin()) {
/* Remove from preferences */
getUserAuth().removeCalendar(null, val);
}
}
getCal().updateCalendar(val);
}
public int deleteCalendar(BwCalendar val) throws CalFacadeException {
/** Only allow delete if not in use
*/
if (getCal().checkCalendarRefs(val)) {
return 2;
}
if (pars.getPublicAdmin()) {
/* Remove from preferences */
getUserAuth().removeCalendar(null, val);
}
/* Attempt to delete
*/
if (getCal().deleteCalendar(val)) {
return 0;
}
return 1; //doesn't exist
}
public boolean addView(BwView val,
boolean makeDefault) throws CalFacadeException {
if (val == null) {
return false;
}
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
setupOwnedEntity(val);
if (prefs.getViews().contains(val)) {
return false;
}
prefs.addView(val);
if (makeDefault) {
prefs.setPreferredView(val.getName());
}
dbi.updatePreferences(prefs);
return true;
}
public boolean removeView(BwView val) throws CalFacadeException{
if (val == null) {
return false;
}
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
Collection views = prefs.getViews();
setupOwnedEntity(val);
if (!views.contains(val)) {
return false;
}
String name = val.getName();
views.remove(val);
if (name.equals(prefs.getPreferredView())) {
prefs.setPreferredView(null);
}
dbi.updatePreferences(prefs);
return true;
}
public BwView findView(String val) throws CalFacadeException {
if (val == null) {
BwPreferences prefs = getPreferences();
val = prefs.getPreferredView();
if (val == null) {
return null;
}
}
Collection views = getViews();
Iterator it = views.iterator();
while (it.hasNext()) {
BwView view = (BwView)it.next();
if (view.getName().equals(val)) {
return view;
}
}
return null;
}
public boolean addViewSubscription(String name,
BwSubscription sub) throws CalFacadeException {
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
BwView view = findView(name);
if (view == null) {
return false;
}
view.addSubscription(sub);
dbi.updatePreferences(prefs);
return true;
}
public boolean removeViewSubscription(String name,
BwSubscription sub) throws CalFacadeException {
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
BwView view = findView(name);
if (view == null) {
return false;
}
view.removeSubscription(sub);
dbi.updatePreferences(prefs);
return true;
}
public Collection getViews() throws CalFacadeException {
return getPreferences().getViews();
}
public boolean setCurrentView(String val) throws CalFacadeException {
if (val == null) {
currentView = null;
return true;
}
Iterator it = getPreferences().iterateViews();
while (it.hasNext()) {
BwView view = (BwView)it.next();
if (val.equals(view.getName())) {
currentView = view;
currentSubscriptions = null;
if (debug) {
trace("view has " + view.getSubscriptions().size() + " subscriptions");
trace("set view to " + view);
}
return true;
}
}
return false;
}
public BwView getCurrentView() throws CalFacadeException {
return currentView;
}
public void setCurrentSubscriptions(Collection val) throws CalFacadeException {
currentSubscriptions = val;
if (val != null) {
currentView = null;
}
}
public Collection getCurrentSubscriptions() throws CalFacadeException {
return currentSubscriptions;
}
public void setSearch(String val) throws CalFacadeException {
getCal().setSearch(val);
}
public String getSearch() throws CalFacadeException {
return getCal().getSearch();
}
public void addFilter(BwFilter val) throws CalFacadeException {
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
getCal().addFilter(val);
}
public void updateFilter(BwFilter val) throws CalFacadeException {
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
getCal().updateFilter(val);
}
/*
public void setFilter(BwFilter val) throws CalFacadeException {
currentFilter = val;
}
public BwFilter getFilter() throws CalFacadeException {
return currentFilter;
}
public void resetFilters() throws CalFacadeException {
currentFilter = null;
}
*/
public void addSubscription(BwSubscription val) throws CalFacadeException {
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
// XXX clone? val = (BwSubscription)val.clone(); // Avoid hibernate
setupOwnedEntity(val);
trace("************* add subscription " + val);
prefs.addSubscription(val);
}
public BwSubscription findSubscription(String name) throws CalFacadeException {
if (name == null) {
return null;
}
Collection subs = getSubscriptions();
Iterator it = subs.iterator();
while (it.hasNext()) {
BwSubscription sub = (BwSubscription)it.next();
if (sub.getName().equals(name)) {
return sub;
}
}
return null;
}
public void removeSubscription(BwSubscription val) throws CalFacadeException {
BwPreferences prefs = getPreferences();
checkOwnerOrSuper(prefs);
prefs.getSubscriptions().remove(val);
//dbi.updatePreferences(prefs);
}
public void updateSubscription(BwSubscription val) throws CalFacadeException {
BwPreferences prefs = getPreferences();
BwSubscription sub = findSubscription(val.getName());
if (sub == null) {
throw new CalFacadeException("Unknown subscription" + val.getName());
}
if ((sub.getUnremoveable() != val.getUnremoveable()) &&
!this.isSuper()) {
throw new CalFacadeAccessException();
}
val.copyTo(sub);
dbi.updatePreferences(prefs);
}
public boolean getSubscribed(BwCalendar val) throws CalFacadeException {
BwSubscription sub = BwSubscription.makeSubscription(val, null, false, false, false);
setupOwnedEntity(sub);
return getPreferences().getSubscriptions().contains(sub);
}
public Collection getSubscriptions() throws CalFacadeException {
return getPreferences().getSubscriptions();
}
public BwSubscription getSubscription(int id) throws CalFacadeException {
return dbi.getSubscription(id);
}
public BwFreeBusy getFreeBusy(BwCalendar cal, BwPrincipal who,
BwDateTime start, BwDateTime end,
BwDuration granularity,
boolean returnAll)
throws CalFacadeException {
if (!(who instanceof BwUser)) {
throw new CalFacadeException("Unsupported: non user principal for free-busy");
}
BwUser u = (BwUser)who;
Collection subs;
if (cal != null) {
getCal().checkAccess(cal, PrivilegeDefs.privReadFreeBusy, false);
BwSubscription sub = BwSubscription.makeSubscription(cal);
subs = new ArrayList();
subs.add(sub);
} else if (currentUser().equals(who)) {
subs = getSubscriptions();
} else {
getCal().checkAccess(getCal().getCalendars(u),
PrivilegeDefs.privReadFreeBusy, false);
subs = dbi.fetchPreferences(u).getSubscriptions();
}
BwFreeBusy fb = new BwFreeBusy(who, start, end);
Collection events = new TreeSet();
Iterator subit = subs.iterator();
while (subit.hasNext()) {
BwSubscription sub = (BwSubscription)subit.next();
if (!sub.getAffectsFreeBusy()) {
continue;
}
Collection evs = getEvents(sub, null, start, end,
CalFacadeDefs.retrieveRecurExpanded);
// Filter out transparent events
Iterator it = evs.iterator();
while (it.hasNext()) {
EventInfo ei = (EventInfo)it.next();
BwEvent ev = ei.getEvent();
// XXX Need to add sub.ignoreTransparency
if (BwEvent.transparencyTransparent.equals(ev.getTransparency())) {
continue;
}
events.add(ei);
}
}
try {
if (granularity != null) {
// chunked.
GetPeriodsPars gpp = new GetPeriodsPars();
gpp.events = events;
gpp.startDt = start;
gpp.dur = granularity;
gpp.tzcache = getTimezones();
BwFreeBusyComponent fbc = null;
if (!returnAll) {
// One component
fbc = new BwFreeBusyComponent();
fb.addTime(fbc);
}
int limit = 10000; // XXX do this better
while (gpp.startDt.before(end)) {
//if (debug) {
// trace("gpp.startDt=" + gpp.startDt + " end=" + end);
if (limit < 0) {
throw new CalFacadeException("org.bedework.svci.limit.exceeded");
}
limit
Collection periodEvents = CalFacadeUtil.getPeriodsEvents(gpp);
if (returnAll) {
fbc = new BwFreeBusyComponent();
fb.addTime(fbc);
DateTime psdt = new DateTime(gpp.startDt.getDtval());
DateTime pedt = new DateTime(gpp.endDt.getDtval());
psdt.setUtc(true);
pedt.setUtc(true);
fbc.addPeriod(new Period(psdt, pedt));
if (periodEvents.size() == 0) {
fbc.setType(BwFreeBusyComponent.typeFree);
}
} else if (periodEvents.size() != 0) {
// Some events fall in the period. Add an entry.
DateTime psdt = new DateTime(gpp.startDt.getDtval());
DateTime pedt = new DateTime(gpp.endDt.getDtval());
psdt.setUtc(true);
pedt.setUtc(true);
fbc.addPeriod(new Period(psdt, pedt));
}
}
return fb;
}
/* For the moment just build a single BwFreeBusyComponent
*/
BwFreeBusyComponent fbc = new BwFreeBusyComponent();
Iterator it = events.iterator();
TreeSet eventPeriods = new TreeSet();
while (it.hasNext()) {
EventInfo ei = (EventInfo)it.next();
BwEvent ev = ei.getEvent();
// Ignore if times were specified and this event is outside the times
BwDateTime estart = ev.getDtstart();
BwDateTime eend = ev.getDtend();
/* Don't report out of the requested period */
String dstart;
String dend;
if (estart.before(start)) {
dstart = start.getDtval();
} else {
dstart = estart.getDtval();
}
if (eend.after(end)) {
dend = end.getDtval();
} else {
dend = eend.getDtval();
}
eventPeriods.add(new EventPeriod(new DateTime(dstart),
new DateTime(dend)));
}
/* iterate through the sorted periods combining them where they are
adjacent or overlap */
Period p = null;
it = eventPeriods.iterator();
while (it.hasNext()) {
EventPeriod ep = (EventPeriod)it.next();
if (p == null) {
p = new Period(ep.start, ep.end);
} else if (ep.start.after(p.getEnd())) {
// Non adjacent periods
fbc.addPeriod(p);
p = new Period(ep.start, ep.end);
} else if (ep.end.after(p.getEnd())) {
// Extend the current period
p = new Period(p.getStart(), ep.end);
} // else it falls within the existing period
}
if (p != null) {
fbc.addPeriod(p);
}
fb.addTime(fbc);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
return fb;
}
private static class EventPeriod implements Comparable {
DateTime start;
DateTime end;
EventPeriod(DateTime start, DateTime end) {
this.start = start;
this.end = end;
}
public int compareTo(Object o) {
if (!(o instanceof EventPeriod)) {
return -1;
}
EventPeriod that = (EventPeriod)o;
int res = start.compareTo(that.start);
if (res != 0) {
return res;
}
return end.compareTo(that.end);
}
}
public Collection getCategories() throws CalFacadeException {
return getCal().getCategories(getUser(), null);
}
public Collection getPublicCategories() throws CalFacadeException {
return getCal().getCategories(getPublicUser(), null);
}
public Collection getEditableCategories() throws CalFacadeException {
if (!isPublicAdmin()) {
return getCal().getCategories(getUser(), null);
}
if (isSuper() || adminCanEditAllPublicCategories) {
return getCal().getCategories(getPublicUser(), null);
}
return getCal().getCategories(getPublicUser(), getUser());
}
public BwCategory getCategory(int id) throws CalFacadeException {
return getCal().getCategory(id);
}
public void addCategory(BwCategory val) throws CalFacadeException {
getCal().addCategory(val);
}
public void replaceCategory(BwCategory val) throws CalFacadeException {
getCal().updateCategory(val);
}
public int deleteCategory(BwCategory val) throws CalFacadeException {
/** Only allow delete if not in use
*/
if (getCal().getCategoryRefs(val).size() > 0) {
return 2;
}
/* Remove from preferences */
getUserAuth().removeCategory(null, val);
/* Attempt to delete
*/
if (getCal().deleteCategory(val)) {
return 0;
}
return 1; //doesn't exist
}
public BwCategory findCategory(BwCategory cat) throws CalFacadeException {
setupSharableEntity(cat);
return getCal().findCategory(cat);
}
public boolean ensureCategoryExists(BwCategory category) throws CalFacadeException {
if (category.getId() != 0) {
// We've already checked it exists
return false;
}
category.setPublick(pars.getPublicAdmin());
category.setCreator(getUser());
// Assume a new category - but see if we can find it.
BwCategory k = findCategory(category);
if (k != null) {
category.setId(k.getId());
return false;
}
// doesn't exist at this point, so we add it to db table
getCal().addCategory(category);
return true;
}
public Collection getLocations() throws CalFacadeException {
return getCal().getLocations(getUser(), null);
}
public Collection getPublicLocations() throws CalFacadeException {
return getCal().getLocations(getPublicUser(), null);
}
public Collection getEditableLocations() throws CalFacadeException {
if (!isPublicAdmin()) {
return getCal().getLocations(getUser(), null);
}
if (isSuper() || adminCanEditAllPublicLocations) {
return getCal().getLocations(getPublicUser(), null);
}
return getCal().getLocations(getPublicUser(), getUser());
}
/** Add a location to the database. The id will be set in the parameter
* object.
*
* @param val LocationVO object to be added
* @return boolean true for added, false for already exists
* @throws CalFacadeException
*/
public boolean addLocation(BwLocation val) throws CalFacadeException {
setupSharableEntity(val);
updateOK(val);
if (findLocation(val) != null) {
return false;
}
if (debug) {
trace("Add location " + val);
}
getCal().addLocation(val);
return true;
}
public void replaceLocation(BwLocation val) throws CalFacadeException {
getCal().updateLocation(val);
}
public BwLocation getLocation(int id) throws CalFacadeException {
return getCal().getLocation(id);
}
public BwLocation findLocation(BwLocation val) throws CalFacadeException {
setupSharableEntity(val);
return getCal().findLocation(val);
}
public int deleteLocation(BwLocation val) throws CalFacadeException {
deleteOK(val);
if (val.getId() <= CalFacadeDefs.maxReservedLocationId) {
// claim it doesn't exist
return 1;
}
/** Only allow delete if not in use
*/
if (getCal().getLocationRefs(val).size() != 0) {
return 2;
}
if (pars.getPublicAdmin()) {
/* Remove from preferences */
getUserAuth().removeLocation(null, val);
}
/* Attempt to delete
*/
if (getCal().deleteLocation(val)) {
return 0;
}
return 1; //doesn't exist
}
public BwLocation ensureLocationExists(BwLocation val)
throws CalFacadeException {
if (val.getId() > 0) {
// We've already checked it exists
return val;
}
// Assume a new entity
setupSharableEntity(val);
BwLocation l = findLocation(val);
if (l != null) {
return l;
}
// doesn't exist at this point, so we add it to db table
addLocation(val);
return null;
}
public Collection getLocationRefs(BwLocation val) throws CalFacadeException {
return getCal().getLocationRefs(val);
}
public Collection getSponsors() throws CalFacadeException {
return getCal().getSponsors(getUser(), null);
}
public Collection getPublicSponsors() throws CalFacadeException {
return getCal().getSponsors(getPublicUser(), null);
}
public Collection getEditableSponsors() throws CalFacadeException {
if (!isPublicAdmin()) {
return getCal().getSponsors(getUser(), null);
}
if (isSuper() || adminCanEditAllPublicSponsors) {
return getCal().getSponsors(getPublicUser(), null);
}
return getCal().getSponsors(getPublicUser(), getUser());
}
public boolean addSponsor(BwSponsor val) throws CalFacadeException {
setupSharableEntity(val);
updateOK(val);
if (findSponsor(val) != null) {
return false;
}
if (debug) {
trace("Add sponsor " + val);
}
getCal().addSponsor(val);
return true;
}
public void replaceSponsor(BwSponsor val) throws CalFacadeException {
updateOK(val);
getCal().updateSponsor(val);
}
public BwSponsor getSponsor(int id) throws CalFacadeException {
return getCal().getSponsor(id);
}
public BwSponsor findSponsor(BwSponsor s) throws CalFacadeException {
setupSharableEntity(s);
return getCal().findSponsor(s);
}
public int deleteSponsor(BwSponsor val) throws CalFacadeException {
deleteOK(val);
if (val.getId() <= CalFacadeDefs.maxReservedLocationId) {
// claim it doesn't exist
return 1;
}
/** Only allow delete if not in use
*/
if (getCal().getSponsorRefs(val).size() != 0) {
return 2;
}
if (pars.getPublicAdmin()) {
/* Remove from all auth preferences */
getUserAuth().removeSponsor(null, val);
}
/* Attempt to delete
*/
if (getCal().deleteSponsor(val)) {
return 0;
}
return 1; //doesn't exist
}
public BwSponsor ensureSponsorExists(BwSponsor val)
throws CalFacadeException {
if (val.getId() > 0) {
// We've already checked it exists
return val;
}
// Assume a new entity
setupSharableEntity(val);
BwSponsor s = findSponsor(val);
if (s != null) {
return s;
}
// doesn't exist at this point, so we add it to db
addSponsor(val);
return null;
}
public Collection getSponsorRefs(BwSponsor val) throws CalFacadeException {
return getCal().getSponsorRefs(val);
}
public EventInfo getEvent(int eventId) throws CalFacadeException {
return postProcess(getCal().getEvent(eventId), null, null);
}
public Collection getEvent(BwSubscription sub, BwCalendar cal,
String guid, String recurrenceId,
int recurRetrieval) throws CalFacadeException {
return postProcess(getCal().getEvent(cal, guid, recurrenceId, recurRetrieval),
sub);
}
public Collection getEvents(BwSubscription sub,
int recurRetrieval) throws CalFacadeException {
return getEvents(sub, null, null, null, recurRetrieval);
}
public Collection getEvents(BwSubscription sub, BwFilter filter,
BwDateTime startDate, BwDateTime endDate,
int recurRetrieval)
throws CalFacadeException {
TreeSet ts = new TreeSet();
// if (pars.getPublicAdmin() || (sub != null)) {
if (sub != null) {
BwCalendar cal = null;
if (sub != null) {
cal = sub.getCalendar();
}
return postProcess(getCal().getEvents(cal, filter, startDate,
endDate, recurRetrieval),
sub);
}
Collection subs = null;
if (currentView != null) {
if (debug) {
trace("Use current view \"" + currentView.getName() + "\"");
}
subs = currentView.getSubscriptions();
} else {
subs = getCurrentSubscriptions();
if (subs == null) {
// Try set of users subscriptions.
if (debug) {
trace("Use user subscriptions");
}
subs = getSubscriptions();
} else if (debug) {
trace("Use current subscriptions");
}
if (subs == null) {
if (debug) {
trace("Make up ALL events");
}
sub = new BwSubscription();
sub.setName("All events"); // XXX property?
sub.setDisplay(true);
sub.setInternalSubscription(true);
return postProcess(getCal().getEvents(null, filter, startDate,
endDate, recurRetrieval),
sub);
}
}
/* Iterate over the subscriptions and merge the results.
*
* First we iterate over the subscriptions looking for internal calendars.
* These we accumulate as children of a single calendar allowing a single
* query for all calendars.
*
* We will then iterate again to handle external calendars. (Not implemented)
*/
Iterator it = subs.iterator();
BwCalendar internal = new BwCalendar();
setupSharableEntity(internal);
// For locating subscriptions from calendar
HashMap sublookup = new HashMap();
while (it.hasNext()) {
sub = (BwSubscription)it.next();
BwCalendar calendar = getSubCalendar(sub);
if (calendar != null) {
internal.addChild(calendar);
putSublookup(sublookup, sub, calendar);
}
}
if (internal.getChildren().size() == 0) {
if (debug) {
trace("No children for internal calendar");
}
return ts;
}
ts.addAll(postProcess(getCal().getEvents(internal, filter,
startDate, endDate,
recurRetrieval),
sublookup));
return ts;
}
public DelEventResult deleteEvent(BwEvent event,
boolean delUnreffedLoc) throws CalFacadeException {
DelEventResult der = new DelEventResult(false, false, 0);
if (event == null) {
return der;
}
BwLocation loc = event.getLocation();
Calintf.DelEventResult cider = getCal().deleteEvent(event);
if (!cider.eventDeleted) {
return der;
}
der.eventDeleted = true;
der.alarmsDeleted = cider.alarmsDeleted;
if (delUnreffedLoc) {
if ((loc != null) &&
(getCal().getLocationRefs(loc).size() == 0) &&
(getCal().deleteLocation(loc))) {
der.locationDeleted = true;
}
}
return der;
}
public EventUpdateResult addEvent(BwCalendar cal,
BwEvent event,
Collection overrides) throws CalFacadeException {
EventUpdateResult updResult = new EventUpdateResult();
if (event instanceof BwEventProxy) {
BwEventProxy proxy = (BwEventProxy)event;
BwEvent override = proxy.getRef();
setupSharableEntity(override);
} else {
setupSharableEntity(event);
}
BwLocation loc = event.getLocation();
BwSponsor sp = event.getSponsor();
if ((sp != null) && (ensureSponsorExists(sp) == null)) {
updResult.sponsorsAdded++;
}
if ((loc != null) && (ensureLocationExists(loc) == null)) {
updResult.locationsAdded++;
}
/* If no calendar has been assigned for this event set it to the default
* calendar for non-public events or reject it for public events.
*/
if (cal == null) {
if (event.getPublick()) {
throw new CalFacadeException("No calendar assigned");
}
cal = getPreferences().getDefaultCalendar();
}
if (!cal.getCalendarCollection()) {
throw new CalFacadeAccessException();
}
event.setCalendar(cal);
event.setDtstamp(new DtStamp(new DateTime(true)).getValue());
event.setLastmod(new LastModified(new DateTime(true)).getValue());
event.setCreated(new Created(new DateTime(true)).getValue());
if (event instanceof BwEventProxy) {
BwEventProxy proxy = (BwEventProxy)event;
BwEvent override = proxy.getRef();
getCal().addEvent(override, overrides);
} else {
getCal().addEvent(event, overrides);
}
if (isPublicAdmin()) {
/* Mail event to any subscribers */
}
return updResult;
}
public void updateEvent(BwEvent event) throws CalFacadeException {
event.setLastmod(new LastModified(new DateTime(true)).getValue());
getCal().updateEvent(event);
if (isPublicAdmin()) {
/* Mail event to any subscribers */
}
}
/** For an event to which we have write access we simply mark it deleted.
*
* <p>Otherwise we add an annotation maarking the event as deleted.
*
* @param event
* @throws CalFacadeException
*/
public void markDeleted(BwEvent event) throws CalFacadeException {
CurrentAccess ca = getCal().checkAccess(event, PrivilegeDefs.privWrite, true);
if (ca.accessAllowed) {
// Have write access - just set the flag and move it into the owners trash
event.setDeleted(true);
event.setCalendar(getCal().getTrashCalendar(event.getOwner()));
updateEvent(event);
return;
}
// Need to annotate it as deleted
BwEventProxy proxy = BwEventProxy.makeAnnotation(event, event.getOwner());
// Where does the ref go? Not in the same calendar - we have no access
// Put it in the trash - but don't delete on empty trash
BwCalendar cal = getCal().getDeletedCalendar(getUser());
proxy.setOwner(getUser());
proxy.setDeleted(true);
proxy.setCalendar(cal);
addEvent(cal, proxy, null);
}
public Collection findEventsByName(BwCalendar cal, String val)
throws CalFacadeException {
return postProcess(getCal().getEventsByName(cal, val), (BwSubscription)null);
}
public BwSynchInfo getSynchInfo() throws CalFacadeException {
return getCal().getSynchInfo();
}
public void addSynchInfo(BwSynchInfo val) throws CalFacadeException {
getCal().addSynchInfo(val);
}
public void updateSynchInfo(BwSynchInfo val) throws CalFacadeException {
getCal().updateSynchInfo(val);
}
public BwSynchState getSynchState(BwEvent ev)
throws CalFacadeException {
return getCal().getSynchState(ev);
}
public Collection getDeletedSynchStates() throws CalFacadeException {
return getCal().getDeletedSynchStates();
}
public void addSynchState(BwSynchState val)
throws CalFacadeException {
getCal().addSynchState(val);
}
public void updateSynchState(BwSynchState val)
throws CalFacadeException {
getCal().updateSynchState(val);
}
public void getSynchData(BwSynchState val) throws CalFacadeException {
getCal().getSynchData(val);
}
public void setSynchData(BwSynchState val) throws CalFacadeException {
getCal().setSynchData(val);
}
public void updateSynchStates() throws CalFacadeException {
getCal().updateSynchStates();
}
public Collection getAlarms(BwEvent event, BwUser user) throws CalFacadeException {
return getCal().getAlarms(event, user);
}
public void setAlarm(BwEvent event,
BwEventAlarm alarm) throws CalFacadeException {
// Do some sort of validation here.
alarm.setEvent(event);
alarm.setOwner(getUser());
getCal().addAlarm(alarm);
}
public void updateAlarm(BwAlarm val) throws CalFacadeException {
getCal().updateAlarm(val);
}
public Collection getUnexpiredAlarms(BwUser user) throws CalFacadeException {
return getCal().getUnexpiredAlarms(user);
}
public Collection getUnexpiredAlarms(BwUser user, long triggerTime)
throws CalFacadeException {
return getCal().getUnexpiredAlarms(user, triggerTime);
}
/* This provides some limits to shareable entity updates for the
* admin users. It is applied in addition to the normal access checks
* applied at the lower levels.
*/
private void updateOK(Object o) throws CalFacadeException {
if (isGuest()) {
throw new CalFacadeAccessException();
}
if (isSuper()) {
// Always ok
return;
}
if (!(o instanceof BwShareableDbentity)) {
throw new CalFacadeAccessException();
}
if (!isPublicAdmin()) {
// Normal access checks apply
return;
}
BwShareableDbentity ent = (BwShareableDbentity)o;
if (adminCanEditAllPublicSponsors ||
ent.getCreator().equals(currentUser())) {
return;
}
throw new CalFacadeAccessException();
}
/* This checks to see if the current user has owner access based on the
* supplied object. This is used to limit access to objects not normally
* shared such as preferences and related objects like veiws and subscriptions.
*/
private void checkOwnerOrSuper(Object o) throws CalFacadeException {
if (isGuest()) {
throw new CalFacadeAccessException();
}
if (isSuper()) {
// Always ok?
return;
}
if (!(o instanceof BwOwnedDbentity)) {
throw new CalFacadeAccessException();
}
BwOwnedDbentity ent = (BwOwnedDbentity)o;
BwUser u;
/*if (!isPublicAdmin()) {
// Expect a different owner - always public-user????
return;
}*/
u = getUser();
if (u.equals(ent.getOwner())) {
return;
}
throw new CalFacadeAccessException();
}
/** Get the current db session
*
* @return Object
*/
Object getDbSession() throws CalFacadeException {
return getCal().getDbSession();
}
private void deleteOK(Object o) throws CalFacadeException {
updateOK(o);
}
/* Get a mailer object which allows the application to mail Message
* objects.
*
* @return MailerIntf implementation.
* /
private MailerIntf getMailer() throws CalFacadeException {
if (mailer != null) {
return mailer;
}
try {
mailer = (MailerIntf)CalEnv.getGlobalObject("mailerclass",
MailerIntf.class);
mailer.init(this, debug);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
return mailer;
}*/
private BwCalendar getSubCalendar(BwSubscription sub) throws CalFacadeException {
if (!sub.getInternalSubscription() || sub.getCalendarDeleted()) {
return null;
}
BwCalendar calendar = sub.getCalendar();
if (calendar != null) {
return calendar;
}
String path;
String uri = sub.getUri();
if (uri.startsWith(CalFacadeDefs.bwUriPrefix)) {
path = uri.substring(CalFacadeDefs.bwUriPrefix.length());
} else {
// Shouldn't happen?
path = uri;
}
if (debug) {
trace("Search for calendar \"" + path + "\"");
}
calendar = getCal().getCalendar(path);
if (calendar == null) {
// Assume deleted
sub.setCalendarDeleted(true);
updateSubscription(sub);
} else {
sub.setCalendar(calendar);
}
return calendar;
}
private void putSublookup(HashMap sublookup, BwSubscription sub, BwCalendar cal) {
if (cal.getCalendarCollection()) {
// Leaf node
sublookup.put(new Integer(cal.getId()), sub);
return;
}
Iterator it = cal.iterateChildren();
while (it.hasNext()) {
putSublookup(sublookup, sub, (BwCalendar)it.next());
}
}
private EventInfo postProcess(CoreEventInfo cei, BwSubscription sub,
HashMap sublookup)
throws CalFacadeException {
if (cei == null) {
return null;
}
//trace("ev: " + ev);
/* If the event is an event reference (an alias) implant it in an event
* proxy and return that object.
*/
BwEvent ev = cei.getEvent();
if (ev instanceof BwEventAnnotation) {
ev = new BwEventProxy((BwEventAnnotation)ev);
}
EventInfo ei = new EventInfo(ev);
if (sub != null) {
ei.setSubscription(sub);
} else if (sublookup != null) {
BwCalendar cal = ev.getCalendar();
ei.setSubscription((BwSubscription)sublookup.get(new Integer(cal.getId())));
}
ei.setRecurrenceId(ev.getRecurrence().getRecurrenceId());
ei.setCurrentAccess(cei.getCurrentAccess());
return ei;
}
private Collection postProcess(Collection ceis, BwSubscription sub)
throws CalFacadeException {
return postProcess(ceis, sub, null);
}
private Collection postProcess(Collection ceis, HashMap sublookup)
throws CalFacadeException {
return postProcess(ceis, null, sublookup);
}
private Collection postProcess(Collection ceis,
BwSubscription sub, HashMap sublookup)
throws CalFacadeException {
ArrayList al = new ArrayList();
Collection deleted = null;
/* XXX possibly not a great idea. We should probably retrieve the
* deleted events at the same time as we retrieve the desired set.
*
* This way we get too many.
*/
if (!isGuest() && !isPublicAdmin()) {
deleted = getCal().getDeletedProxies();
}
//traceDeleted(deleted);
Iterator it = ceis.iterator();
while (it.hasNext()) {
CoreEventInfo cei = (CoreEventInfo)it.next();
// if (!deleted.contains(cei)) {
if (!isDeleted(deleted, cei)) {
EventInfo ei = postProcess(cei, sub, sublookup);
al.add(ei);
}
}
return al;
}
/* XXX This is here because contains doesn't appear to be working with
* CoreEventInfo objects (or their events)
*
* This is either the TreeSet impleemntation (unlikely) or something to
* do with comparisons but under debug the compare method doesn't even get
* called for some of he objects in deleted
*/
private boolean isDeleted(Collection deleted, CoreEventInfo tryCei) {
if ((deleted == null) || (deleted.size() == 0)) {
return false;
}
Iterator it = deleted.iterator();
while (it.hasNext()) {
CoreEventInfo cei = (CoreEventInfo)it.next();
if (cei.equals(tryCei)) {
return true;
}
}
return false;
}
private BwPreferences getPreferences() throws CalFacadeException {
return dbi.getPreferences();
}
/*
private BwDateTime todaysDateTime() {
return CalFacadeUtil.getDateTime(new java.util.Date(System.currentTimeMillis()),
true, false);
}*/
Calintf getCal() throws CalFacadeException {
if (cali != null) {
return cali;
}
try {
cali = (Calintf)CalEnv.getGlobalObject("calintfclass", Calintf.class);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
try {
cali.open(); // Just for the user interactions
cali.beginTransaction();
boolean userCreated = cali.init(pars.getAuthUser(),
pars.getUser(),
pars.getPublicAdmin(),
getGroups(),
pars.getSynchId(),
debug);
// Prepare for call below.
publicUserAccount = cali.getSyspars().getPublicUser();
BwUser auth;
// XXX if (isPublicAdmin() || isGuest()) {
if (isGuest()) {
auth = getPublicUser();
} else {
auth = cali.getUser(pars.getAuthUser());
}
if (debug) {
trace("Got auth user object " + auth);
}
dbi = new CalSvcDb(this, auth);
if (userCreated) {
initUser(auth, cali);
}
if (debug) {
trace("PublicAdmin: " + pars.getPublicAdmin() + " user: " +
pars.getUser());
}
if (pars.getPublicAdmin()) {
/* We may be running as a different user. The preferences we want to see
* are those of the user we are running as - i.e. the 'run.as' user for
* not those of the authenticated user.
*/
dbi.close();
BwUser user = cali.getUser(pars.getUser());
dbi = new CalSvcDb(this, user);
}
return cali;
} finally {
cali.endTransaction();
cali.close();
}
}
private void initUser(BwUser user, Calintf cali) throws CalFacadeException {
// Add preferences
BwPreferences prefs = new BwPreferences();
BwCalendar cal = cali.getDefaultCalendar(user);
prefs.setOwner(user);
prefs.setDefaultCalendar(cal);
// Add default subscription for default calendar.
BwSubscription defSub = BwSubscription.makeSubscription(cal,
cal.getName(), true, true, false);
defSub.setOwner(user);
setupOwnedEntity(defSub);
prefs.addSubscription(defSub);
// Add default subscription for trash calendar.
cal = cali.getTrashCalendar(user);
BwSubscription sub = BwSubscription.makeSubscription(cal, cal.getName(),
false, false, false);
sub.setOwner(user);
setupOwnedEntity(sub);
prefs.addSubscription(sub);
// Add a default view for the default calendar subscription
BwView view = new BwView();
view.setName(getSyspars().getDefaultUserViewName());
view.addSubscription(defSub);
view.setOwner(user);
prefs.addView(view);
prefs.setPreferredView(view.getName());
dbi.updatePreferences(prefs);
}
private BwUser currentUser() throws CalFacadeException {
return getUser();
}
/*
private BwAuthUser getAdminUser() throws CalFacadeException {
if (adminUser == null) {
adminUser = getUserAuth().getUser(pars.getAuthUser());
}
return adminUser;
}
*/
/* See if in public admin mode
*/
private boolean isPublicAdmin() throws CalFacadeException {
return pars.getPublicAdmin();
}
/* See if current authorised user has super user access.
*/
private boolean isSuper() throws CalFacadeException {
return pars.getPublicAdmin() && superUser;
}
/* See if current authorised is a guest.
*/
private boolean isGuest() throws CalFacadeException {
return pars.isGuest();
}
/*
private boolean checkField(String fld1, String fld2) {
if (fld1 == null) {
if (fld2 == null) {
return true;
}
} else if (fld1.equals(fld2)) {
return true;
}
return false;
}
*/
private UserAuthCallBack getUserAuthCallBack() {
if (uacb == null) {
uacb = new UserAuthCallBack(this);
}
return (UserAuthCallBack)uacb;
}
private GroupsCallBack getGroupsCallBack() {
if (gcb == null) {
gcb = new GroupsCallBack(this);
}
return (GroupsCallBack)gcb;
}
private class IcalCallbackcb implements IcalCallback {
public BwUser getUser() throws CalFacadeException {
return CalSvc.this.getUser();
}
public BwCategory findCategory(BwCategory val) throws CalFacadeException {
return CalSvc.this.findCategory(val);
}
public void addCategory(BwCategory val) throws CalFacadeException {
CalSvc.this.addCategory(val);
}
public BwLocation ensureLocationExists(String address) throws CalFacadeException {
BwLocation loc = new BwLocation();
loc.setAddress(address);
loc.setOwner(getUser());
BwLocation l = CalSvc.this.ensureLocationExists(loc);
if (l == null) {
return loc;
}
return l;
}
public Collection getEvent(BwCalendar cal, String guid, String rid,
int recurRetrieval) throws CalFacadeException {
return CalSvc.this.getEvent(BwSubscription.makeSubscription(cal), cal, guid,
rid, recurRetrieval);
}
public URIgen getURIgen() throws CalFacadeException {
return null;
}
public CalTimezones getTimezones() throws CalFacadeException {
return getCal().getTimezones();
}
public void saveTimeZone(String tzid, VTimeZone vtz
) throws CalFacadeException {
timezones.saveTimeZone(tzid, vtz);
}
public void registerTimeZone(String id, TimeZone timezone)
throws CalFacadeException {
timezones.registerTimeZone(id, timezone);
}
public TimeZone getTimeZone(final String id) throws CalFacadeException {
return timezones.getTimeZone(id);
}
public VTimeZone findTimeZone(final String id, BwUser owner) throws CalFacadeException {
return timezones.findTimeZone(id, owner);
}
}
/** Set the owner and creator on a shareable entity.
*
* @param entity
* @throws CalFacadeException
*/
private void setupSharableEntity(BwShareableDbentity entity)
throws CalFacadeException {
if (entity.getCreator() == null) {
entity.setCreator(getUser());
}
setupOwnedEntity(entity);
}
/** Set the owner and publick on an owned entity.
*
* @param entity
* @throws CalFacadeException
*/
private void setupOwnedEntity(BwOwnedDbentity entity)
throws CalFacadeException {
entity.setPublick(isPublicAdmin());
if (entity.getOwner() == null) {
BwUser owner;
if (entity.getPublick()) {
owner = getPublicUser();
} else {
owner = getUser();
}
entity.setOwner(owner);
}
}
private Index getIndexer() throws CalFacadeException {
try {
if (indexer == null) {
indexer = new BwIndexLuceneImpl(this,
// XXX Schema change - in syspars
"/temp/bedeworkindex",
isPublicAdmin(),
debug);
}
return indexer;
} catch (Throwable t) {
throw new CalFacadeException(t);
}
}
/* Call to (re)index an event
*/
private void indexEvent(BwEvent ev) throws CalFacadeException {
try {
getIndexer().indexRec(ev);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
}
private void unindexEvent(BwEvent ev) throws CalFacadeException {
try {
getIndexer().unindexRec(ev);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
}
/* Call to (re)index a calendar
*/
private void indexCalendar(BwCalendar cal) throws CalFacadeException {
try {
getIndexer().indexRec(cal);
} catch (Throwable t) {
throw new CalFacadeException(t);
}
}
private void unindexCalendar(BwCalendar cal) throws CalFacadeException {
try {
getIndexer().unindexRec(cal);
// And all the children
Iterator it = cal.iterateChildren();
while (it.hasNext()) {
BwCalendar ch = (BwCalendar)it.next();
unindexCalendar(ch);
}
} catch (Throwable t) {
throw new CalFacadeException(t);
}
}
/* Get a logger for messages
*/
private Logger getLogger() {
if (log == null) {
log = Logger.getLogger(this.getClass());
}
return log;
}
private void logIt(String msg) {
getLogger().info(msg);
}
private void trace(String msg) {
getLogger().debug(msg);
}
} |
package framework;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.media.opengl.GL2;
/**
* This class represents a curve loop defined by a sequence of control points.
*
* @author Robert C. Duvall
*/
public class Spline implements Iterable<float[]> {
private List<float[]> myControlPoints = new ArrayList<>();
/**
* Create empty curve.
*/
public Spline (float[] controlPoints) {
// BUGBUG: check that it is a multiple of 3
for (int k = 0; k < controlPoints.length; k += 3) {
addPoint(controlPoints[k], controlPoints[k+1], controlPoints[k+2]);
}
}
/**
* Create curve from the control points listed in the given file.
*/
@SuppressWarnings("resource")
public Spline (String filename) {
try {
Scanner input = new Scanner(new File(filename));
input.nextLine(); // read starting comment
while (input.hasNextLine()) {
Scanner line = new Scanner(input.nextLine());
addPoint(line.nextFloat(), line.nextFloat(), line.nextFloat());
}
input.close();
} catch (FileNotFoundException e) {
// BUGBUG: not the best way to handle this error
e.printStackTrace();
System.exit(1);
}
}
/**
* Add control point
*
* @return index of new control point
*/
public int addPoint (float x, float y, float z) {
return addPoint(new float[] { x, y, z});
}
/**
* Add control point
*
* @return index of new control point
*/
public int addPoint (float[] point) {
myControlPoints.add(point);
return myControlPoints.size() - 1;
}
/**
* Evaluate a point on the curve at a given time.
*
* Note, t varies from [0 .. 1] across a set of 4 control points and
* each set of 4 control points influences the curve within them.
* Thus a time value between [0 .. 1] generates a point within the first
* 4 control points and a value between [n-2 .. n-1] generates a point
* within the last 4 control points.
*
* A time value outside the range [0 .. n] is wrapped, modded, so it
* falls within the appropriate range.
*/
public float[] evaluateAt (float t) {
int tn = (int)Math.floor(t);
float u = t - tn;
float u_sq = u * u;
float u_cube = u * u_sq;
// evaluate basis functions at t, faster than matrix multiply
float[] basis = {
-u_cube + 3*u_sq - 3*u + 1,
3*u_cube - 6*u_sq + 4,
-3*u_cube + 3*u_sq + 3*u + 1,
u_cube
};
return evaluateBasisAt(tn, basis);
}
/**
* Evaluate the derivative of the curve at a given time.
*
* Note, t varies from [0 .. 1] across a set of 4 control points and
* each set of 4 control points influences the curve within them.
* Thus a time value between [0 .. 1] generates a derivative within the
* first 4 control points and a value between [n-2 .. n-1] generates a
* derivative within the last 4 control points.
*
* A time value outside the range [0 .. n] is wrapped, modded, so it
* falls within the appropriate range.
*/
public float[] evaluateDerivativeAt (float t) {
int tn = (int)Math.floor(t);
float u = t - tn;
float u_sq = u * u;
// evaluate basis functions at t, faster than matrix multiply
float[] basis = {
-3*u_sq + 6*u - 3,
9*u_sq - 12*u,
-9*u_sq + 6*u + 3,
3*u_sq
};
return evaluateBasisAt(tn, basis);
}
/**
* Returns total number of control points around the curve.
*/
public int numControlPoints () {
return myControlPoints.size();
}
/**
* Draws the curve as a sequence of lines as the given resolution.
*
* The higher the resolution, the more lines generated, the closer
* the approximation to the actual curve. A value of 1 will look
* like the points a connected linearly, with no curve, with smaller
* values giving better approximations.
*/
public void draw (GL2 gl, float resolution) {
gl.glBegin(GL2.GL_LINE_STRIP); {
for (float t = 0; t < numControlPoints(); t += resolution) {
gl.glVertex3fv(evaluateAt(t), 0);
}
}
gl.glEnd();
}
/**
* Draws control points around the curve as a collection of points.
*/
public void drawControlPoints (GL2 gl) {
gl.glBegin(GL2.GL_POINTS); {
for (float[] pt : myControlPoints) {
gl.glVertex3fv(pt, 0);
}
}
gl.glEnd();
}
/**
* Returns an iterator over the curve's control points, allowing the
* user to directly iterate over them using a foreach loop.
*/
@Override
public Iterator<float[]> iterator () {
return Collections.unmodifiableList(myControlPoints).iterator();
}
/**
* Returns a string representation of the curve's control points.
*/
@Override
public String toString () {
StringBuffer result = new StringBuffer();
for (float[] pt : myControlPoints) {
result.append(Arrays.toString(pt));
}
return result.toString();
}
// use the basis functions to evaluate a specific point on the curve
private float[] evaluateBasisAt (int t, float[] basis) {
// sum the control points times the basis functions for each dimension
float[] result = { 0, 0, 0 };
for (int k = 0; k < 4; k++) {
int index = (t + k) % numControlPoints();
result[0] += myControlPoints.get(index)[0] * basis[k];
result[1] += myControlPoints.get(index)[1] * basis[k];
result[2] += myControlPoints.get(index)[2] * basis[k];
}
// divide through the constant factor
for (int k = 0; k < result.length; k++) {
result[k] /= 6.0f;
}
return result;
}
} |
package com.company;
import java.io.File;
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] args) {
String fileName = "test.txt";
DB db = new DB(fileName);
}
} |
package com.health.input;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.health.Table;
/**
* Implements a parser for xls input files.
*
*/
public class XlsParser implements Parser {
/**
* Given a path to a xls file and an input descriptor, parses the input file into a {@link Table}.
*
* @param path
* the path of the input file.
* @param config
* the input descriptor.
* @return a table representing the parsed input file.
* @throws IOException
* if any IO errors occur.
* @throws InputException
* if any input errors occur.
*/
@Override
public Table parse(String path, InputDescriptor config) throws InputException, IOException {
Objects.requireNonNull(path);
Objects.requireNonNull(config);
Table table = config.buildTable();
FileInputStream io = new FileInputStream(path);
HSSFWorkbook wb = new HSSFWorkbook(io);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
// Do something here
}
}
wb.close();
return table;
}
} |
package game;
import java.io.IOException;
import javax.swing.JFrame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* @author Sean Lewis
*/
public class GravityGolf {
public static void main(String[] args) throws IOException {
final GameFrame gf = new GameFrame();
gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
gf.safeQuit(); // ensures gamelog.txt and settings.txt will be
// written to on close
gf.dispose();
}
});
}
} |
package io.searchbox.core;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import io.searchbox.action.AbstractAction;
import io.searchbox.action.AbstractMultiINodeActionBuilder;
import io.searchbox.action.AbstractMultiIndexActionBuilder;
import io.searchbox.action.AbstractMultiTypeActionBuilder;
import io.searchbox.strings.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @author Bartosz Polnik
*/
public class Cat extends AbstractAction<CatResult> {
private final static String PATH_TO_RESULT = "result";
private final String operationPath;
protected <T extends AbstractAction.Builder<Cat, ? extends Builder> & CatBuilder> Cat(T builder) {
super(builder);
this.operationPath = builder.operationPath();
setURI(buildURI());
}
@Override
protected String buildURI() {
String uriSuffix = super.buildURI();
try {
if (!StringUtils.isBlank(nodes)) {
uriSuffix += URLEncoder.encode(nodes, CHARSET);
}
} catch (UnsupportedEncodingException e) {
log.error("Error occurred while adding nodes to uri", e);
}
return "_cat/" + this.operationPath + (uriSuffix.isEmpty() ? "" : "/") + uriSuffix;
}
@Override
public String getRestMethodName() {
return "GET";
}
@Override
public String getPathToResult() {
return PATH_TO_RESULT;
}
@Override
public CatResult createNewElasticSearchResult(String responseBody, int statusCode, String reasonPhrase, Gson gson) {
return createNewElasticSearchResult(new CatResult(gson), responseBody, statusCode, reasonPhrase, gson);
}
@Override
protected JsonObject parseResponseBody(String responseBody) {
if (responseBody == null || responseBody.trim().isEmpty()) {
return new JsonObject();
}
JsonElement parsed = new JsonParser().parse(responseBody);
if (parsed.isJsonArray()) {
JsonObject result = new JsonObject();
result.add(PATH_TO_RESULT, parsed.getAsJsonArray());
return result;
} else {
throw new JsonSyntaxException("Cat response did not contain a JSON Array");
}
}
public static class IndicesBuilder extends AbstractMultiTypeActionBuilder<Cat, IndicesBuilder> implements CatBuilder {
private static final String operationPath = "indices";
public IndicesBuilder() {
setHeader("accept", "application/json");
setHeader("content-type", "application/json");
}
@Override
public Cat build() {
return new Cat(this);
}
@Override
public String operationPath() {
return operationPath;
}
}
public static class AliasesBuilder extends AbstractMultiIndexActionBuilder<Cat, AliasesBuilder> implements CatBuilder {
private static final String operationPath = "aliases";
public AliasesBuilder() {
setHeader("accept", "application/json");
setHeader("content-type", "application/json");
}
@Override
public Cat build() {
return new Cat(this);
}
@Override
public String operationPath() {
return operationPath;
}
}
public static class ShardsBuilder extends AbstractMultiIndexActionBuilder<Cat, ShardsBuilder> implements CatBuilder {
private static final String operationPath = "shards";
public ShardsBuilder() {
setHeader("accept", "application/json");
setHeader("content-type", "application/json");
}
@Override
public Cat build() {
return new Cat(this);
}
@Override
public String operationPath() {
return operationPath;
}
@Override
public String getJoinedIndices() {
if (indexNames.size() > 0) {
return Joiner.on(',').join(indexNames);
} else {
return null;
}
}
}
public static class SegmentsBuilder extends AbstractMultiIndexActionBuilder<Cat, SegmentsBuilder> implements CatBuilder {
private static final String operationPath = "segments";
public SegmentsBuilder() {
setHeader("accept", "application/json");
setHeader("content-type", "application/json");
}
@Override
public Cat build() {
return new Cat(this);
}
@Override
public String operationPath() {
return operationPath;
}
@Override
public String getJoinedIndices() {
return indexNames.size() > 0 ? Joiner.on(',').join(indexNames) : null;
}
}
public static class NodesBuilder extends AbstractAction.Builder<Cat, NodesBuilder> implements CatBuilder {
private static final String operationPath = "nodes";
public NodesBuilder() {
setHeader("accept", "application/json");
setHeader("content-type", "application/json");
}
@Override
public Cat build() {
return new Cat(this);
}
@Override
public String operationPath() {
return operationPath;
}
}
public static class AllocationBuilder extends AbstractMultiINodeActionBuilder<Cat, AllocationBuilder> implements CatBuilder {
private static final String operationPath = "allocation";
public AllocationBuilder() {
setHeader("accept", "application/json");
setHeader("content-type", "application/json");
}
@Override
public Cat build() {
return new Cat(this);
}
@Override
public String operationPath() {
return operationPath;
}
@Override
public String getJoinedNodes() {
return nodes.isEmpty() ? null : Joiner.on(',').join(nodes);
}
}
protected interface CatBuilder {
String operationPath();
}
} |
package com.jme3.math;
import com.jme3.export.*;
import java.io.IOException;
/**
* <code>ColorRGBA</code> defines a color made from a collection of red, green
* and blue values stored in Linear color space. An alpha value determines is
* transparency.
*
* @author Mark Powell
* @version $Id: ColorRGBA.java,v 1.29 2007/09/09 18:25:14 irrisor Exp $
*/
public final class ColorRGBA implements Savable, Cloneable, java.io.Serializable {
static final float GAMMA = 2.2f;
static final long serialVersionUID = 1;
/**
* The color black (0,0,0).
*/
public static final ColorRGBA Black = new ColorRGBA(0f, 0f, 0f, 1f);
/**
* The color white (1,1,1).
*/
public static final ColorRGBA White = new ColorRGBA(1f, 1f, 1f, 1f);
/**
* The color gray (.2,.2,.2).
*/
public static final ColorRGBA DarkGray = new ColorRGBA(0.2f, 0.2f, 0.2f, 1.0f);
/**
* The color gray (.5,.5,.5).
*/
public static final ColorRGBA Gray = new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f);
/**
* The color gray (.8,.8,.8).
*/
public static final ColorRGBA LightGray = new ColorRGBA(0.8f, 0.8f, 0.8f, 1.0f);
/**
* The color red (1,0,0).
*/
public static final ColorRGBA Red = new ColorRGBA(1f, 0f, 0f, 1f);
/**
* The color green (0,1,0).
*/
public static final ColorRGBA Green = new ColorRGBA(0f, 1f, 0f, 1f);
/**
* The color blue (0,0,1).
*/
public static final ColorRGBA Blue = new ColorRGBA(0f, 0f, 1f, 1f);
/**
* The color yellow (1,1,0).
*/
public static final ColorRGBA Yellow = new ColorRGBA(1f, 1f, 0f, 1f);
/**
* The color magenta (1,0,1).
*/
public static final ColorRGBA Magenta = new ColorRGBA(1f, 0f, 1f, 1f);
/**
* The color cyan (0,1,1).
*/
public static final ColorRGBA Cyan = new ColorRGBA(0f, 1f, 1f, 1f);
/**
* The color orange (251/255, 130/255,0).
*/
public static final ColorRGBA Orange = new ColorRGBA(251f / 255f, 130f / 255f, 0f, 1f);
/**
* The color brown (65/255, 40/255, 25/255).
*/
public static final ColorRGBA Brown = new ColorRGBA(65f / 255f, 40f / 255f, 25f / 255f, 1f);
/**
* The color pink (1, 0.68, 0.68).
*/
public static final ColorRGBA Pink = new ColorRGBA(1f, 0.68f, 0.68f, 1f);
/**
* The black color with no alpha (0, 0, 0, 0).
*/
public static final ColorRGBA BlackNoAlpha = new ColorRGBA(0f, 0f, 0f, 0f);
/**
* The red component of the color. 0 is none and 1 is maximum red.
*/
public float r;
/**
* The green component of the color. 0 is none and 1 is maximum green.
*/
public float g;
/**
* The blue component of the color. 0 is none and 1 is maximum blue.
*/
public float b;
/**
* The alpha component of the color. 0 is transparent and 1 is opaque.
*/
public float a;
/**
* Constructor instantiates a new <code>ColorRGBA</code> object. This
* color is the default "white" with all values 1.
*/
public ColorRGBA() {
r = g = b = a = 1.0f;
}
/**
* Constructor instantiates a new <code>ColorRGBA</code> object. The
* values are defined as passed parameters.
* these values are assumed to be in linear space and stored as is.
* If you want to assign sRGB values use
* {@link ColorRGBA#setAsSrgb(float, float, float, float) }
* @param r The red component of this color.
* @param g The green component of this <code>ColorRGBA</code>.
* @param b The blue component of this <code>ColorRGBA</code>.
* @param a The alpha component of this <code>ColorRGBA</code>.
*/
public ColorRGBA(float r, float g, float b, float a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
/**
* Copy constructor creates a new <code>ColorRGBA</code> object, based on
* a provided color.
* @param rgba The <code>ColorRGBA</code> object to copy.
*/
public ColorRGBA(ColorRGBA rgba) {
this.a = rgba.a;
this.r = rgba.r;
this.g = rgba.g;
this.b = rgba.b;
}
/**
* <code>set</code> sets the RGBA values of this <code>ColorRGBA</code>.
* these values are assumed to be in linear space and stored as is.
* If you want to assign sRGB values use
* {@link ColorRGBA#setAsSrgb(float, float, float, float) }
*
* @param r The red component of this color.
* @param g The green component of this color.
* @param b The blue component of this color.
* @param a The alpha component of this color.
* @return this
*/
public ColorRGBA set(float r, float g, float b, float a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
return this;
}
/**
* <code>set</code> sets the values of this <code>ColorRGBA</code> to those
* set by a parameter color.
*
* @param rgba The color to set this <code>ColorRGBA</code> to.
* @return this
*/
public ColorRGBA set(ColorRGBA rgba) {
if (rgba == null) {
r = 0;
g = 0;
b = 0;
a = 0;
} else {
r = rgba.r;
g = rgba.g;
b = rgba.b;
a = rgba.a;
}
return this;
}
/**
* Saturate that color ensuring all channels have a value between 0 and 1
*/
public void clamp() {
r = FastMath.clamp(r, 0f, 1f);
g = FastMath.clamp(g, 0f, 1f);
b = FastMath.clamp(b, 0f, 1f);
a = FastMath.clamp(a, 0f, 1f);
}
/**
* <code>getColorArray</code> retrieves the color values of this
* <code>ColorRGBA</code> as a four element <code>float</code> array in the
* order: r,g,b,a.
* @return The <code>float</code> array that contains the color components.
*/
public float[] getColorArray() {
return new float[]{r, g, b, a};
}
/**
* Stores the current r,g,b,a values into the given array. The given array must have a
* length of 4 or greater, or an array index out of bounds exception will be thrown.
* @param store The <code>float</code> array to store the values into.
* @return The <code>float</code> array after storage.
*/
public float[] getColorArray(float[] store) {
store[0] = r;
store[1] = g;
store[2] = b;
store[3] = a;
return store;
}
/**
* Retrieves the alpha component value of this <code>ColorRGBA</code>.
* @return The alpha component value.
*/
public float getAlpha() {
return a;
}
/**
* Retrieves the red component value of this <code>ColorRGBA</code>.
* @return The red component value.
*/
public float getRed() {
return r;
}
/**
* Retrieves the blue component value of this <code>ColorRGBA</code>.
* @return The blue component value.
*/
public float getBlue() {
return b;
}
/**
* Retrieves the green component value of this <code>ColorRGBA</code>.
* @return The green component value.
*/
public float getGreen() {
return g;
}
/**
* Sets this <code>ColorRGBA</code> to the interpolation by changeAmnt from
* this to the finalColor:
* this=(1-changeAmnt)*this + changeAmnt * finalColor
* @param finalColor The final color to interpolate towards.
* @param changeAmnt An amount between 0.0 - 1.0 representing a percentage
* change from this towards finalColor.
* @return this ColorRGBA
*/
public ColorRGBA interpolateLocal(ColorRGBA finalColor, float changeAmnt) {
this.r = (1 - changeAmnt) * this.r + changeAmnt * finalColor.r;
this.g = (1 - changeAmnt) * this.g + changeAmnt * finalColor.g;
this.b = (1 - changeAmnt) * this.b + changeAmnt * finalColor.b;
this.a = (1 - changeAmnt) * this.a + changeAmnt * finalColor.a;
return this;
}
/**
* Sets this <code>ColorRGBA</code> to the interpolation by changeAmnt from
* beginColor to finalColor:
* this=(1-changeAmnt)*beginColor + changeAmnt * finalColor
* @param beginColor The beginning color (changeAmnt=0).
* @param finalColor The final color to interpolate towards (changeAmnt=1).
* @param changeAmnt An amount between 0.0 - 1.0 representing a percentage
* change from beginColor towards finalColor.
* @return this ColorRGBA
*/
public ColorRGBA interpolateLocal(ColorRGBA beginColor, ColorRGBA finalColor, float changeAmnt) {
this.r = (1 - changeAmnt) * beginColor.r + changeAmnt * finalColor.r;
this.g = (1 - changeAmnt) * beginColor.g + changeAmnt * finalColor.g;
this.b = (1 - changeAmnt) * beginColor.b + changeAmnt * finalColor.b;
this.a = (1 - changeAmnt) * beginColor.a + changeAmnt * finalColor.a;
return this;
}
/**
* <code>randomColor</code> is a utility method that generates a random
* opaque color.
* @return a random <code>ColorRGBA</code> with an alpha set to 1.
*/
public static ColorRGBA randomColor() {
ColorRGBA rVal = new ColorRGBA(0, 0, 0, 1);
rVal.r = FastMath.nextRandomFloat();
rVal.g = FastMath.nextRandomFloat();
rVal.b = FastMath.nextRandomFloat();
return rVal;
}
/**
* Multiplies each r,g,b,a of this <code>ColorRGBA</code> by the corresponding
* r,g,b,a of the given color and returns the result as a new <code>ColorRGBA</code>.
* Used as a way of combining colors and lights.
* @param c The color to multiply by.
* @return The new <code>ColorRGBA</code>. this*c
*/
public ColorRGBA mult(ColorRGBA c) {
return new ColorRGBA(c.r * r, c.g * g, c.b * b, c.a * a);
}
/**
* Multiplies each r,g,b,a of this <code>ColorRGBA</code> by the given scalar and
* returns the result as a new <code>ColorRGBA</code>.
* Used as a way of making colors dimmer or brighter.
* @param scalar The scalar to multiply by.
* @return The new <code>ColorRGBA</code>. this*scalar
*/
public ColorRGBA mult(float scalar) {
return new ColorRGBA(scalar * r, scalar * g, scalar * b, scalar * a);
}
/**
* Multiplies each r,g,b,a of this <code>ColorRGBA</code> by the given scalar and
* returns the result (this).
* Used as a way of making colors dimmer or brighter.
* @param scalar The scalar to multiply by.
* @return this*c
*/
public ColorRGBA multLocal(float scalar) {
this.r *= scalar;
this.g *= scalar;
this.b *= scalar;
this.a *= scalar;
return this;
}
/**
* Adds each r,g,b,a of this <code>ColorRGBA</code> by the corresponding
* r,g,b,a of the given color and returns the result as a new <code>ColorRGBA</code>.
* Used as a way of combining colors and lights.
* @param c The color to add.
* @return The new <code>ColorRGBA</code>. this+c
*/
public ColorRGBA add(ColorRGBA c) {
return new ColorRGBA(c.r + r, c.g + g, c.b + b, c.a + a);
}
/**
* Adds each r,g,b,a of this <code>ColorRGBA</code> by the r,g,b,a the given
* color and returns the result (this).
* Used as a way of combining colors and lights.
* @param c The color to add.
* @return this+c
*/
public ColorRGBA addLocal(ColorRGBA c) {
set(c.r + r, c.g + g, c.b + b, c.a + a);
return this;
}
/**
* <code>toString</code> returns the string representation of this <code>ColorRGBA</code>.
* The format of the string is:<br>
* <Class Name>: [R=RR.RRRR, G=GG.GGGG, B=BB.BBBB, A=AA.AAAA]
* @return The string representation of this <code>ColorRGBA</code>.
*/
@Override
public String toString() {
return "Color[" + r + ", " + g + ", " + b + ", " + a + "]";
}
@Override
public ColorRGBA clone() {
try {
return (ColorRGBA) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(); // can not happen
}
}
/**
* Saves this <code>ColorRGBA</code> into the given <code>float</code> array.
* @param floats The <code>float</code> array to take this <code>ColorRGBA</code>.
* If null, a new <code>float[4]</code> is created.
* @return The array, with r,g,b,a float values in that order.
*/
public float[] toArray(float[] floats) {
if (floats == null) {
floats = new float[4];
}
floats[0] = r;
floats[1] = g;
floats[2] = b;
floats[3] = a;
return floats;
}
/**
* <code>equals</code> returns true if this <code>ColorRGBA</code> is logically equivalent
* to a given color. That is, if all the components of the two colors are the same.
* False is returned otherwise.
* @param o The object to compare against.
* @return true if the colors are equal, false otherwise.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof ColorRGBA)) {
return false;
}
if (this == o) {
return true;
}
ColorRGBA comp = (ColorRGBA) o;
if (Float.compare(r, comp.r) != 0) {
return false;
}
if (Float.compare(g, comp.g) != 0) {
return false;
}
if (Float.compare(b, comp.b) != 0) {
return false;
}
if (Float.compare(a, comp.a) != 0) {
return false;
}
return true;
}
/**
* <code>hashCode</code> returns a unique code for this <code>ColorRGBA</code> based
* on its values. If two colors are logically equivalent, they will return
* the same hash code value.
* @return The hash code value of this <code>ColorRGBA</code>.
*/
@Override
public int hashCode() {
int hash = 37;
hash += 37 * hash + Float.floatToIntBits(r);
hash += 37 * hash + Float.floatToIntBits(g);
hash += 37 * hash + Float.floatToIntBits(b);
hash += 37 * hash + Float.floatToIntBits(a);
return hash;
}
public void write(JmeExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(r, "r", 0);
capsule.write(g, "g", 0);
capsule.write(b, "b", 0);
capsule.write(a, "a", 0);
}
public void read(JmeImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
r = capsule.readFloat("r", 0);
g = capsule.readFloat("g", 0);
b = capsule.readFloat("b", 0);
a = capsule.readFloat("a", 0);
}
/**
* Retrieves the component values of this <code>ColorRGBA</code> as
* a four element <code>byte</code> array in the order: r,g,b,a.
* @return the <code>byte</code> array that contains the color components.
*/
public byte[] asBytesRGBA() {
byte[] store = new byte[4];
store[0] = (byte) ((int) (r * 255) & 0xFF);
store[1] = (byte) ((int) (g * 255) & 0xFF);
store[2] = (byte) ((int) (b * 255) & 0xFF);
store[3] = (byte) ((int) (a * 255) & 0xFF);
return store;
}
/**
* Retrieves the component values of this <code>ColorRGBA</code> as an
* <code>int</code> in a,r,g,b order.
* Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue.
* @return The integer representation of this <code>ColorRGBA</code> in a,r,g,b order.
*/
public int asIntARGB() {
int argb = (((int) (a * 255) & 0xFF) << 24)
| (((int) (r * 255) & 0xFF) << 16)
| (((int) (g * 255) & 0xFF) << 8)
| (((int) (b * 255) & 0xFF));
return argb;
}
/**
* Retrieves the component values of this <code>ColorRGBA</code> as an
* <code>int</code> in r,g,b,a order.
* Bits 24-31 are red, 16-23 are green, 8-15 are blue, 0-7 are alpha.
* @return The integer representation of this <code>ColorRGBA</code> in r,g,b,a order.
*/
public int asIntRGBA() {
int rgba = (((int) (r * 255) & 0xFF) << 24)
| (((int) (g * 255) & 0xFF) << 16)
| (((int) (b * 255) & 0xFF) << 8)
| (((int) (a * 255) & 0xFF));
return rgba;
}
/**
* Retrieves the component values of this <code>ColorRGBA</code> as an
* <code>int</code> in a,b,g,r order.
* Bits 24-31 are alpha, 16-23 are blue, 8-15 are green, 0-7 are red.
* @return The integer representation of this <code>ColorRGBA</code> in a,b,g,r order.
*/
public int asIntABGR() {
int abgr = (((int) (a * 255) & 0xFF) << 24)
| (((int) (b * 255) & 0xFF) << 16)
| (((int) (g * 255) & 0xFF) << 8)
| (((int) (r * 255) & 0xFF));
return abgr;
}
/**
* Sets the component values of this <code>ColorRGBA</code> with the given
* combined ARGB <code>int</code>.
* Bits 24-31 are alpha, bits 16-23 are red, bits 8-15 are green, bits 0-7 are blue.
* @param color The integer ARGB value used to set this <code>ColorRGBA</code>.
*/
public void fromIntARGB(int color) {
a = ((byte) (color >> 24) & 0xFF) / 255f;
r = ((byte) (color >> 16) & 0xFF) / 255f;
g = ((byte) (color >> 8) & 0xFF) / 255f;
b = ((byte) (color) & 0xFF) / 255f;
}
/**
* Sets the RGBA values of this <code>ColorRGBA</code> with the given combined RGBA value
* Bits 24-31 are red, bits 16-23 are green, bits 8-15 are blue, bits 0-7 are alpha.
* @param color The integer RGBA value used to set this object.
*/
public void fromIntRGBA(int color) {
r = ((byte) (color >> 24) & 0xFF) / 255f;
g = ((byte) (color >> 16) & 0xFF) / 255f;
b = ((byte) (color >> 8) & 0xFF) / 255f;
a = ((byte) (color) & 0xFF) / 255f;
}
/**
* Transform this <code>ColorRGBA</code> to a <code>Vector3f</code> using
* x = r, y = g, z = b. The Alpha value is not used.
* This method is useful to use for shaders assignment.
* @return A <code>Vector3f</code> containing the RGB value of this <code>ColorRGBA</code>.
*/
public Vector3f toVector3f() {
return new Vector3f(r, g, b);
}
/**
* Transform this <code>ColorRGBA</code> to a <code>Vector4f</code> using
* x = r, y = g, z = b, w = a.
* This method is useful to use for shaders assignment.
* @return A <code>Vector4f</code> containing the RGBA value of this <code>ColorRGBA</code>.
*/
public Vector4f toVector4f() {
return new Vector4f(r, g, b, a);
}
/**
* Sets the rgba channels of this color in sRGB color space.
* You probably want to use this method if the color is picked by the use
* in a color picker from a GUI.
*
* Note that the values will be gamma corrected to be stored in linear space
* GAMMA value is 2.2
*
* Note that no correction will be performed on the alpha channel as it's
* conventionnally doesn't represent a color itself
*
* @param r the red value in sRGB color space
* @param g the green value in sRGB color space
* @param b the blue value in sRGB color space
* @param a the alpha value
*
* @return this ColorRGBA with updated values.
*/
public ColorRGBA setAsSrgb(float r, float g, float b, float a){
this.r = (float)Math.pow(r, GAMMA);
this.b = (float)Math.pow(b, GAMMA);
this.g = (float)Math.pow(g, GAMMA);
this.a = a;
return this;
}
/**
* Get the color in sRGB color space as a Vector4f
*
* Note that linear values stored in the ColorRGBA will be gamma corrected
* and returned as a Vector4f
* the x atribute will be fed with the r channel in sRGB space
* the y atribute will be fed with the g channel in sRGB space
* the z atribute will be fed with the b channel in sRGB space
* the w atribute will be fed with the a channel
*
* Note that no correction will be performed on the alpha channel as it's
* conventionnally doesn't represent a color itself
*
* @return the color in sRGB color space as a Vector4f
*/
public Vector4f getAsSrgb(){
Vector4f srgb = new Vector4f();
float invGama = 1f/GAMMA;
srgb.x = (float)Math.pow(r, invGama);
srgb.y = (float)Math.pow(g, invGama);
srgb.z = (float)Math.pow(b, invGama);
srgb.w = a;
return srgb;
}
} |
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
package javax.management.j2ee;
import java.rmi.RemoteException;
import java.util.Set;
import javax.ejb.EJBObject;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
/**
*
*
*
* @version $Revision: 1.4 $
*/
public interface Management extends EJBObject {
public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, RemoteException;
public AttributeList getAttributes(ObjectName name, String[] attributes) throws InstanceNotFoundException, ReflectionException, RemoteException;
public String getDefaultDomain() throws RemoteException;
public Integer getMBeanCount() throws RemoteException;
public MBeanInfo getMBeanInfo(ObjectName name) throws IntrospectionException, InstanceNotFoundException, ReflectionException, RemoteException;
public Object invoke(ObjectName name, String operationName, Object[] params, String[] signature) throws InstanceNotFoundException, MBeanException, ReflectionException, RemoteException;
public boolean isRegistered(ObjectName name) throws RemoteException;
public Set queryNames(ObjectName name, QueryExp query) throws RemoteException;
public void setAttribute(ObjectName name, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, RemoteException;
public AttributeList setAttributes(ObjectName name, AttributeList attributes) throws InstanceNotFoundException, ReflectionException, RemoteException;
public ListenerRegistration getListenerRegistry() throws RemoteException;
} |
package gui;
import helpers.DateHelper;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import model.Airport;
import model.Connection;
@SuppressWarnings("serial")
public class EditorWindow extends JFrame implements View, MouseListener {
Vector<Airport> locations;
// Beans
JPanel connectionsContainer;
JList<Airport> locationJList;
public EditorWindow(Vector<Airport> locations) {
this.locations = locations;
}
public void draw() {
super.getContentPane().removeAll(); // making this function being able to repaint the mainwindow
super.setTitle("Bearbeiten");
super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
super.setResizable(false);
super.setLayout(new GridLayout(1, 2, 10, 0));
((JComponent)getContentPane()).setBorder(BorderFactory.createMatteBorder( 4, 4, 4, 4, Color.LIGHT_GRAY ) );
// Build the UI Elems
this.locationJList = new JList<Airport>(this.locations);
this.connectionsContainer = new JPanel();
// Add ActionListening
this.locationJList.addMouseListener(this);
// Add elems to frame
super.getContentPane().add(this.locationJList);
super.getContentPane().add(this.connectionsContainer);
// Do the rest for displaying the window
super.pack();
super.setLocationRelativeTo(null); // center the frame
// Show the window
super.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
// Determine which element was clicked
int elem = this.locations.indexOf(this.locationJList.getSelectedValue());
Airport ap = this.locations.get(elem); // the object of type Airport that has been chosen from the list
// Render Form
this.connectionsContainer.removeAll();
this.connectionsContainer.setLayout(new GridLayout(ap.getConnections().size(), 2));
for(Map.Entry<Airport, Connection> entry : ap.getConnections().entrySet()){
//System.out.print(entry.getKey());
//System.out.print(" -> ");
//System.out.println(entry.getValue().getName());
this.connectionsContainer.add(new JLabel(entry.getKey().getName())); // THIS WILL BECOME A SELECTBOX LATER!!!!
this.connectionsContainer.add(new JTextField(DateHelper.INSTANCE.durationToString(entry.getValue().getDuration())));
}
this.pack();
this.repaint();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} |
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.core;
import java.util.HashMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
import org.apache.commons.math3.stat.descriptive.rank.Percentile.EstimationType;
import org.apache.commons.math3.util.ResizableDoubleArray;
import com.google.common.base.Preconditions;
/**
* Utility class that provides common, generally useful aggregators.
*/
public final class Aggregators {
/**
* Different interpolation methods
*/
public enum Interpolation {
LERP, /* Regular linear interpolation */
ZIM, /* Returns 0 when a data point is missing */
MAX, /* Returns the <type>.MaxValue when a data point is missing */
MIN /* Returns the <type>.MinValue when a data point is missing */
}
/** Aggregator that sums up all the data points. */
public static final Aggregator SUM = new Sum(
Interpolation.LERP, "sum");
/** Aggregator that returns the minimum data point. */
public static final Aggregator MIN = new Min(
Interpolation.LERP, "min");
/** Aggregator that returns the maximum data point. */
public static final Aggregator MAX = new Max(
Interpolation.LERP, "max");
/** Aggregator that returns the average value of the data point. */
public static final Aggregator AVG = new Avg(
Interpolation.LERP, "avg");
/** Aggregator that skips aggregation/interpolation and/or downsampling. */
public static final Aggregator NONE = new None(Interpolation.ZIM, "raw");
/** Return the product of two time series
* @since 2.3 */
public static final Aggregator MULTIPLY = new Multiply(
Interpolation.LERP, "multiply");
/** Aggregator that returns the Standard Deviation of the data points. */
public static final Aggregator DEV = new StdDev(
Interpolation.LERP, "dev");
/** Sums data points but will cause the SpanGroup to return a 0 if timesamps
* don't line up instead of interpolating. */
public static final Aggregator ZIMSUM = new Sum(
Interpolation.ZIM, "zimsum");
/** Returns the minimum data point, causing SpanGroup to set <type>.MaxValue
* if timestamps don't line up instead of interpolating. */
public static final Aggregator MIMMIN = new Min(
Interpolation.MAX, "mimmin");
/** Returns the maximum data point, causing SpanGroup to set <type>.MinValue
* if timestamps don't line up instead of interpolating. */
public static final Aggregator MIMMAX = new Max(
Interpolation.MIN, "mimmax");
/** Aggregator that returns the number of data points.
* WARNING: This currently interpolates with zero-if-missing. In this case
* counts will be off when counting multiple time series. Only use this when
* downsampling until we support NaNs.
* @since 2.2 */
public static final Aggregator COUNT = new Count(Interpolation.ZIM, "count");
/** Aggregator that returns the first data point. */
public static final Aggregator FIRST = new First(Interpolation.ZIM, "first");
/** Aggregator that returns the first data point. */
public static final Aggregator LAST = new Last(Interpolation.ZIM, "last");
/** Maps an aggregator name to its instance. */
private static final HashMap<String, Aggregator> aggregators;
/** Aggregator that returns 99.9th percentile. */
public static final PercentileAgg p999 = new PercentileAgg(99.9d, "p999");
/** Aggregator that returns 99th percentile. */
public static final PercentileAgg p99 = new PercentileAgg(99d, "p99");
/** Aggregator that returns 95th percentile. */
public static final PercentileAgg p95 = new PercentileAgg(95d, "p95");
/** Aggregator that returns 99th percentile. */
public static final PercentileAgg p90 = new PercentileAgg(90d, "p90");
/** Aggregator that returns 75th percentile. */
public static final PercentileAgg p75 = new PercentileAgg(75d, "p75");
/** Aggregator that returns 50th percentile. */
public static final PercentileAgg p50 = new PercentileAgg(50d, "p50");
/** Aggregator that returns estimated 99.9th percentile. */
public static final PercentileAgg ep999r3 =
new PercentileAgg(99.9d, "ep999r3", EstimationType.R_3);
/** Aggregator that returns estimated 99th percentile. */
public static final PercentileAgg ep99r3 =
new PercentileAgg(99d, "ep99r3", EstimationType.R_3);
/** Aggregator that returns estimated 95th percentile. */
public static final PercentileAgg ep95r3 =
new PercentileAgg(95d, "ep95r3", EstimationType.R_3);
/** Aggregator that returns estimated 75th percentile. */
public static final PercentileAgg ep90r3 =
new PercentileAgg(90d, "ep90r3", EstimationType.R_3);
/** Aggregator that returns estimated 50th percentile. */
public static final PercentileAgg ep75r3 =
new PercentileAgg(75d, "ep75r3", EstimationType.R_3);
/** Aggregator that returns estimated 50th percentile. */
public static final PercentileAgg ep50r3 =
new PercentileAgg(50d, "ep50r3", EstimationType.R_3);
/** Aggregator that returns estimated 99.9th percentile. */
public static final PercentileAgg ep999r7 =
new PercentileAgg(99.9d, "ep999r7", EstimationType.R_7);
/** Aggregator that returns estimated 99th percentile. */
public static final PercentileAgg ep99r7 =
new PercentileAgg(99d, "ep99r7", EstimationType.R_7);
/** Aggregator that returns estimated 95th percentile. */
public static final PercentileAgg ep95r7 =
new PercentileAgg(95d, "ep95r7", EstimationType.R_7);
/** Aggregator that returns estimated 75th percentile. */
public static final PercentileAgg ep90r7 =
new PercentileAgg(90d, "ep90r7", EstimationType.R_7);
/** Aggregator that returns estimated 50th percentile. */
public static final PercentileAgg ep75r7 =
new PercentileAgg(75d, "ep75r7", EstimationType.R_7);
/** Aggregator that returns estimated 50th percentile. */
public static final PercentileAgg ep50r7 =
new PercentileAgg(50d, "ep50r7", EstimationType.R_7);
static {
aggregators = new HashMap<String, Aggregator>(8);
aggregators.put("sum", SUM);
aggregators.put("min", MIN);
aggregators.put("max", MAX);
aggregators.put("avg", AVG);
aggregators.put("none", NONE);
aggregators.put("mult", MULTIPLY);
aggregators.put("dev", DEV);
aggregators.put("count", COUNT);
aggregators.put("zimsum", ZIMSUM);
aggregators.put("mimmin", MIMMIN);
aggregators.put("mimmax", MIMMAX);
aggregators.put("first", FIRST);
aggregators.put("last", LAST);
PercentileAgg[] percentiles = {
p999, p99, p95, p90, p75, p50,
ep999r3, ep99r3, ep95r3, ep90r3, ep75r3, ep50r3,
ep999r7, ep99r7, ep95r7, ep90r7, ep75r7, ep50r7
};
for (PercentileAgg agg : percentiles) {
aggregators.put(agg.toString(), agg);
}
}
private Aggregators() {
// Can't create instances of this utility class.
}
/**
* Returns the set of the names that can be used with {@link #get get}.
*/
public static Set<String> set() {
return aggregators.keySet();
}
/**
* Returns the aggregator corresponding to the given name.
* @param name The name of the aggregator to get.
* @throws NoSuchElementException if the given name doesn't exist.
* @see #set
*/
public static Aggregator get(final String name) {
final Aggregator agg = aggregators.get(name);
if (agg != null) {
return agg;
}
throw new NoSuchElementException("No such aggregator: " + name);
}
private static final class Sum extends Aggregator {
public Sum(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(final Longs values) {
long result = values.nextLongValue();
while (values.hasNextValue()) {
result += values.nextLongValue();
}
return result;
}
@Override
public double runDouble(final Doubles values) {
double result = 0.;
long n = 0L;
while (values.hasNextValue()) {
final double val = values.nextDoubleValue();
if (!Double.isNaN(val)) {
result += val;
++n;
}
}
return (0L == n) ? Double.NaN : result;
}
}
private static final class Min extends Aggregator {
public Min(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(final Longs values) {
long min = values.nextLongValue();
while (values.hasNextValue()) {
final long val = values.nextLongValue();
if (val < min) {
min = val;
}
}
return min;
}
@Override
public double runDouble(final Doubles values) {
final double initial = values.nextDoubleValue();
double min = Double.isNaN(initial) ? Double.POSITIVE_INFINITY : initial;
while (values.hasNextValue()) {
final double val = values.nextDoubleValue();
if (!Double.isNaN(val) && val < min) {
min = val;
}
}
return (Double.POSITIVE_INFINITY == min) ? Double.NaN : min;
}
}
private static final class Max extends Aggregator {
public Max(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(final Longs values) {
long max = values.nextLongValue();
while (values.hasNextValue()) {
final long val = values.nextLongValue();
if (val > max) {
max = val;
}
}
return max;
}
@Override
public double runDouble(final Doubles values) {
final double initial = values.nextDoubleValue();
double max = Double.isNaN(initial) ? Double.NEGATIVE_INFINITY : initial;
while (values.hasNextValue()) {
final double val = values.nextDoubleValue();
if (!Double.isNaN(val) && val > max) {
max = val;
}
}
return (Double.NEGATIVE_INFINITY == max) ? Double.NaN : max;
}
}
private static final class Avg extends Aggregator {
public Avg(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(final Longs values) {
long result = values.nextLongValue();
int n = 1;
while (values.hasNextValue()) {
result += values.nextLongValue();
n++;
}
return result / n;
}
@Override
public double runDouble(final Doubles values) {
double result = 0.;
int n = 0;
while (values.hasNextValue()) {
final double val = values.nextDoubleValue();
if (!Double.isNaN(val)) {
result += val;
n++;
}
}
return (0 == n) ? Double.NaN : result / n;
}
}
/**
* An aggregator that isn't meant for aggregation. Paradoxical!!
* Really it's used as a flag to indicate that, during sorting and iteration,
* that the pipeline should not perform any aggregation and should emit
* raw time series.
*/
private static final class None extends Aggregator {
public None(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(final Longs values) {
final long v = values.nextLongValue();
if (values.hasNextValue()) {
throw new IllegalDataException("More than one value in aggregator " + values);
}
return v;
}
@Override
public double runDouble(final Doubles values) {
final double v = values.nextDoubleValue();
if (values.hasNextValue()) {
throw new IllegalDataException("More than one value in aggregator " + values);
}
return v;
}
}
private static final class Multiply extends Aggregator {
public Multiply(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(Longs values) {
long result = values.nextLongValue();
while (values.hasNextValue()) {
result *= values.nextLongValue();
}
return result;
}
@Override
public double runDouble(Doubles values) {
double result = values.nextDoubleValue();
while (values.hasNextValue()) {
result *= values.nextDoubleValue();
}
return result;
}
}
private static final class StdDev extends Aggregator {
public StdDev(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(final Longs values) {
double old_mean = values.nextLongValue();
if (!values.hasNextValue()) {
return 0;
}
long n = 2;
double new_mean = 0.;
double M2 = 0.;
do {
final double x = values.nextLongValue();
new_mean = old_mean + (x - old_mean) / n;
M2 += (x - old_mean) * (x - new_mean);
old_mean = new_mean;
n++;
} while (values.hasNextValue());
return (long) Math.sqrt(M2 / (n - 1));
}
@Override
public double runDouble(final Doubles values) {
// Try to get at least one non-NaN value.
double old_mean = values.nextDoubleValue();
while (Double.isNaN(old_mean) && values.hasNextValue()) {
old_mean = values.nextDoubleValue();
}
if (Double.isNaN(old_mean)) {
// Couldn't find any non-NaN values.
// The stddev of NaNs is NaN.
return Double.NaN;
}
if (!values.hasNextValue()) {
// Only found one non-NaN value.
// The stddev of one value is zero.
return 0.;
}
// If we got here, then we have one non-NaN value, and there are more
// values to aggregate; however, some or all of these values may be NaNs.
long n = 2;
double new_mean = 0.;
// This is not strictly the second central moment (i.e., variance), but
// rather a multiple of it.
double M2 = 0.;
do {
final double x = values.nextDoubleValue();
if (!Double.isNaN(x)) {
new_mean = old_mean + (x - old_mean) / n;
M2 += (x - old_mean) * (x - new_mean);
old_mean = new_mean;
n++;
}
} while (values.hasNextValue());
// If n is still 2, then we never found another non-NaN value; therefore,
// we should return zero.
// Otherwise, we calculate the actual variance, and then we find its
// positive square root, which is the standard deviation.
return (2 == n) ? 0. : Math.sqrt(M2 / (n - 1));
}
}
private static final class Count extends Aggregator {
public Count(final Interpolation method, final String name) {
super(method, name);
}
@Override
public long runLong(Longs values) {
long result = 0;
while (values.hasNextValue()) {
values.nextLongValue();
result++;
}
return result;
}
@Override
public double runDouble(Doubles values) {
double result = 0;
while (values.hasNextValue()) {
final double val = values.nextDoubleValue();
if (!Double.isNaN(val)) {
result++;
}
}
return result;
}
}
private static final class PercentileAgg extends Aggregator {
private final Double percentile;
private final EstimationType estimation;
public PercentileAgg(final Double percentile, final String name) {
this(percentile, name, null);
}
public PercentileAgg(final Double percentile, final String name,
final EstimationType est) {
super(Aggregators.Interpolation.LERP, name);
Preconditions.checkArgument(percentile > 0 && percentile <= 100,
"Invalid percentile value");
this.percentile = percentile;
this.estimation = est;
}
@Override
public long runLong(final Longs values) {
final Percentile percentile =
this.estimation == null
? new Percentile(this.percentile)
: new Percentile(this.percentile).withEstimationType(estimation);
final ResizableDoubleArray local_values = new ResizableDoubleArray();
while(values.hasNextValue()) {
local_values.addElement(values.nextLongValue());
}
percentile.setData(local_values.getElements());
return (long) percentile.evaluate();
}
@Override
public double runDouble(final Doubles values) {
final Percentile percentile = new Percentile(this.percentile);
final ResizableDoubleArray local_values = new ResizableDoubleArray();
int n = 0;
while(values.hasNextValue()) {
final double val = values.nextDoubleValue();
if (!Double.isNaN(val)) {
local_values.addElement(val);
n++;
}
}
if (n > 0) {
percentile.setData(local_values.getElements());
return percentile.evaluate();
} else {
return Double.NaN;
}
}
}
public static final class MovingAverage extends Aggregator {
private LinkedList<SumPoint> list = new LinkedList<SumPoint>();
private final long numPoints;
private final boolean isTimeUnit;
public MovingAverage(final Interpolation method, final String name, long numPoints, boolean isTimeUnit) {
super(method, name);
this.numPoints = numPoints;
this.isTimeUnit = isTimeUnit;
}
public long runLong(final Longs values) {
long sum = values.nextLongValue();
while (values.hasNextValue()) {
sum += values.nextLongValue();
}
if (values instanceof DataPoint) {
long ts = ((DataPoint) values).timestamp();
list.addFirst(new SumPoint(ts, sum));
}
long result = 0;
int count = 0;
Iterator<SumPoint> iter = list.iterator();
SumPoint first = iter.next();
boolean conditionMet = false;
// now sum up the preceeding points
while (iter.hasNext()) {
SumPoint next = iter.next();
result += (Long) next.val;
count++;
if (!isTimeUnit && count >= numPoints) {
conditionMet = true;
break;
} else if (isTimeUnit && ((first.ts - next.ts) > numPoints)) {
conditionMet = true;
break;
}
}
if (!conditionMet || count == 0) {
return 0;
}
return result / count;
}
@Override
public double runDouble(Doubles values) {
double sum = values.nextDoubleValue();
while (values.hasNextValue()) {
sum += values.nextDoubleValue();
}
if (values instanceof DataPoint) {
long ts = ((DataPoint) values).timestamp();
list.addFirst(new SumPoint(ts, sum));
}
double result = 0;
int count = 0;
Iterator<SumPoint> iter = list.iterator();
SumPoint first = iter.next();
boolean conditionMet = false;
// now sum up the preceeding points
while (iter.hasNext()) {
SumPoint next = iter.next();
result += (Double) next.val;
count++;
if (!isTimeUnit && count >= numPoints) {
conditionMet = true;
break;
} else if (isTimeUnit && ((first.ts - next.ts) > numPoints)) {
conditionMet = true;
break;
}
}
if (!conditionMet || count == 0) {
return 0;
}
return result / count;
}
class SumPoint {
long ts;
Object val;
public SumPoint(long ts, Object val) {
this.ts = ts;
this.val = val;
}
}
}
private static final class First extends Aggregator {
public First(final Interpolation method, final String name) {
super(method, name);
}
public long runLong(final Longs values) {
long val = values.nextLongValue();
while (values.hasNextValue()) {
values.nextLongValue();
}
return val;
}
public double runDouble(final Doubles values) {
double val = values.nextDoubleValue();
while (values.hasNextValue()) {
values.nextDoubleValue();
}
return val;
}
}
private static final class Last extends Aggregator {
public Last(final Interpolation method, final String name) {
super(method, name);
}
public long runLong(final Longs values) {
long val = values.nextLongValue();
while (values.hasNextValue()) {
val = values.nextLongValue();
}
return val;
}
public double runDouble(final Doubles values) {
double val = values.nextDoubleValue();
while (values.hasNextValue()) {
val = values.nextDoubleValue();
}
return val;
}
}
} |
package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.maps.MapActivity;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.ui.dialog.Dialogs.ItemWithIcon;
import cgeo.geocaching.utils.ImageUtils;
import rx.functions.Action1;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class CreateShortcutActivity extends AbstractActionBarActivity {
private static class Shortcut implements ItemWithIcon {
private final int titleResourceId;
private final int drawableResourceId;
private final Intent intent;
/**
* shortcut with a separate icon
*/
public Shortcut(final int titleResourceId, final int drawableResourceId, final Intent intent) {
this.titleResourceId = titleResourceId;
this.drawableResourceId = drawableResourceId;
this.intent = intent;
}
@Override
public int getIcon() {
return drawableResourceId;
}
@Override
public String toString() {
return CgeoApplication.getInstance().getString(titleResourceId);
}
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// init
setTheme();
promptForShortcut();
}
private void promptForShortcut() {
final List<Shortcut> shortcuts = new ArrayList<>();
shortcuts.add(new Shortcut(R.string.live_map_button, R.drawable.main_live, new Intent(this, MapActivity.class)));
shortcuts.add(new Shortcut(R.string.caches_nearby_button, R.drawable.main_nearby, CacheListActivity.getNearestIntent(this)));
// TODO: make logging activities ask for cache/trackable when being invoked externally
// shortcuts.add(new Shortcut(R.string.cache_menu_visit, new Intent(this, LogCacheActivity.class)));
// shortcuts.add(new Shortcut(R.string.trackable_log_touch, new Intent(this, LogTrackableActivity.class)));
final Shortcut offlineShortcut = new Shortcut(R.string.stored_caches_button, R.drawable.main_stored, null);
shortcuts.add(offlineShortcut);
shortcuts.add(new Shortcut(R.string.advanced_search_button, R.drawable.main_search, new Intent(this, SearchActivity.class)));
shortcuts.add(new Shortcut(R.string.any_button, R.drawable.main_any, new Intent(this, NavigateAnyPointActivity.class)));
shortcuts.add(new Shortcut(R.string.menu_history, R.drawable.main_stored, CacheListActivity.getHistoryIntent(this)));
Dialogs.select(this, getString(R.string.create_shortcut), shortcuts, new Action1<Shortcut>() {
@Override
public void call(final Shortcut shortcut) {
if (shortcut == offlineShortcut) {
promptForListShortcut();
}
else {
createShortcutAndFinish(shortcut.toString(), shortcut.intent, shortcut.drawableResourceId);
}
}
});
}
protected void promptForListShortcut() {
new StoredList.UserInterface(this).promptForListSelection(R.string.create_shortcut, new Action1<Integer>() {
@Override
public void call(final Integer listId) {
createOfflineListShortcut(listId.intValue());
}
}, true, -1);
}
protected void createOfflineListShortcut(final int listId) {
final StoredList list = DataStore.getList(listId);
if (list == null) {
return;
}
// target to be executed by the shortcut
final Intent targetIntent = new Intent(this, CacheListActivity.class);
targetIntent.putExtra(Intents.EXTRA_LIST_ID, list.id);
// shortcut to be returned
createShortcutAndFinish(list.title, targetIntent, R.drawable.main_stored);
}
private void createShortcutAndFinish(final String title, final Intent targetIntent, final int iconResourceId) {
final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
if (iconResourceId == R.drawable.cgeo) {
final ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(this, iconResourceId);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
}
else {
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, createOverlay(iconResourceId));
}
setResult(RESULT_OK, intent);
// finish activity to return the shortcut
finish();
}
private Bitmap createOverlay(final int drawableResourceId) {
final LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] {
res.getDrawable(drawableResourceId), res.getDrawable(R.drawable.cgeo) });
layerDrawable.setLayerInset(0, 0, 0, 10, 10);
layerDrawable.setLayerInset(1, 50, 50, 0, 0);
return ImageUtils.convertToBitmap(layerDrawable);
}
} |
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquared.maps.BestLocationListener;
import com.joelapenna.foursquared.maps.CityLocationListener;
import com.joelapenna.foursquared.util.DumpcatcherHelper;
import com.joelapenna.foursquared.util.NullDiskCache;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.location.Location;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import java.util.List;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Foursquared extends Application {
private static final String TAG = "Foursquared";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_ACTION_LOGGED_OUT = "com.joelapenna.foursquared.intent.action.LOGGED_OUT";
public static final String EXTRA_VENUE_ID = "com.joelapenna.foursquared.VENUE_ID";
// Common menu items
private static final int MENU_PREFERENCES = -1;
private static final int MENU_GROUP_SYSTEM = 20;
private SharedPreferences mPrefs;
private BestLocationListener mBestLocationListener;
private CityLocationListener mCityLocationListener;
private LocationManager mLocationManager;
private MediaCardStateBroadcastReceiver mMediaCardStateBroadcastReceiver;
private RemoteResourceManager mRemoteResourceManager;
final private Foursquare mFoursquare = new Foursquare(FoursquaredSettings.USE_DEBUG_SERVER);
@Override
public void onCreate() {
Log.i(TAG, "Using Debug Server:\t" + FoursquaredSettings.USE_DEBUG_SERVER);
Log.i(TAG, "Using Dumpcatcher:\t" + FoursquaredSettings.USE_DUMPCATCHER);
Log.i(TAG, "Using Debug Log:\t" + DEBUG);
// Setup Prefs and dumpcatcher (based on prefs)
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
if (FoursquaredSettings.USE_DUMPCATCHER) {
Resources resources = getResources();
new DumpcatcherHelper(Preferences.createUniqueId(mPrefs), resources);
DumpcatcherHelper.sendUsage("Started");
}
// 9/20/2009 - Changed the cache dir names so we wanna clean up after ourselves.
cleanupOldResourceManagers();
// Set up storage cache.
mMediaCardStateBroadcastReceiver = new MediaCardStateBroadcastReceiver();
mMediaCardStateBroadcastReceiver.register();
loadResourceManagers();
// Try logging in and setting up foursquare oauth, then user credentials.
mFoursquare.setOAuthConsumerCredentials(
getResources().getString(R.string.oauth_consumer_key),
getResources().getString(R.string.oauth_consumer_secret));
try {
loadCredentials();
} catch (FoursquareCredentialsException e) {
// We're not doing anything because hopefully our related activities
// will handle the failure. This is simply convenience.
}
// Construct the listener we'll use for tight location updates and start listening for city
// location.
mBestLocationListener = new BestLocationListener();
mCityLocationListener = new CityLocationListener(mFoursquare, mPrefs);
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
CityLocationListener.LOCATION_UPDATE_MIN_TIME,
CityLocationListener.LOCATION_UPDATE_MIN_DISTANCE, mCityLocationListener);
}
@Override
public void onTerminate() {
mRemoteResourceManager.shutdown();
mLocationManager.removeUpdates(mCityLocationListener);
mLocationManager.removeUpdates(mBestLocationListener);
}
public Foursquare getFoursquare() {
return mFoursquare;
}
public Location getLastKnownLocation() {
primeLocationListener();
return mBestLocationListener.getLastKnownLocation();
}
public BestLocationListener getLocationListener() {
primeLocationListener();
return mBestLocationListener;
}
public RemoteResourceManager getRemoteResourceManager() {
return mRemoteResourceManager;
}
private void loadCredentials() throws FoursquareCredentialsException {
if (FoursquaredSettings.DEBUG) Log.d(TAG, "loadCredentials()");
String phoneNumber = mPrefs.getString(Preferences.PREFERENCE_PHONE, null);
String password = mPrefs.getString(Preferences.PREFERENCE_PASSWORD, null);
String oauthToken = mPrefs.getString(Preferences.PREFERENCE_OAUTH_TOKEN, null);
String oauthTokenSecret = mPrefs.getString(Preferences.PREFERENCE_OAUTH_TOKEN_SECRET, null);
if (TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(password)
|| TextUtils.isEmpty(oauthToken) || TextUtils.isEmpty(oauthTokenSecret)) {
throw new FoursquareCredentialsException(
"Phone number or password not set in preferences.");
}
mFoursquare.setCredentials(phoneNumber, password);
mFoursquare.setOAuthToken(oauthToken, oauthTokenSecret);
}
private void loadResourceManagers() {
// at least have some sort of disk cache so that things don't npe when trying to access the
// resource managers.
try {
if (DEBUG) Log.d(TAG, "Attempting to load RemoteResourceManager(cache)");
mRemoteResourceManager = new RemoteResourceManager("cache");
} catch (IllegalStateException e) {
if (DEBUG) Log.d(TAG, "Falling back to NullDiskCache for RemoteResourceManager");
mRemoteResourceManager = new RemoteResourceManager(new NullDiskCache());
}
}
private void primeLocationListener() {
LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = null;
List<String> providers = manager.getProviders(true);
int providersCount = providers.size();
for (int i = 0; i < providersCount; i++) {
location = manager.getLastKnownLocation(providers.get(i));
mBestLocationListener.getBetterLocation(location);
}
}
public static void addPreferencesToMenu(Context context, Menu menu) {
Intent intent = new Intent(context, PreferenceActivity.class);
menu.add(MENU_GROUP_SYSTEM, MENU_PREFERENCES, Menu.CATEGORY_SECONDARY,
R.string.preferences_label)
.setIcon(android.R.drawable.ic_menu_preferences).setIntent(intent);
}
public static void cleanupOldResourceManagers() {
if (DEBUG) Log.d(TAG, "cleaning up old resource managers.");
try {
new RemoteResourceManager("badges").clear();
new RemoteResourceManager("user_photos").clear();
} catch (IllegalStateException e) {
// Its okay if we catch this, it just likely means that the RRM can't be constructed
// because the sd card isn't mounted.
}
}
/**
* Set up resource managers on the application depending on SD card state.
*
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class MediaCardStateBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "Media state changed, reloading resource managers:"
+ intent.getAction());
if (Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())) {
getRemoteResourceManager().shutdown();
loadResourceManagers();
} else if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) {
loadResourceManagers();
}
}
public void register() {
// Register our media card broadcast receiver so we can enable/disable the cache as
// appropriate.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
// intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
// intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);
// intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
// intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
// intentFilter.addAction(Intent.ACTION_MEDIA_NOFS);
// intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
// intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addDataScheme("file");
registerReceiver(mMediaCardStateBroadcastReceiver, intentFilter);
}
}
} |
package net.oneandone.stool.ssl;
import net.oneandone.sushi.fs.World;
import net.oneandone.sushi.fs.file.FileNode;
import net.oneandone.sushi.fs.http.HttpFilesystem;
import net.oneandone.sushi.fs.http.HttpNode;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
public class Itca {
public static final String HOSTNAME = "itca.server.lan";
public static final String URL_PREFIX = "https://" + HOSTNAME + "/cgi-bin/cert.cgi?action=create%20certificate&cert-commonName=";
public static Pair create(FileNode workDir, String hostname) throws IOException {
Pair pair;
pair = newPair(workDir, hostname);
if (!(pair.privateKey().exists() || pair.certificate().exists())) {
download(workDir, URL_PREFIX + hostname);
}
return pair;
}
private static Pair newPair(FileNode workDir, String hostname) {
FileNode crt, key;
crt = workDir.join(hostname.replace("*", "_") + ".crt");
key = workDir.join(hostname.replace("*", "_") + ".key");
return new Pair(key, crt);
}
public static void download(FileNode workDir, String url) throws IOException {
FileNode zip;
World world;
HttpNode itca;
byte[] bytes;
world = workDir.getWorld();
((HttpFilesystem) world.getFilesystem("https")).setSocketFactorySelector((protocol, hostname) ->
protocol.equals("https") ? (hostname.equals(HOSTNAME) ? lazyFactory() : SSLSocketFactory.getDefault()) : null );
zip = world.getTemp().createTempFile();
itca = (HttpNode) world.validNode(url);
bytes = itca.readBytes();
zip.writeBytes(bytes);
zip.unzip(workDir);
}
public static SSLSocketFactory lazyFactory() {
TrustManager[] trustAllCerts;
SSLContext sc;
trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
try {
sc = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
try {
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (KeyManagementException e) {
throw new IllegalArgumentException(e);
}
return sc.getSocketFactory();
}
} |
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// Modifications by Arthur Edelstein, Nico Stuurman
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import java.util.Timer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.event.AncestorEvent;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.Metadata;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.api.ImageCache;
import org.micromanager.api.ImageCacheListener;
import org.micromanager.acquisition.MMImageCache;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.Autofocus;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.conf2.ConfiguratorDlg2;
import org.micromanager.conf.ConfiguratorDlg;
import org.micromanager.conf.MMConfigFileException;
import org.micromanager.conf.MicroscopeModel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.PositionList;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.TooltipTextMaker;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.process.FloatProcessor;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.event.AncestorListener;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.micromanager.acquisition.AcquisitionVirtualStack;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import org.micromanager.acquisition.LiveModeTimer;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.MetadataPanel;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.VirtualAcquisitionDisplay;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.utils.ImageFocusListener;
import org.micromanager.api.Pipeline;
import org.micromanager.api.TaggedImageStorage;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.HotKeysDialog;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.ReportingUtils;
import org.micromanager.utils.SnapLiveContrastSettings;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements ScriptInterface, DeviceControlGUI {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4";
private static final String VERSION = "1.4.7 20111110";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton toggleButtonLive_;
private JButton toAlbumButton_;
private JCheckBox autoShutterCheckBox_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton buttonSnap_;
private JButton buttonAutofocus_;
private JButton buttonAutofocusTools_;
private JToggleButton toggleButtonShutter_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ReportProblemDialog reportProblemDialog_;
private JMenu pluginMenu_;
private ArrayList<PluginItem> plugins_;
private List<MMListenerInterface> MMListeners_
= (List<MMListenerInterface>)
Collections.synchronizedList(new ArrayList<MMListenerInterface>());
private List<Component> MMFrames_
= (List<Component>)
Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private LiveModeTimer liveModeTimer_;
private GraphData lineProfileData_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
private Preferences colorPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private ScriptPanel scriptPanel_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static VirtualAcquisitionDisplay simpleDisplay_;
private SnapLiveContrastSettings simpleContrastSettings_;
private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};
private int snapCount_ = -1;
private boolean liveModeSuspended_;
public Font defaultScriptFont_ = null;
public static final String SIMPLE_ACQ = "Snap/Live Window";
public static FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final JMenu switchConfigurationMenu_;
private final MetadataPanel metadataPanel_;
public static FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread pipelineClassLoadingThread_ = null;
private Class pipelineClass_ = null;
private Pipeline acquirePipeline_ = null;
private final JSplitPane splitPane_;
private volatile boolean ignorePropertyChanges_;
public static AtomicBoolean seriousErrorReported_ = new AtomicBoolean(false);
public ImageWindow getImageWin() {
return simpleDisplay_.getHyperImage().getWindow();
}
public static VirtualAcquisitionDisplay getSimpleDisplay() {
return simpleDisplay_;
}
public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException {
simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name);
}
public void checkSimpleAcquisition() {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
int width = (int) core_.getImageWidth();
int height = (int) core_.getImageHeight();
int depth = (int) core_.getBytesPerPixel();
int bitDepth = (int) core_.getImageBitDepth();
int numCamChannels = (int) core_.getNumberOfCameraChannels();
try {
if (acquisitionExists(SIMPLE_ACQ)) {
if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)
|| (getAcquisitionImageHeight(SIMPLE_ACQ) != height)
|| (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)
|| (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)
|| (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window
closeAcquisitionImage5D(SIMPLE_ACQ);
closeAcquisition(SIMPLE_ACQ);
}
}
if (!acquisitionExists(SIMPLE_ACQ)) {
openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true);
if (numCamChannels > 1) {
for (long i = 0; i < numCamChannels; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();
setChannelColor(SIMPLE_ACQ, (int) i,
getChannelColor(chName, defaultColor));
setChannelName(SIMPLE_ACQ, (int) i, chName);
}
}
initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);
getAcquisition(SIMPLE_ACQ).promptToSave(false);
getAcquisition(SIMPLE_ACQ).toFront();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void checkSimpleAcquisition(TaggedImage image) {
try {
JSONObject tags = image.tags;
int width = MDUtils.getWidth(tags);
int height = MDUtils.getHeight(tags);
int depth = MDUtils.getDepth(tags);
int bitDepth = MDUtils.getBitDepth(tags);
int numCamChannels = (int) core_.getNumberOfCameraChannels();
if (acquisitionExists(SIMPLE_ACQ)) {
if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)
|| (getAcquisitionImageHeight(SIMPLE_ACQ) != height)
|| (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)
|| (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)
|| (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window
closeAcquisitionImage5D(SIMPLE_ACQ);
closeAcquisition(SIMPLE_ACQ);
}
}
if (!acquisitionExists(SIMPLE_ACQ)) {
openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true);
if (numCamChannels > 1) {
for (long i = 0; i < numCamChannels; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();
setChannelColor(SIMPLE_ACQ, (int) i,
getChannelColor(chName, defaultColor));
setChannelName(SIMPLE_ACQ, (int) i, chName);
}
}
initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);
getAcquisition(SIMPLE_ACQ).promptToSave(false);
getAcquisition(SIMPLE_ACQ).toFront();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void saveSimpleContrastSettings(ContrastSettings c, int channel, String pixelType) {
simpleContrastSettings_.saveSettings(c, channel, pixelType);
}
public ContrastSettings loadSimpleContrastSettigns(String pixelType, int channel) {
try {
return simpleContrastSettings_.loadSettings(pixelType, channel);
} catch (MMException ex) {
ReportingUtils.logError(ex);
return null;
}
}
public void saveChannelColor(String chName, int rgb)
{
if (colorPrefs_ != null) {
colorPrefs_.putInt("Color_" + chName, rgb);
}
}
public Color getChannelColor(String chName, int defaultColor)
{
if (colorPrefs_ != null) {
defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor);
}
return new Color(defaultColor);
}
private void initializeHelpMenu() {
// add help menu item
final JMenu helpMenu = new JMenu();
helpMenu.setText("Help");
menuBar_.add(helpMenu);
final JMenuItem usersGuideMenuItem = new JMenuItem();
usersGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_User%27s_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
usersGuideMenuItem.setText("User's Guide...");
helpMenu.add(usersGuideMenuItem);
final JMenuItem configGuideMenuItem = new JMenuItem();
configGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_Configuration_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
configGuideMenuItem.setText("Configuration Guide...");
helpMenu.add(configGuideMenuItem);
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
final JMenuItem registerMenuItem = new JMenuItem();
registerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
registerMenuItem.setText("Register your copy of Micro-Manager...");
helpMenu.add(registerMenuItem);
}
final MMStudioMainFrame thisFrame = this;
final JMenuItem reportProblemMenuItem = new JMenuItem();
reportProblemMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (null == reportProblemDialog_) {
reportProblemDialog_ = new ReportProblemDialog(core_, thisFrame, options_);
thisFrame.addMMBackgroundListener(reportProblemDialog_);
reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_));
}
reportProblemDialog_.setVisible(true);
}
});
reportProblemMenuItem.setText("Report Problem");
helpMenu.add(reportProblemMenuItem);
final JMenuItem aboutMenuItem = new JMenuItem();
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + VERSION;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
aboutMenuItem.setText("About Micromanager...");
helpMenu.add(aboutMenuItem);
menuBar_.validate();
}
private void updateSwitchConfigurationMenu() {
switchConfigurationMenu_.removeAll();
for (final String configFile : MRUConfigFiles_) {
if (! configFile.equals(sysConfigFile_)) {
JMenuItem configMenuItem = new JMenuItem();
configMenuItem.setText(configFile);
configMenuItem.addActionListener(new ActionListener() {
String theConfigFile = configFile;
public void actionPerformed(ActionEvent e) {
sysConfigFile_ = theConfigFile;
loadSystemConfiguration();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
}
});
switchConfigurationMenu_.add(configMenuItem);
}
}
}
/**
* Allows MMListeners to register themselves
*/
public void addMMListener(MMListenerInterface newL) {
if (MMListeners_.contains(newL))
return;
MMListeners_.add(newL);
}
/**
* Allows MMListeners to remove themselves
*/
public void removeMMListener(MMListenerInterface oldL) {
if (!MMListeners_.contains(oldL))
return;
MMListeners_.remove(oldL);
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated
*/
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
*/
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
/**
* Part of ScriptInterface
* Manipulate acquisition so that it looks like a burst
*/
public void runBurstAcquisition() throws MMScriptException {
double interval = engine_.getFrameIntervalMs();
int nr = engine_.getNumFrames();
boolean doZStack = engine_.isZSliceSettingEnabled();
boolean doChannels = engine_.isChannelsSettingEnabled();
engine_.enableZSliceSetting(false);
engine_.setFrames(nr, 0);
engine_.enableChannelsSetting(false);
try {
engine_.acquire();
} catch (MMException e) {
throw new MMScriptException(e);
}
engine_.setFrames(nr, interval);
engine_.enableZSliceSetting(doZStack);
engine_.enableChannelsSetting(doChannels);
}
public void runBurstAcquisition(int nr) throws MMScriptException {
int originalNr = engine_.getNumFrames();
double interval = engine_.getFrameIntervalMs();
engine_.setFrames(nr, 0);
this.runBurstAcquisition();
engine_.setFrames(originalNr, interval);
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
//String originalName = engine_.getDirName();
String originalRoot = engine_.getRootName();
engine_.setDirName(name);
engine_.setRootName(root);
this.runBurstAcquisition(nr);
engine_.setRootName(originalRoot);
//engine_.setDirName(originalDirName);
}
public void logStartupProperties() {
core_.enableDebugLog(options_.debugLogEnabled_);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
core_.logMessage("JVM: " + System.getProperty("java.vm.name") + ", version " + System.getProperty("java.version") + "; " + System.getProperty("sun.arch.data.model") + " bit");
}
/**
* @deprecated
* @throws MMScriptException
*/
public void startBurstAcquisition() throws MMScriptException {
runAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
private void startLoadingPipelineClass() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
pipelineClassLoadingThread_ = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
pipelineClass_ = Class.forName("org.micromanager.AcqEngine");
} catch (Exception ex) {
ReportingUtils.logError(ex);
pipelineClass_ = null;
}
}
};
pipelineClassLoadingThread_.start();
}
public void addImageStorageListener(ImageCacheListener listener) {
throw new UnsupportedOperationException("Not supported yet.");
}
public ImageCache getAcquisitionImageCache(String acquisitionName) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
@Override
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!");
} else {
if (ignorePropertyChanges_) {
core_.logMessage("Notification from MMCore ignored since the system is still loading");
} else {
core_.updateSystemStateCache();
updateGUI(true);
// update all registered listeners
for (MMListenerInterface mmIntf : MMListeners_) {
mmIntf.propertiesChangedAlert();
}
core_.logMessage("Notification from MMCore!");
}
}
}
@Override
public void onPropertyChanged(String deviceName, String propName, String propValue) {
core_.logMessage("Notification for Device: " + deviceName + " Property: " +
propName + " changed to value: " + propValue);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertyChangedAlert(deviceName, propName, propValue);
}
}
@Override
public void onConfigGroupChanged(String groupName, String newConfig) {
try {
configPad_.refreshGroup(groupName, newConfig);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.configGroupChangedAlert(groupName, newConfig);
}
} catch (Exception e) {
}
}
@Override
public void onPixelSizeChanged(double newPixelSizeUm) {
updatePixSizeUm (newPixelSizeUm);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.pixelSizeChangedAlert(newPixelSizeUm);
}
}
@Override
public void onStagePositionChanged(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_)) {
updateZPos(pos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.stagePositionChangedAlert(deviceName, pos);
}
}
}
@Override
public void onStagePositionChangedRelative(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPosRelative(pos);
}
@Override
public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_)) {
updateXYPos(xPos, yPos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);
}
}
}
@Override
public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPosRelative(xPos, yPos);
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
public MMStudioMainFrame(boolean pluginStatus) {
super();
startLoadingPipelineClass();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
acqMgr_ = new AcquisitionManager();
simpleContrastSettings_ = new SnapLiveContrastSettings();
sysConfigFile_ = System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME;
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = System.getProperty("user.dir") + "/"
+ options_.startupScript_;
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
AcqControlDlg.COLOR_SETTINGS_NODE);
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 482);
int dividerPos = mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 178);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);
setBounds(x, y, width, height);
setExitStrategy(options_.closeOnExit_);
setTitle(MICRO_MANAGER_TITLE);
setBackground(guiColors_.background.get((options_.displayBackground_)));
SpringLayout topLayout = new SpringLayout();
this.setMinimumSize(new Dimension(605,480));
JPanel topPanel = new JPanel();
topPanel.setLayout(topLayout);
topPanel.setMinimumSize(new Dimension(580, 195));
class ListeningJPanel extends JPanel implements AncestorListener {
public void ancestorMoved(AncestorEvent event) {
//System.out.println("moved!");
}
public void ancestorRemoved(AncestorEvent event) {}
public void ancestorAdded(AncestorEvent event) {}
}
ListeningJPanel bottomPanel = new ListeningJPanel();
bottomPanel.setLayout(topLayout);
splitPane_ = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane_.setBorder(BorderFactory.createEmptyBorder());
splitPane_.setDividerLocation(dividerPos);
splitPane_.setResizeWeight(0.0);
splitPane_.addAncestorListener(bottomPanel);
getContentPane().add(splitPane_);
// Snap button
buttonSnap_ = new JButton();
buttonSnap_.setIconTextGap(6);
buttonSnap_.setText("Snap");
buttonSnap_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/camera.png"));
buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonSnap_.setToolTipText("Snap single image");
buttonSnap_.setMaximumSize(new Dimension(0, 0));
buttonSnap_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSnap();
}
});
topPanel.add(buttonSnap_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonSnap_, 4,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonSnap_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonSnap_, 7,
SpringLayout.WEST, topPanel);
// Initialize
// Exposure field
final JLabel label_1 = new JLabel();
label_1.setFont(new Font("Arial", Font.PLAIN, 10));
label_1.setText("Exposure [ms]");
topPanel.add(label_1);
topLayout.putConstraint(SpringLayout.EAST, label_1, 198,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, label_1, 111,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, label_1, 39,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, label_1, 23,
SpringLayout.NORTH, topPanel);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
synchronized(shutdownLock_) {
if (core_ != null)
setExposure();
}
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
topPanel.add(textFieldExp_);
topLayout.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, textFieldExp_, 21,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, textFieldExp_, 276,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, textFieldExp_, 203,
SpringLayout.WEST, topPanel);
// Live button
toggleButtonLive_ = new JToggleButton();
toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2));
toggleButtonLive_.setIconTextGap(1);
toggleButtonLive_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setIconTextGap(6);
toggleButtonLive_.setToolTipText("Continuous live view");
toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10));
toggleButtonLive_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enableLiveMode(!isLiveModeOn());
}
});
toggleButtonLive_.setText("Live");
topPanel.add(toggleButtonLive_);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7,
SpringLayout.WEST, topPanel);
// Acquire button
toAlbumButton_ = new JButton();
toAlbumButton_.setMargin(new Insets(2, 2, 2, 2));
toAlbumButton_.setIconTextGap(1);
toAlbumButton_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/camera_plus_arrow.png"));
toAlbumButton_.setIconTextGap(6);
toAlbumButton_.setToolTipText("Acquire single frame and add to an album");
toAlbumButton_.setFont(new Font("Arial", Font.PLAIN, 10));
toAlbumButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snapAndAddToImage5D();
}
});
toAlbumButton_.setText("Album");
topPanel.add(toAlbumButton_);
topLayout.putConstraint(SpringLayout.SOUTH, toAlbumButton_, 69,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toAlbumButton_, 48,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, toAlbumButton_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toAlbumButton_, 7,
SpringLayout.WEST, topPanel);
// Shutter button
toggleButtonShutter_ = new JToggleButton();
toggleButtonShutter_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
toggleShutter();
}
});
toggleButtonShutter_.setToolTipText("Open/close the shutter");
toggleButtonShutter_.setIconTextGap(6);
toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10));
toggleButtonShutter_.setText("Open");
topPanel.add(toggleButtonShutter_);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonShutter_,
275, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonShutter_,
203, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_,
138 - 21, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonShutter_,
117 - 21, SpringLayout.NORTH, topPanel);
// Active shutter label
final JLabel activeShutterLabel = new JLabel();
activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10));
activeShutterLabel.setText("Shutter");
topPanel.add(activeShutterLabel);
topLayout.putConstraint(SpringLayout.SOUTH, activeShutterLabel,
108 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, activeShutterLabel,
95 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, activeShutterLabel,
160 - 2, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, activeShutterLabel,
113 - 2, SpringLayout.WEST, topPanel);
// Active shutter Combo Box
shutterComboBox_ = new JComboBox();
shutterComboBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return;
}
});
topPanel.add(shutterComboBox_);
topLayout.putConstraint(SpringLayout.SOUTH, shutterComboBox_,
114 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, shutterComboBox_,
92 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, shutterComboBox_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, shutterComboBox_, 170,
SpringLayout.WEST, topPanel);
menuBar_ = new JMenuBar();
setJMenuBar(menuBar_);
final JMenu fileMenu = new JMenu();
fileMenu.setText("File");
menuBar_.add(fileMenu);
final JMenuItem openMenuItem = new JMenuItem();
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
openAcquisitionData();
}
}.start();
}
});
openMenuItem.setText("Open Acquisition Data...");
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
final JMenuItem loadState = new JMenuItem();
loadState.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemState();
}
});
loadState.setText("Load System State...");
fileMenu.add(loadState);
final JMenuItem saveStateAs = new JMenuItem();
fileMenu.add(saveStateAs);
saveStateAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSystemState();
}
});
saveStateAs.setText("Save System State As...");
fileMenu.addSeparator();
final JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeSequence();
}
});
fileMenu.add(exitMenuItem);
exitMenuItem.setText("Exit");
/*
final JMenu image5dMenu = new JMenu();
image5dMenu.setText("Image5D");
menuBar_.add(image5dMenu);
final JMenuItem closeAllMenuItem = new JMenuItem();
closeAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
WindowManager.closeAllWindows();
}
});
closeAllMenuItem.setText("Close All");
image5dMenu.add(closeAllMenuItem);
final JMenuItem duplicateMenuItem = new JMenuItem();
duplicateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Duplicate_Image5D duplicate = new Duplicate_Image5D();
duplicate.run("");
}
});
duplicateMenuItem.setText("Duplicate");
image5dMenu.add(duplicateMenuItem);
final JMenuItem cropMenuItem = new JMenuItem();
cropMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Crop_Image5D crop = new Crop_Image5D();
crop.run("");
}
});
cropMenuItem.setText("Crop");
image5dMenu.add(cropMenuItem);
final JMenuItem makeMontageMenuItem = new JMenuItem();
makeMontageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Make_Montage makeMontage = new Make_Montage();
makeMontage.run("");
}
});
makeMontageMenuItem.setText("Make Montage");
image5dMenu.add(makeMontageMenuItem);
final JMenuItem zProjectMenuItem = new JMenuItem();
zProjectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Z_Project projection = new Z_Project();
projection.run("");
}
});
zProjectMenuItem.setText("Z Project");
image5dMenu.add(zProjectMenuItem);
final JMenuItem convertToRgbMenuItem = new JMenuItem();
convertToRgbMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB();
stackToRGB.run("");
}
});
convertToRgbMenuItem.setText("Copy to RGB Stack(z)");
image5dMenu.add(convertToRgbMenuItem);
final JMenuItem convertToRgbtMenuItem = new JMenuItem();
convertToRgbtMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t();
stackToRGB_t.run("");
}
});
convertToRgbtMenuItem.setText("Copy to RGB Stack(t)");
image5dMenu.add(convertToRgbtMenuItem);
final JMenuItem convertToStackMenuItem = new JMenuItem();
convertToStackMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_Stack image5DToStack = new Image5D_to_Stack();
image5DToStack.run("");
}
});
convertToStackMenuItem.setText("Copy to Stack");
image5dMenu.add(convertToStackMenuItem);
final JMenuItem convertToStacksMenuItem = new JMenuItem();
convertToStacksMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks();
image5DToStacks.run("");
}
});
convertToStacksMenuItem.setText("Copy to Stacks (channels)");
image5dMenu.add(convertToStacksMenuItem);
final JMenuItem volumeViewerMenuItem = new JMenuItem();
volumeViewerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer();
volumeViewer.run("");
}
});
volumeViewerMenuItem.setText("VolumeViewer");
image5dMenu.add(volumeViewerMenuItem);
final JMenuItem splitImageMenuItem = new JMenuItem();
splitImageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Split_Image5D splitImage = new Split_Image5D();
splitImage.run("");
}
});
splitImageMenuItem.setText("SplitView");
image5dMenu.add(splitImageMenuItem);
*/
final JMenu toolsMenu = new JMenu();
toolsMenu.setText("Tools");
menuBar_.add(toolsMenu);
final JMenuItem refreshMenuItem = new JMenuItem();
refreshMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/arrow_refresh.png"));
refreshMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshMenuItem.setText("Refresh GUI");
refreshMenuItem.setToolTipText("Refresh all GUI controls directly from the hardware");
toolsMenu.add(refreshMenuItem);
final JMenuItem rebuildGuiMenuItem = new JMenuItem();
rebuildGuiMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initializeGUI();
core_.updateSystemStateCache();
}
});
rebuildGuiMenuItem.setText("Rebuild GUI");
rebuildGuiMenuItem.setToolTipText("Regenerate micromanager user interface");
toolsMenu.add(rebuildGuiMenuItem);
toolsMenu.addSeparator();
final JMenuItem scriptPanelMenuItem = new JMenuItem();
toolsMenu.add(scriptPanelMenuItem);
scriptPanelMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scriptPanel_.setVisible(true);
}
});
scriptPanelMenuItem.setText("Script Panel...");
scriptPanelMenuItem.setToolTipText("Open micromanager script editor window");
final JMenuItem hotKeysMenuItem = new JMenuItem();
toolsMenu.add(hotKeysMenuItem);
hotKeysMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
HotKeysDialog hk = new HotKeysDialog
(guiColors_.background.get((options_.displayBackground_)));
//hk.setBackground(guiColors_.background.get((options_.displayBackground_)));
}
});
hotKeysMenuItem.setText("Shortcuts...");
hotKeysMenuItem.setToolTipText("Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts");
final JMenuItem propertyEditorMenuItem = new JMenuItem();
toolsMenu.add(propertyEditorMenuItem);
propertyEditorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createPropertyEditor();
}
});
propertyEditorMenuItem.setText("Device/Property Browser...");
propertyEditorMenuItem.setToolTipText("Open new window to view and edit property values in current configuration");
toolsMenu.addSeparator();
final JMenuItem xyListMenuItem = new JMenuItem();
xyListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showXYPositionList();
}
});
xyListMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/application_view_list.png"));
xyListMenuItem.setText("XY List...");
toolsMenu.add(xyListMenuItem);
xyListMenuItem.setToolTipText("Open position list manager window");
final JMenuItem acquisitionMenuItem = new JMenuItem();
acquisitionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
acquisitionMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/film.png"));
acquisitionMenuItem.setText("Multi-Dimensional Acquisition...");
toolsMenu.add(acquisitionMenuItem);
acquisitionMenuItem.setToolTipText("Open multi-dimensional acquisition window");
/*
final JMenuItem splitViewMenuItem = new JMenuItem();
splitViewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitViewDialog();
}
});
splitViewMenuItem.setText("Split View...");
toolsMenu.add(splitViewMenuItem);
*/
centerAndDragMenuItem_ = new JCheckBoxMenuItem();
centerAndDragMenuItem_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (centerAndDragListener_ == null) {
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
}
if (!centerAndDragListener_.isRunning()) {
centerAndDragListener_.start();
centerAndDragMenuItem_.setSelected(true);
} else {
centerAndDragListener_.stop();
centerAndDragMenuItem_.setSelected(false);
}
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
});
centerAndDragMenuItem_.setText("Mouse Moves Stage");
centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
centerAndDragMenuItem_.setToolTipText("When enabled, double clicking in live window moves stage");
toolsMenu.add(centerAndDragMenuItem_);
final JMenuItem calibrationMenuItem = new JMenuItem();
toolsMenu.add(calibrationMenuItem);
calibrationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createCalibrationListDlg();
}
});
calibrationMenuItem.setText("Pixel Size Calibration...");
toolsMenu.add(calibrationMenuItem);
String calibrationTooltip = "Define size calibrations specific to each objective lens. " +
"When the objective in use has a calibration defined, " +
"micromanager will automatically use it when " +
"calculating metadata";
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
calibrationMenuItem.setToolTipText(calibrationTooltip);
else
calibrationMenuItem.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(calibrationTooltip));
toolsMenu.addSeparator();
final JMenuItem configuratorMenuItem = new JMenuItem();
configuratorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// true - new wizard
// false - old wizard
runHardwareWizard(true);
}
});
configuratorMenuItem.setText("Hardware Configuration Wizard...");
toolsMenu.add(configuratorMenuItem);
configuratorMenuItem.setToolTipText("Open wizard to create new hardware configuration");
final JMenuItem loadSystemConfigMenuItem = new JMenuItem();
toolsMenu.add(loadSystemConfigMenuItem);
loadSystemConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadConfiguration();
initializeGUI();
}
});
loadSystemConfigMenuItem.setText("Load Hardware Configuration...");
loadSystemConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize new one");
switchConfigurationMenu_ = new JMenu();
for (int i=0; i<5; i++)
{
JMenuItem configItem = new JMenuItem();
configItem.setText(Integer.toString(i));
switchConfigurationMenu_.add(configItem);
}
final JMenuItem reloadConfigMenuItem = new JMenuItem();
toolsMenu.add(reloadConfigMenuItem);
reloadConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemConfiguration();
initializeGUI();
}
});
reloadConfigMenuItem.setText("Reload Hardware Configuration");
reloadConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize most recently loaded configuration");
switchConfigurationMenu_.setText("Switch Hardware Configuration");
toolsMenu.add(switchConfigurationMenu_);
switchConfigurationMenu_.setToolTipText("Switch between recently used configurations");
final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem();
saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
updateChannelCombos();
}
});
saveConfigurationPresetsMenuItem.setText("Save Configuration Settings as...");
toolsMenu.add(saveConfigurationPresetsMenuItem);
saveConfigurationPresetsMenuItem.setToolTipText("Save current configuration settings as new configuration file");
/*
final JMenuItem regenerateConfiguratorDeviceListMenuItem = new JMenuItem();
regenerateConfiguratorDeviceListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(options_.enableDeviceDiscovery_, resultFile,core_);
setCursor(oldc);
}
});
regenerateConfiguratorDeviceListMenuItem.setText("Regenerate Configurator Device List");
toolsMenu.add(regenerateConfiguratorDeviceListMenuItem);
*/
toolsMenu.addSeparator();
final MMStudioMainFrame thisInstance = this;
final JMenuItem optionsMenuItem = new JMenuItem();
optionsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
int oldBufsize = options_.circularBufferSizeMB_;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance, sysConfigFile_);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB_) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
optionsMenuItem.setText("Options...");
toolsMenu.add(optionsMenuItem);
final JLabel binningLabel = new JLabel();
binningLabel.setFont(new Font("Arial", Font.PLAIN, 10));
binningLabel.setText("Binning");
topPanel.add(binningLabel);
topLayout.putConstraint(SpringLayout.SOUTH, binningLabel, 64,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, binningLabel, 43,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1,
SpringLayout.WEST, topPanel);
metadataPanel_ = new MetadataPanel();
bottomPanel.add(metadataPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, metadataPanel_, 0,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, metadataPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, metadataPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, metadataPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_.setBorder(BorderFactory.createEmptyBorder());
comboBinning_ = new JComboBox();
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
topPanel.add(comboBinning_);
topLayout.putConstraint(SpringLayout.EAST, comboBinning_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, comboBinning_, 200,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, comboBinning_, 66,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, comboBinning_, 43,
SpringLayout.NORTH, topPanel);
final JLabel cameraSettingsLabel = new JLabel();
cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11));
cameraSettingsLabel.setText("Camera settings");
topPanel.add(cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, cameraSettingsLabel,
211, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.WEST, cameraSettingsLabel,
109, SpringLayout.WEST, topPanel);
labelImageDimensions_ = new JLabel();
labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(labelImageDimensions_);
topLayout.putConstraint(SpringLayout.SOUTH, labelImageDimensions_,
0, SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, labelImageDimensions_,
-20, SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, labelImageDimensions_,
0, SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, labelImageDimensions_,
5, SpringLayout.WEST, topPanel);
configPad_ = new ConfigGroupPad();
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance());
configPad_.setFont(new Font("", Font.PLAIN, 10));
topPanel.add(configPad_);
topLayout.putConstraint(SpringLayout.EAST, configPad_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPad_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPad_, -4,
SpringLayout.NORTH, configPadButtonPanel_);
topLayout.putConstraint(SpringLayout.NORTH, configPad_, 21,
SpringLayout.NORTH, topPanel);
topPanel.add(configPadButtonPanel_);
topLayout.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, -40,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, -20,
SpringLayout.SOUTH, topPanel);
final JLabel stateDeviceLabel = new JLabel();
stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11));
stateDeviceLabel.setText("Configuration settings");
topPanel.add(stateDeviceLabel);
topLayout.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0,
SpringLayout.SOUTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0,
SpringLayout.NORTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150,
SpringLayout.WEST, configPad_);
topLayout.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0,
SpringLayout.WEST, configPad_);
final JButton buttonAcqSetup = new JButton();
buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2));
buttonAcqSetup.setIconTextGap(1);
buttonAcqSetup.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/film.png"));
buttonAcqSetup.setToolTipText("Open multi-dimensional acquisition window");
buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAcqSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
buttonAcqSetup.setText("Multi-D Acq.");
topPanel.add(buttonAcqSetup);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7,
SpringLayout.WEST, topPanel);
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() == 0) {
toggleButtonShutter_.setEnabled(false);
return;
}
if (autoShutterCheckBox_.isSelected()) {
try {
core_.setAutoShutter(true);
core_.setShutterOpen(false);
toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
toggleButtonShutter_.setEnabled(false);
} catch (Exception e2) {
ReportingUtils.logError(e2);
}
} else {
try {
core_.setAutoShutter(false);
core_.setShutterOpen(false);
toggleButtonShutter_.setEnabled(true);
toggleButtonShutter_.setText("Open");
} catch (Exception exc) {
ReportingUtils.logError(exc);
}
}
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
topPanel.add(autoShutterCheckBox_);
topLayout.putConstraint(SpringLayout.EAST, autoShutterCheckBox_,
202 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autoShutterCheckBox_,
110 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_,
141 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_,
118 - 22, SpringLayout.NORTH, topPanel);
final JButton refreshButton = new JButton();
refreshButton.setMargin(new Insets(2, 2, 2, 2));
refreshButton.setIconTextGap(1);
refreshButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_refresh.png"));
refreshButton.setFont(new Font("Arial", Font.PLAIN, 10));
refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware");
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshButton.setText("Refresh");
topPanel.add(refreshButton);
topLayout.putConstraint(SpringLayout.SOUTH, refreshButton, 113,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, refreshButton, 92,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, refreshButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, refreshButton, 7,
SpringLayout.WEST, topPanel);
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
topPanel.add(citePleaLabel);
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
topLayout.putConstraint(SpringLayout.SOUTH, citePleaLabel, 139,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, citePleaLabel, 119,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, citePleaLabel, 270,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, citePleaLabel, 7,
SpringLayout.WEST, topPanel);
class Pleader extends Thread{
Pleader(){
super("pleader");
}
@Override
public void run(){
try {
ij.plugin.BrowserLauncher.openURL("https://valelab.ucsf.edu/~MM/MMwiki/index.php/Citing_Micro-Manager");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
}
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Pleader p = new Pleader();
p.start();
}
});
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence();
}
@Override
public void windowOpened(WindowEvent e) {
// initialize hardware
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib");
return;
}
ReportingUtils.setCore(core_);
logStartupProperties();
cameraLabel_ = "";
shutterLabel_ = "";
zStageLabel_ = "";
xyStageLabel_ = "";
engine_ = new AcquisitionWrapperEngine();
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
loadMRUConfigFiles();
initializePlugins();
toFront();
if (!options_.doNotAskForConfigFile_) {
MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));
introDlg.setVisible(true);
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
paint(MMStudioMainFrame.this.getGraphics());
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
// if an error occurred during config loading,
// do not display more errors than needed
if (!loadSystemConfiguration())
ReportingUtils.showErrorOn(false);
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this);
addMMBackgroundListener(acqControlWin_);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
// initializeGUI(); Not needed since it is already called in loadSystemConfiguration
initializeHelpMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
// switch error reporting back on
ReportingUtils.showErrorOn(true);
}
private void initializePlugins() {
pluginMenu_ = new JMenu();
pluginMenu_.setText("Plugins");
menuBar_.add(pluginMenu_);
new Thread("Plugin loading") {
@Override
public void run() {
// Needed for loading clojure-based jars:
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
loadPlugins();
}
}.run();
}
});
final JButton setRoiButton = new JButton();
setRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/shape_handles.png"));
setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle");
setRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setROI();
}
});
topPanel.add(setRoiButton);
topLayout.putConstraint(SpringLayout.EAST, setRoiButton, 37,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, setRoiButton, 7,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, setRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, setRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JButton clearRoiButton = new JButton();
clearRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_out.png"));
clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
clearRoiButton.setToolTipText("Reset Region of Interest to full frame");
clearRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearROI();
}
});
topPanel.add(clearRoiButton);
topLayout.putConstraint(SpringLayout.EAST, clearRoiButton, 70,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, clearRoiButton, 40,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, clearRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JLabel regionOfInterestLabel = new JLabel();
regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel.setText("ROI");
topPanel.add(regionOfInterestLabel);
topLayout.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel,
154, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, regionOfInterestLabel,
140, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel,
71, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel,
8, SpringLayout.WEST, topPanel);
final JLabel regionOfInterestLabel_1 = new JLabel();
regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel_1.setText("Zoom");
topPanel.add(regionOfInterestLabel_1);
topLayout.putConstraint(SpringLayout.SOUTH,
regionOfInterestLabel_1, 154, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.NORTH,
regionOfInterestLabel_1, 140, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1,
139, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1,
81, SpringLayout.WEST, topPanel);
final JButton zoomInButton = new JButton();
zoomInButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomIn();
}
});
zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_in.png"));
zoomInButton.setToolTipText("Zoom in");
zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomInButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomInButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomInButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomInButton, 110,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomInButton, 80,
SpringLayout.WEST, topPanel);
final JButton zoomOutButton = new JButton();
zoomOutButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomOut();
}
});
zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_out.png"));
zoomOutButton.setToolTipText("Zoom out");
zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomOutButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomOutButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomOutButton, 143,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomOutButton, 113,
SpringLayout.WEST, topPanel);
// Profile
final JLabel profileLabel_ = new JLabel();
profileLabel_.setFont(new Font("Arial", Font.BOLD, 11));
profileLabel_.setText("Profile");
topPanel.add(profileLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, profileLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, profileLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, profileLabel_, 217,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, profileLabel_, 154,
SpringLayout.WEST, topPanel);
final JButton buttonProf = new JButton();
buttonProf.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/chart_curve.png"));
buttonProf.setFont(new Font("Arial", Font.PLAIN, 10));
buttonProf.setToolTipText("Open line profile window (requires line selection)");
buttonProf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openLineProfileWindow();
}
});
// buttonProf.setText("Profile");
topPanel.add(buttonProf);
topLayout.putConstraint(SpringLayout.SOUTH, buttonProf, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonProf, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonProf, 183,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonProf, 153,
SpringLayout.WEST, topPanel);
// Autofocus
final JLabel autofocusLabel_ = new JLabel();
autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11));
autofocusLabel_.setText("Autofocus");
topPanel.add(autofocusLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, autofocusLabel_, 274,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autofocusLabel_, 194,
SpringLayout.WEST, topPanel);
buttonAutofocus_ = new JButton();
buttonAutofocus_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/find.png"));
buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocus_.setToolTipText("Autofocus now");
buttonAutofocus_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if(lmo)
enableLiveMode(false);
afMgr_.getDevice().fullFocus();
if(lmo)
enableLiveMode(true);
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start(); // or any other method from Autofocus.java API
}
}
});
topPanel.add(buttonAutofocus_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193,
SpringLayout.WEST, topPanel);
buttonAutofocusTools_ = new JButton();
buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/wrench_orange.png"));
buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocusTools_.setToolTipText("Set autofocus options");
buttonAutofocusTools_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAutofocusDialog();
}
});
topPanel.add(buttonAutofocusTools_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226,
SpringLayout.WEST, topPanel);
saveConfigButton_ = new JButton();
saveConfigButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
}
});
saveConfigButton_.setToolTipText("Save current presets to the configuration file");
saveConfigButton_.setText("Save");
saveConfigButton_.setEnabled(false);
topPanel.add(saveConfigButton_);
topLayout.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, saveConfigButton_, -5,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, saveConfigButton_, -80,
SpringLayout.EAST, topPanel);
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + "
}
if (options_.debugLogEnabled_) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (isLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
public void makeActive() {
toFront();
}
private void setExposure() {
try {
if (!isLiveModeOn()) {
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
} else {
liveModeTimer_.stop();
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
try {
liveModeTimer_.begin();
} catch (Exception e) {
ReportingUtils.showError("Couldn't restart live mode");
liveModeTimer_.stop();
}
}
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
} catch (Exception exp) {
// Do nothing.
}
}
public boolean getConserveRamOption() {
return options_.conserveRam_;
}
public boolean getAutoreloadOption() {
return options_.autoreloadDevices_;
}
private void updateTitle() {
this.setTitle("System: " + sysConfigFile_);
}
public void updateLineProfile() {
if (WindowManager.getCurrentWindow() == null || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
public Rectangle getROI() throws MMScriptException {
// ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBoundingRect();
// if we already had an ROI defined, correct for the offsets
Rectangle cameraR = getROI();
r.x += cameraR.x;
r.y += cameraR.y;
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
/**
* Returns instance of the core uManager object;
*/
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudioMainFrame
*/
public static MMStudioMainFrame getInstance() {
return gui_;
}
public MetadataPanel getMetadataPanel() {
return metadataPanel_;
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
public String getAcqDirectory() {
return openAcqDirectory_;
}
/**
* Get currently used configuration file
* @return - Path to currently used configuration file
*/
public String getSysConfigFile() {
return sysConfigFile_;
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
*
*/
public void openAcquisitionData() {
// choose the directory
File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET);
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
openAcquisitionData(openAcqDirectory_);
}
}
public void openAcquisitionData(String dir) {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir= rootDir.substring(0, rootDir.length() - (name.length() + 1));
try {
acqMgr_.openAcquisition(name, rootDir, true, true, true);
acqMgr_.getAcquisition(name).initialize();
acqMgr_.closeAcquisition(name);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (vad != null) {
vad.storeWindowSizeAfterZoom(curWin);
vad.updateWindowTitleAndStatus();
}
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (vad != null) {
vad.storeWindowSizeAfterZoom(curWin);
vad.updateWindowTitleAndStatus();
}
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (isLiveModeOn() ) {
liveRunning = true;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(scriptPanel_);
}
}
/**
* Updates Status line in main window from cached values
*/
private void updateStaticInfoFromCache() {
String dimText = "Image info (from camera): " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPos(double x, double y) {
staticInfo_.x_ = x;
staticInfo_.y_ = y;
updateStaticInfoFromCache();
}
public void updateZPos(double z) {
staticInfo_.zPos_ = z;
updateStaticInfoFromCache();
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
public void updateXYStagePosition(){
double x[] = new double[1];
double y[] = new double[1];
try {
if (xyStageLabel_.length() > 0)
core_.getXYPosition(xyStageLabel_, x, y);
} catch (Exception e) {
ReportingUtils.showError(e);
}
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
private void updatePixSizeUm (double pixSizeUm) {
staticInfo_.pixSizeUm_ = pixSizeUm;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
public void toggleShutter() {
try {
if (!toggleButtonShutter_.isEnabled())
return;
toggleButtonShutter_.requestFocusInWindow();
if (toggleButtonShutter_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
private void setShutterButton(boolean state) {
if (state) {
// toggleButtonShutter_.setSelected(true);
toggleButtonShutter_.setText("Close");
} else {
// toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
}
}
// public interface available for scripting access
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null) {
return ip.getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null) {
return;
}
ip.getProcessor().setPixels(obj);
}
public int getImageHeight() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getHeight();
return 0;
}
public int getImageWidth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getWidth();
return 0;
}
public int getImageDepth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getBitDepth();
return 0;
}
public ImageProcessor getImageProcessor() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null)
return null;
return ip.getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
/**
* Implements ScriptInterface
*/
public PositionListDlg getXYPosListDlg() {
if (posListDlg_ == null)
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
return posListDlg_;
}
/**
* Implements ScriptInterface
*/
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
/**
* Implements ScriptInterface
*/
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = VERSION.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (Exception ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
public boolean isLiveModeOn() {
return liveModeTimer_ != null && liveModeTimer_.isRunning();
}
public void enableLiveMode(boolean enable) {
if (core_ == null) {
return;
}
if (enable == isLiveModeOn()) {
return;
}
if (enable) {
try {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
updateButtonsForLiveMode(false);
return;
}
if (liveModeTimer_ == null) {
liveModeTimer_ = new LiveModeTimer(33);
}
liveModeTimer_.begin();
enableLiveModeListeners(enable);
} catch (Exception e) {
ReportingUtils.showError(e);
liveModeTimer_.stop();
enableLiveModeListeners(false);
updateButtonsForLiveMode(false);
return;
}
} else {
liveModeTimer_.stop();
enableLiveModeListeners(enable);
}
updateButtonsForLiveMode(enable);
}
public void updateButtonsForLiveMode(boolean enable) {
toggleButtonShutter_.setEnabled(!enable);
autoShutterCheckBox_.setEnabled(!enable);
buttonSnap_.setEnabled(!enable);
toAlbumButton_.setEnabled(!enable);
toggleButtonLive_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setSelected(false);
toggleButtonLive_.setText(enable ? "Stop Live" : "Live");
}
private void enableLiveModeListeners(boolean enable) {
if (enable) {
// attach mouse wheel listener to control focus:
if (zWheelListener_ == null)
zWheelListener_ = new ZWheelListener(core_, this);
zWheelListener_.start(getImageWin());
// attach key listener to control the stage and focus:
if (xyzKeyListener_ == null)
xyzKeyListener_ = new XYZKeyListener(core_, this);
xyzKeyListener_.start(getImageWin());
if (centerAndDragListener_ == null)
centerAndDragListener_ = new CenterAndDragListener(core_, this);
centerAndDragListener_.start();
} else {
if (zWheelListener_ != null)
zWheelListener_.stop();
if (xyzKeyListener_ != null)
xyzKeyListener_.stop();
if (centerAndDragListener_ != null)
centerAndDragListener_.stop();
}
}
public boolean getLiveMode() {
return isLiveModeOn();
}
public boolean updateImage() {
try {
if (isLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do, just show the last image
}
if (WindowManager.getCurrentWindow() == null) {
return false;
}
ImagePlus ip = WindowManager.getCurrentImage();
core_.snapImage();
Object img = core_.getImage();
ip.getProcessor().setPixels(img);
ip.updateAndRepaintWindow();
if (!isCurrentImageFormatSupported()) {
return false;
}
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(final Object pixels) {
return displayImage(pixels, true);
}
public boolean displayImage(final Object pixels, boolean wait) {
String[] acqs = acqMgr_.getAcqusitionNames();
VirtualAcquisitionDisplay virtAcq;
if (acqs == null || acqs.length == 0) {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip instanceof VirtualAcquisitionDisplay.MMImagePlus) {
virtAcq = ((VirtualAcquisitionDisplay.MMImagePlus) ip).display_;
} else if (ip instanceof VirtualAcquisitionDisplay.MMCompositeImage) {
virtAcq = ((VirtualAcquisitionDisplay.MMCompositeImage) ip).display_;
} else {
return false;
}
} else {
String acqName = acqs[acqs.length - 1];
MMAcquisition acq;
try {
acq = acqMgr_.getAcquisition(acqName);
} catch (MMScriptException ex) {
ReportingUtils.showError("Can't locate acquisition");
return false;
}
virtAcq = acq.getAcquisitionWindow();
}
try {
JSONObject summary = virtAcq.getImageCache().getSummaryMetadata();
int width = MDUtils.getWidth(summary);
int height = MDUtils.getHeight(summary);
int bitDepth = MDUtils.getBitDepth(summary);
String pixelType = MDUtils.getPixelType(summary);
if (height != core_.getImageHeight() || width != core_.getImageWidth() ||
bitDepth != core_.getImageBitDepth())
return false;
TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, bitDepth);
ti.tags.put("PixelType", pixelType);
virtAcq.getImageCache().putImage(ti);
virtAcq.showImage(ti, wait);
return true;
} catch (Exception ex) {
ReportingUtils.showError(ex);
return false;
}
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
String[] acqs = acqMgr_.getAcqusitionNames();
VirtualAcquisitionDisplay virtAcq;
if (acqs == null || acqs.length == 0) {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip instanceof VirtualAcquisitionDisplay.MMImagePlus) {
virtAcq = ((VirtualAcquisitionDisplay.MMImagePlus) ip).display_;
} else if (ip instanceof VirtualAcquisitionDisplay.MMCompositeImage) {
virtAcq = ((VirtualAcquisitionDisplay.MMCompositeImage) ip).display_;
} else {
return false;
}
} else {
String acqName = acqs[acqs.length - 1];
MMAcquisition acq;
try {
acq = acqMgr_.getAcquisition(acqName);
} catch (MMScriptException ex) {
ReportingUtils.showError("Can't locate acquisition");
return false;
}
virtAcq = acq.getAcquisitionWindow();
}
try {
JSONObject tags = virtAcq.getImageCache().getLastImageTags();
int width = MDUtils.getWidth(tags);
int height = MDUtils.getHeight(tags);
int depth = MDUtils.getBitDepth(tags);
if (height != core_.getImageHeight() || width != core_.getImageWidth()
|| depth != core_.getImageBitDepth()) {
return false;
}
TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0, 0, width, height, depth);
virtAcq.getImageCache().putImage(ti);
virtAcq.showImage(ti);
virtAcq.displayStatusLine(statusLine);
return true;
} catch (Exception ex) {
ReportingUtils.logError(ex);
return false;
}
}
public void displayStatusLine(String statusLine) {
ImagePlus ip = WindowManager.getCurrentImage();
VirtualAcquisitionDisplay virtAcq;
if (ip instanceof VirtualAcquisitionDisplay.MMImagePlus )
virtAcq = ((VirtualAcquisitionDisplay.MMImagePlus) ip).display_;
else if (ip instanceof VirtualAcquisitionDisplay.MMCompositeImage)
virtAcq = ((VirtualAcquisitionDisplay.MMCompositeImage) ip).display_;
else
return;
virtAcq.displayStatusLine(statusLine);
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
public void doSnap() {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
try {
core_.snapImage();
long c = core_.getNumberOfCameraChannels();
for (int i = 0; i < c; ++i) {
displayImage(core_.getTaggedImage(i), (i == c - 1), i);
}
simpleDisplay_.getImagePlus().getWindow().toFront();
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public boolean displayImage(TaggedImage ti) {
return displayImage(ti, true, 0);
}
public boolean displayImage(TaggedImage ti, boolean update, int channel) {
try {
checkSimpleAcquisition(ti);
setCursor(new Cursor(Cursor.WAIT_CURSOR));
//getAcquisition(SIMPLE_ACQ).toFront();
ti.tags.put("Summary", getAcquisition(SIMPLE_ACQ).getSummaryMetadata());
ti.tags.put("ChannelIndex", channel);
ti.tags.put("PositionIndex", 0);
ti.tags.put("SliceIndex", 0);
ti.tags.put("FrameIndex", 0);
addImage(SIMPLE_ACQ, ti, update, true);
} catch (Exception ex) {
ReportingUtils.logError(ex);
return false;
}
if (update) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
updateLineProfile();
}
return true;
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.size() == 0) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null);
buttonAutofocus_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getVersion() {
return VERSION;
}
private void addPluginToMenu(final PluginItem plugin, Class<?> cl) {
// add plugin menu items
final JMenuItem newMenuItem = new JMenuItem();
newMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
ReportingUtils.logMessage("Plugin command: "
+ e.getActionCommand());
plugin.instantiate();
plugin.plugin.show();
}
});
newMenuItem.setText(plugin.menuItem);
String toolTipDescription = "";
try {
// Get this static field from the class implementing MMPlugin.
toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
toolTipDescription = "Description not available";
} catch (NoSuchFieldException e) {
toolTipDescription = "Description not available";
ReportingUtils.logError(cl.getName() + " fails to implement static String tooltipDescription.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
newMenuItem.setToolTipText(toolTipDescription);
else
newMenuItem.setToolTipText( TooltipTextMaker.addHTMLBreaksForTooltip(toolTipDescription) );
pluginMenu_.add(newMenuItem);
pluginMenu_.validate();
menuBar_.validate();
}
public void updateGUI(boolean updateConfigPadStructure) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
GUIUtils.setComboSelection(comboBinning_, binSize);
}
if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure();
// Needed to update read-only properties. May slow things down...
core_.updateSystemStateCache();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
public boolean okToAcquire() {
return !isLiveModeOn();
}
public void stopAllActivity() {
enableLiveMode(false);
}
private boolean cleanupOnClose() {
// NS: Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
}
if (liveModeTimer_ != null)
liveModeTimer_.stop();
if (!WindowManager.closeAllWindows())
return false;
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
synchronized (shutdownLock_) {
try {
if (core_ != null){
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
return true;
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE);
if (f != null) {
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
private void loadSystemState() {
File f = FileDialogs.openFile(this, "Load a system state file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
// WaitDialog waitDlg = new
// WaitDialog("Loading saved state, please wait...");
// waitDlg.showDialog();
core_.loadSystemState(sysStateFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
// waitDlg.closeDialog();
initializeGUI();
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
private void saveSystemState() {
File f = FileDialogs.save(this,
"Save the system state to a config file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
core_.saveSystemState(sysStateFile_);
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
public void closeSequence() {
if (!this.isRunning())
return;
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return;
}
}
stopAllActivity();
if (!cleanupOnClose())
return;
running_ = false;
saveSettings();
try {
configPad_.saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
this.logError(e);
}
this.dispose();
if (options_.closeOnExit_) {
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
}
}
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
ImagePlus img = WindowManager.getCurrentImage();
if (img == null)
return;
if (img.getBytesPerPixel() == 1)
metadataPanel_.setChannelContrast(0, contrast8.min, contrast8.max, contrast8.gamma);
else
metadataPanel_.setChannelContrast(0, contrast16.min, contrast16.max, contrast16.gamma);
}
@Override
public ContrastSettings getContrastSettings() {
return metadataPanel_.getChannelContrast(0);
}
public boolean is16bit() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null && ip.getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.showError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads system configuration from the cfg file.
*/
private boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
ignorePropertyChanges_ = true;
core_.loadSystemConfiguration(sysConfigFile_);
ignorePropertyChanges_ = false;
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
ReportingUtils.showError(err);
result = false;
} finally {
waitDlg.closeDialog();
}
setEnabled(true);
initializeGUI();
updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
acqControlWin_.repaint();
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
* /** Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/**
* Returns the current background color
* @return
*/
@Override
public Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((backgroundType)));
paint(MMStudioMainFrame.this.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
// Scripting interface
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
@Override
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private class LoadAcq implements Runnable {
private String filePath_;
public LoadAcq(String path) {
filePath_ = path;
}
@Override
public void run() {
// stop current acquisition if any
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(filePath_);
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
@Override
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
@Override
public String runAcquisition() throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
String name = acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return name;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
@Override
public String runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
String acqName = acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return acqName;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
@Override
public String runAcqusition(String name, String root) throws MMScriptException {
return runAcquisition(name, root);
}
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new LoadAcq(path));
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null) {
posListDlg_.setPositionList(posList_);
engine_.setPositionList(posList_);
}
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
// TODO:
@Override
public MMAcquisition getCurrentAcquisition() {
return null; // if none available
}
public void openAcquisition(String name, String rootDir) throws MMScriptException {
openAcquisition(name, rootDir, true);
}
public void openAcquisition(String name, String rootDir, boolean show) throws MMScriptException {
//acqMgr_.openAcquisition(name, rootDir, show);
TaggedImageStorage imageFileManager = new TaggedImageStorageDiskDefault((new File(rootDir, name)).getAbsolutePath());
MMImageCache cache = new MMImageCache(imageFileManager);
VirtualAcquisitionDisplay display = new VirtualAcquisitionDisplay(cache, (AcquisitionEngine) null);
display.show();
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, virtual);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);
}
public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) {
return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_);
}
private void openAcquisitionSnap(String name, String rootDir, boolean show)
throws MMScriptException {
/*
MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this,
show);
acq.setDimensions(0, 1, 1, 1);
try {
// acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm());
acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm()));
} catch (Exception e) {
ReportingUtils.showError(e);
}
*
*/
}
@Override
public void initializeSimpleAcquisition(String name, int width, int height,
int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh);
acq.initializeSimpleAcq();
}
@Override
public void initializeAcquisition(String name, int width, int height,
int depth) throws MMScriptException {
initializeAcquisition(name,width,height,depth,8*depth);
}
@Override
public void initializeAcquisition(String name, int width, int height,
int depth, int bitDepth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
//number of multi-cam cameras is set to 1 here for backwards compatibility
//might want to change this later
acq.setImagePhysicalDimensions(width, height, depth, bitDepth,1);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getBitDepth();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getDepth();
}
@Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getMultiCameraNumChannels();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
@Override
public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException {
acqMgr_.closeImage5D(acquisitionName);
}
@Override
public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException {
acqMgr_.closeImage5D(acquisitionName);
}
/**
* Since Burst and normal acquisition are now carried out by the same engine,
* loadBurstAcquistion simply calls loadAcquisition
* t
* @param path - path to file specifying acquisition settings
*/
@Override
public void loadBurstAcquisition(String path) throws MMScriptException {
this.loadAcquisition(path);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSystemState(md);
}
public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSummaryProperties(md);
}
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
public void snapAndAddImage(String name, int frame, int channel, int slice)
throws MMScriptException {
snapAndAddImage(name, frame, channel, slice, 0);
}
public void snapAndAddImage(String name, int frame, int channel, int slice, int position)
throws MMScriptException {
Metadata md = new Metadata();
try {
Object img;
if (core_.isSequenceRunning()) {
img = core_.getLastImageMD(0, 0, md);
} else {
core_.snapImage();
img = core_.getImage();
}
MMAcquisition acq = acqMgr_.getAcquisition(name);
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
long bitDepth = core_.getImageBitDepth();
int multiCamNumCh = (int) core_.getNumberOfCameraChannels();
if (!acq.isInitialized()) {
acq.setImagePhysicalDimensions((int) width, (int) height,
(int) depth, (int) bitDepth, multiCamNumCh);
acq.initialize();
}
acq.insertImage(img, frame, channel, slice, position);
// Insert exposure in metadata
// acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
/*
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
acq.setSystemState(frame, channel, slice, state);
*/
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void addToSnapSeries(Object img, String acqName) {
try {
acqMgr_.getCurrentAlbum();
if (acqName == null) {
acqName = "Snap" + snapCount_;
}
Boolean newSnap = false;
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
//MMAcquisitionSnap acq = null;
if (! acqMgr_.hasActiveImage5D(acqName)) {
newSnap = true;
}
if (newSnap) {
snapCount_++;
acqName = "Snap" + snapCount_;
this.openAcquisitionSnap(acqName, null, true); // (dir=null) ->
// keep in
// memory; don't
// save to file.
initializeAcquisition(acqName, (int) width, (int) height,
(int) depth);
}
setChannelColor(acqName, 0, Color.WHITE);
setChannelName(acqName, 0, "Snap");
// acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName);
// acq.appendImage(img);
// add exposure to metadata
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
// JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
// acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state);
// closeAcquisition(acqName);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
public String createNewAlbum() {
return acqMgr_.createNewAlbum();
}
public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(taggedImg.tags, f);
} catch (JSONException e) {
throw new MMScriptException("Unable to set the frame index.");
}
acq.insertTaggedImage(taggedImg, f, 0, 0);
}
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
addToAlbum(taggedImg, null);
}
public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException {
acqMgr_.addToAlbum(taggedImg,displaySettings);
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg);
}
public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay);
}
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);
}
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
public String[] getAcquisitionNames()
{
return acqMgr_.getAcqusitionNames();
}
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
public void run() {
if (scriptPanel_ != null)
scriptPanel_.message(msg_);
}
}
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public String getXYStageName() {
return core_.getXYStageDevice();
}
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionEngine getAcquisitionEngine() {
return engine_;
}
public String installPlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = className + " module loaded.";
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
return className + " already loaded.";
}
}
PluginItem pi = new PluginItem();
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logError(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
//core_.logMessage(className + " fails to implement static String menuName.");
}
pi.menuItem = pi.menuItem.replace("_", " ");
pi.pluginClass = cl;
plugins_.add(pi);
final PluginItem pi2 = pi;
final Class<?> cl2 = cl;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
addPluginToMenu(pi2, cl2);
}
});
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
return msg;
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
public String installPlugin(String className) {
String msg = "";
try {
Class clazz = Class.forName(className);
return installPlugin(clazz);
} catch (ClassNotFoundException e) {
msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
public Pipeline getPipeline() {
try {
pipelineClassLoadingThread_.join();
if (acquirePipeline_ == null) {
acquirePipeline_ = (Pipeline) pipelineClass_.newInstance();
}
return acquirePipeline_;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
public void snapAndAddToImage5D() {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
try {
getPipeline().acquireSingle();
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public void setAcquisitionEngine(AcquisitionEngine eng) {
engine_ = eng;
}
public void suspendLiveMode() {
liveModeSuspended_ = isLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
public String regenerateDeviceList() {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(resultFile, core_);
//MicroscopeModel.generateDeviceListFile();
setCursor(oldc);
return resultFile.toString();
}
private void loadPlugins() {
afMgr_ = new AutofocusManager(this);
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
long t1 = System.currentTimeMillis();
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
//System.out.println("findClasses: " + (System.currentTimeMillis() - t1));
//System.out.println(classes.size());
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
for (Class<?> plugin : pluginClasses) {
try {
ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
installPlugin(plugin);
} catch (Exception e) {
ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName());
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
public void logError(Exception e) {
ReportingUtils.logError(e);
}
public void logError(String msg) {
ReportingUtils.logError(msg);
}
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
public void showError(Exception e) {
ReportingUtils.showError(e);
}
public void showError(String msg) {
ReportingUtils.showError(msg);
}
private void runHardwareWizard(boolean v2) {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
if (v2) {
ConfiguratorDlg2 cfg2 = null;
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);
} finally {
setCursor(Cursor.getDefaultCursor());
}
cfg2.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = cfg2.getFileName();
} else {
ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_);
configurator.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = configurator.getFileName();
}
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
if (liveRunning) {
enableLiveMode(liveRunning);
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
} |
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//This file is distributed in the hope that it will be useful,
//of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ImageStatistics;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.Metadata;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.MMAcquisitionSnap;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
import org.micromanager.conf.ConfiguratorDlg;
import org.micromanager.conf.MMConfigFileException;
import org.micromanager.conf.MicroscopeModel;
import org.micromanager.graph.ContrastPanel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.image5d.ChannelCalibration;
import org.micromanager.image5d.ChannelControl;
import org.micromanager.image5d.ChannelDisplayProperties;
import org.micromanager.image5d.Crop_Image5D;
import org.micromanager.image5d.Duplicate_Image5D;
import org.micromanager.image5d.Image5D;
import org.micromanager.image5d.Image5DWindow;
import org.micromanager.image5d.Image5D_Channels_to_Stacks;
import org.micromanager.image5d.Image5D_Stack_to_RGB;
import org.micromanager.image5d.Image5D_Stack_to_RGB_t;
import org.micromanager.image5d.Image5D_to_Stack;
import org.micromanager.image5d.Image5D_to_VolumeViewer;
import org.micromanager.image5d.Make_Montage;
import org.micromanager.image5d.Split_Image5D;
import org.micromanager.image5d.Z_Project;
import org.micromanager.metadata.AcquisitionData;
import org.micromanager.metadata.DisplaySettings;
import org.micromanager.metadata.ImagePropertyKeys;
import org.micromanager.metadata.MMAcqDataException;
import org.micromanager.metadata.SummaryKeys;
import org.micromanager.metadata.WellAcquisitionData;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.PositionList;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.Annotator;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.CfgFileFilter;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMImageWindow;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ProgressBar;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.VirtualStack;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.image.DirectColorModel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.micromanager.nativegui.NativeGUI;
import org.micromanager.utils.ReportingUtils;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4";
private static final String VERSION = "1.4.0";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_EXPOSURE = "exposure";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String MAIN_STRETCH_CONTRAST = "stretch_contrast";
private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN";
private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX";
private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN";
private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private SpringLayout springLayout_;
private JLabel labelImageDimensions_;
private JToggleButton toggleButtonLive_;
private JCheckBox autoShutterCheckBox_;
private boolean autoShutterOrg_;
private boolean shutterOrg_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton buttonSnap_;
private JButton buttonAutofocus_;
private JButton buttonAutofocusTools_;
private JToggleButton toggleButtonShutter_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ArrayList<PluginItem> plugins_;
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private ContrastPanel contrastPanel_;
// Timer interval - image display interval
private double liveModeInterval_ = 40;
private Timer liveModeTimer_;
private GraphData lineProfileData_;
private Object img_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean liveRunning_ = false;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private FastAcqDlg fastAcqWin_;
private ScriptPanel scriptPanel_;
private SplitView splitView_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static MMImageWindow imageWin_;
private int snapCount_ = -1;
private boolean liveModeSuspended_;
private boolean liveModeFullyStarted_;
public Font defaultScriptFont_ = null;
public static MMImageWindow getLiveWin() {
return imageWin_;
}
// Our instance
private MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private boolean virtual_ = false;
private void applyChannelSettingsTo5D(AcquisitionData ad, Image5D img5d) throws MMAcqDataException {
Color[] colors = ad.getChannelColors();
String[] names = ad.getChannelNames();
if (colors != null && names != null) {
for (int i = 0; i < ad.getNumberOfChannels(); i++) {
ChannelCalibration chcal = new ChannelCalibration();
// set channel name
chcal.setLabel(names[i]);
img5d.setChannelCalibration(i + 1, chcal);
if (img5d.getBytesPerPixel() == 4) {
img5d.setChannelColorModel(i + 1, new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF));
} else {
img5d.setChannelColorModel(i + 1, ChannelDisplayProperties.createModelFromColor(colors[i]));
}
}
}
}
private void popUpImage5DWindow(Image5D img5d, AcquisitionData ad) {
// pop-up 5d image window
Image5DWindow i5dWin = new Image5DWindow(img5d);
i5dWin.setBackground(guiColors_.background.get(options_.displayBackground));
if (ad.getNumberOfChannels() == 1) {
img5d.setDisplayMode(ChannelControl.ONE_CHANNEL_COLOR);
} else {
img5d.setDisplayMode(ChannelControl.OVERLAY);
}
i5dWin.setAcquitionEngine(engine_);
i5dWin.setAcquisitionData(ad);
i5dWin.setAcqSavePath(openAcqDirectory_);
i5dWin.addWindowListener(new WindowAdapter() {
public void windowGainedFocus(WindowEvent e) {
updateHistogram();
}
});
i5dWin.addWindowListener(new WindowAdapter() {
public void windowGainedFocus(WindowEvent e) {
updateHistogram();
}
});
i5dWin.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
updateHistogram();
}
});
img5d.changes = false;
}
private void set5DDisplaySettingsForChannels(int k, int i, AcquisitionData ad, int j, Image5D img5d) throws MMAcqDataException {
// set display settings for channels
if (k == 0 && i == 0) {
DisplaySettings[] ds = ad.getChannelDisplaySettings();
if (ds != null) {
// display properties are recorded in
// metadata use them...
double min = ds[j].min;
double max = ds[j].max;
img5d.setChannelMinMax(j + 1, min, max);
} else {
// ...if not, autoscale channels based
// on the first slice of the first frame
ImageStatistics stats = img5d.getStatistics(); // get
// uncalibrated
// stats
double min = stats.min;
double max = stats.max;
img5d.setChannelMinMax(j + 1, min, max);
}
}
}
public ImageWindow getImageWin() {
return imageWin_;
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!");
} else {
updateGUI(true);
if (propertyBrowser_ != null) {
propertyBrowser_.updateStatus();
}
core_.logMessage("Notification from MMCore!");
}
}
public void onCoordinateUpdate() { /* todo */
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
public MMStudioMainFrame(boolean pluginStatus) {
super();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
ReportingUtils.showError(e, "An uncaught exception was thrown in thread " + t.getName() + ".");
}
});
options_ = new MMOptions();
options_.loadSettings();
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
// !!! contrastSettings8_ = new ContrastSettings();
// contrastSettings16_ = new ContrastSettings();
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = new String(System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME);
if (options_.startupScript.length() > 0) {
startupScriptFile_ = new String(System.getProperty("user.dir") + "/"
+ options_.startupScript);
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
systemPrefs_ = mainPrefs_;
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
// initialize timer
ActionListener liveModeTimerHandler = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (!isImageWindowOpen()) {
// stop live acquisition if user closed the window
enableLiveMode(false);
return;
}
if (!isNewImageAvailable()) {
return;
}
try {
Object img;
// ToDo: implement color and multi-channel camera support
// use core_.getLastImage()
long channels = core_.getNumberOfComponents();
if (!liveModeFullyStarted_) {
if (core_.getRemainingImageCount() > 0) {
liveModeFullyStarted_ = true;
}
}
if (liveModeFullyStarted_) {
if (channels == 1) {
img = core_.getLastImage();
} else {
img = core_.getRGB32Image();
}
if (img != img_) {
img_ = img;
displayImage(img_);
}
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
};
liveModeTimer_ = new Timer((int) liveModeInterval_, liveModeTimerHandler);
liveModeTimer_.stop();
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 451);
boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true);
ContrastSettings s8 = new ContrastSettings(mainPrefs_.getDouble(
CONTRAST_SETTINGS_8_MIN, 0.0), mainPrefs_.getDouble(
CONTRAST_SETTINGS_8_MAX, 0.0));
ContrastSettings s16 = new ContrastSettings(mainPrefs_.getDouble(
CONTRAST_SETTINGS_16_MIN, 0.0), mainPrefs_.getDouble(
CONTRAST_SETTINGS_16_MAX, 0.0));
MMImageWindow.setContrastSettings(s8, s16);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
setBounds(x, y, width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
springLayout_ = new SpringLayout();
getContentPane().setLayout(springLayout_);
setTitle(MICRO_MANAGER_TITLE);
setBackground(guiColors_.background.get((options_.displayBackground)));
// Snap button
buttonSnap_ = new JButton();
buttonSnap_.setIconTextGap(6);
buttonSnap_.setText("Snap");
buttonSnap_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/camera.png"));
buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonSnap_.setToolTipText("Snap single image");
buttonSnap_.setMaximumSize(new Dimension(0, 0));
buttonSnap_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSnap();
}
});
getContentPane().add(buttonSnap_);
springLayout_.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, buttonSnap_, 4,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, buttonSnap_, 95,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, buttonSnap_, 7,
SpringLayout.WEST, getContentPane());
// Initialize
// Exposure field
final JLabel label_1 = new JLabel();
label_1.setFont(new Font("Arial", Font.PLAIN, 10));
label_1.setText("Exposure [ms]");
getContentPane().add(label_1);
springLayout_.putConstraint(SpringLayout.EAST, label_1, 198,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, label_1, 111,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.SOUTH, label_1, 39,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, label_1, 23,
SpringLayout.NORTH, getContentPane());
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent fe) {
setExposure();
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
getContentPane().add(textFieldExp_);
springLayout_.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, textFieldExp_, 21,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, textFieldExp_, 276,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, textFieldExp_, 203,
SpringLayout.WEST, getContentPane());
// Live button
toggleButtonLive_ = new JToggleButton();
toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2));
toggleButtonLive_.setIconTextGap(1);
toggleButtonLive_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setIconTextGap(6);
toggleButtonLive_.setToolTipText("Continuous live view");
toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10));
toggleButtonLive_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!IsLiveModeOn()) {
// Display interval for Live Mode changes as well
setLiveModeInterval();
}
enableLiveMode(!IsLiveModeOn());
}
});
toggleButtonLive_.setText("Live");
getContentPane().add(toggleButtonLive_);
springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7,
SpringLayout.WEST, getContentPane());
// Acquire button
JButton acquireButton = new JButton();
acquireButton.setMargin(new Insets(2, 2, 2, 2));
acquireButton.setIconTextGap(1);
acquireButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/snapAppend.png"));
acquireButton.setIconTextGap(6);
acquireButton.setToolTipText("Acquire single frame");
acquireButton.setFont(new Font("Arial", Font.PLAIN, 10));
acquireButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snapAndAddToImage5D(null);
}
});
acquireButton.setText("Acquire");
getContentPane().add(acquireButton);
springLayout_.putConstraint(SpringLayout.SOUTH, acquireButton, 69,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, acquireButton, 48,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, acquireButton, 95,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, acquireButton, 7,
SpringLayout.WEST, getContentPane());
// Shutter button
toggleButtonShutter_ = new JToggleButton();
toggleButtonShutter_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
try {
if (toggleButtonShutter_.isSelected()) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
toggleButtonShutter_.setToolTipText("Open/close the shutter");
toggleButtonShutter_.setIconTextGap(6);
toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10));
toggleButtonShutter_.setText("Open");
getContentPane().add(toggleButtonShutter_);
springLayout_.putConstraint(SpringLayout.EAST, toggleButtonShutter_,
275, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, toggleButtonShutter_,
203, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_,
138 - 21, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonShutter_,
117 - 21, SpringLayout.NORTH, getContentPane());
// Active shutter label
final JLabel activeShutterLabel = new JLabel();
activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10));
activeShutterLabel.setText("Shutter");
getContentPane().add(activeShutterLabel);
springLayout_.putConstraint(SpringLayout.SOUTH, activeShutterLabel,
108 - 22, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, activeShutterLabel,
95 - 22, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, activeShutterLabel,
160 - 2, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, activeShutterLabel,
113 - 2, SpringLayout.WEST, getContentPane());
// Active shutter Combo Box
shutterComboBox_ = new JComboBox();
shutterComboBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return;
}
});
getContentPane().add(shutterComboBox_);
springLayout_.putConstraint(SpringLayout.SOUTH, shutterComboBox_,
114 - 22, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, shutterComboBox_,
92 - 22, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, shutterComboBox_, 275,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, shutterComboBox_, 170,
SpringLayout.WEST, getContentPane());
menuBar_ = new JMenuBar();
setJMenuBar(menuBar_);
final JMenu fileMenu = new JMenu();
fileMenu.setText("File");
menuBar_.add(fileMenu);
final JMenuItem openMenuItem = new JMenuItem();
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
new Thread() {
public void run() {
openAcquisitionData();
}
}.start();
}
});
openMenuItem.setText("Open Acquisition Data as Image5D......");
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
final JMenuItem loadState = new JMenuItem();
loadState.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemState();
}
});
loadState.setText("Load System State...");
fileMenu.add(loadState);
final JMenuItem saveStateAs = new JMenuItem();
fileMenu.add(saveStateAs);
saveStateAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSystemState();
}
});
saveStateAs.setText("Save System State As...");
fileMenu.addSeparator();
final JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeSequence();
}
});
fileMenu.add(exitMenuItem);
exitMenuItem.setText("Exit");
final JMenu image5dMenu = new JMenu();
image5dMenu.setText("Image5D");
menuBar_.add(image5dMenu);
final JMenuItem closeAllMenuItem = new JMenuItem();
closeAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
WindowManager.closeAllWindows();
}
});
closeAllMenuItem.setText("Close All");
image5dMenu.add(closeAllMenuItem);
final JMenuItem duplicateMenuItem = new JMenuItem();
duplicateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Duplicate_Image5D duplicate = new Duplicate_Image5D();
duplicate.run("");
}
});
duplicateMenuItem.setText("Duplicate");
image5dMenu.add(duplicateMenuItem);
final JMenuItem cropMenuItem = new JMenuItem();
cropMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Crop_Image5D crop = new Crop_Image5D();
crop.run("");
}
});
cropMenuItem.setText("Crop");
image5dMenu.add(cropMenuItem);
final JMenuItem makeMontageMenuItem = new JMenuItem();
makeMontageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Make_Montage makeMontage = new Make_Montage();
makeMontage.run("");
}
});
makeMontageMenuItem.setText("Make Montage");
image5dMenu.add(makeMontageMenuItem);
final JMenuItem zProjectMenuItem = new JMenuItem();
zProjectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Z_Project projection = new Z_Project();
projection.run("");
}
});
zProjectMenuItem.setText("Z Project");
image5dMenu.add(zProjectMenuItem);
final JMenuItem convertToRgbMenuItem = new JMenuItem();
convertToRgbMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB();
stackToRGB.run("");
}
});
convertToRgbMenuItem.setText("Copy to RGB Stack(z)");
image5dMenu.add(convertToRgbMenuItem);
final JMenuItem convertToRgbtMenuItem = new JMenuItem();
convertToRgbtMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t();
stackToRGB_t.run("");
}
});
convertToRgbtMenuItem.setText("Copy to RGB Stack(t)");
image5dMenu.add(convertToRgbtMenuItem);
final JMenuItem convertToStackMenuItem = new JMenuItem();
convertToStackMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_Stack image5DToStack = new Image5D_to_Stack();
image5DToStack.run("");
}
});
convertToStackMenuItem.setText("Copy to Stack");
image5dMenu.add(convertToStackMenuItem);
final JMenuItem convertToStacksMenuItem = new JMenuItem();
convertToStacksMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks();
image5DToStacks.run("");
}
});
convertToStacksMenuItem.setText("Copy to Stacks (channels)");
image5dMenu.add(convertToStacksMenuItem);
final JMenuItem volumeViewerMenuItem = new JMenuItem();
volumeViewerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer();
volumeViewer.run("");
}
});
volumeViewerMenuItem.setText("VolumeViewer");
image5dMenu.add(volumeViewerMenuItem);
final JMenuItem splitImageMenuItem = new JMenuItem();
splitImageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Split_Image5D splitImage = new Split_Image5D();
splitImage.run("");
}
});
splitImageMenuItem.setText("SplitView");
image5dMenu.add(splitImageMenuItem);
final JMenu toolsMenu = new JMenu();
toolsMenu.setText("Tools");
menuBar_.add(toolsMenu);
final JMenuItem refreshMenuItem = new JMenuItem();
refreshMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/arrow_refresh.png"));
refreshMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateGUI(true);
}
});
refreshMenuItem.setText("Refresh GUI");
toolsMenu.add(refreshMenuItem);
final JMenuItem rebuildGuiMenuItem = new JMenuItem();
rebuildGuiMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initializeGUI();
}
});
rebuildGuiMenuItem.setText("Rebuild GUI");
toolsMenu.add(rebuildGuiMenuItem);
toolsMenu.addSeparator();
final JMenuItem scriptPanelMenuItem = new JMenuItem();
toolsMenu.add(scriptPanelMenuItem);
scriptPanelMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createScriptPanel();
}
});
scriptPanelMenuItem.setText("Script Panel...");
final JMenuItem propertyEditorMenuItem = new JMenuItem();
toolsMenu.add(propertyEditorMenuItem);
propertyEditorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createPropertyEditor();
}
});
propertyEditorMenuItem.setText("Device/Property Browser...");
toolsMenu.addSeparator();
final JMenuItem xyListMenuItem = new JMenuItem();
xyListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showXYPositionList();
}
});
xyListMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/application_view_list.png"));
xyListMenuItem.setText("XY List...");
toolsMenu.add(xyListMenuItem);
final JMenuItem acquisitionMenuItem = new JMenuItem();
acquisitionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
acquisitionMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/film.png"));
acquisitionMenuItem.setText("Multi-Dimensional Acquisition...");
toolsMenu.add(acquisitionMenuItem);
final JMenuItem sequenceMenuItem = new JMenuItem();
sequenceMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openSequenceDialog();
}
});
sequenceMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/film_go.png"));
sequenceMenuItem.setText("Burst Acquisition...");
toolsMenu.add(sequenceMenuItem);
final JMenuItem splitViewMenuItem = new JMenuItem();
splitViewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitViewDialog();
}
});
splitViewMenuItem.setText("Split View...");
toolsMenu.add(splitViewMenuItem);
centerAndDragMenuItem_ = new JCheckBoxMenuItem();
centerAndDragMenuItem_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (centerAndDragListener_ == null) {
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
}
if (!centerAndDragListener_.isRunning()) {
centerAndDragListener_.start();
centerAndDragMenuItem_.setSelected(true);
} else {
centerAndDragListener_.stop();
centerAndDragMenuItem_.setSelected(false);
}
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
});
centerAndDragMenuItem_.setText("Mouse Moves Stage");
centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
toolsMenu.add(centerAndDragMenuItem_);
toolsMenu.addSeparator();
final JMenuItem configuratorMenuItem = new JMenuItem();
configuratorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
ConfiguratorDlg configurator = new ConfiguratorDlg(core_,
sysConfigFile_);
configurator.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = configurator.getFileName();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
});
configuratorMenuItem.setText("Hardware Configuration Wizard...");
toolsMenu.add(configuratorMenuItem);
final JMenuItem calibrationMenuItem = new JMenuItem();
toolsMenu.add(calibrationMenuItem);
calibrationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createCalibrationListDlg();
}
});
calibrationMenuItem.setText("Pixel Size Calibration...");
toolsMenu.add(calibrationMenuItem);
final JMenuItem loadSystemConfigMenuItem = new JMenuItem();
toolsMenu.add(loadSystemConfigMenuItem);
loadSystemConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadConfiguration();
initializeGUI();
}
});
loadSystemConfigMenuItem.setText("Load Hardware Configuration...");
final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem();
saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
updateChannelCombos();
}
});
saveConfigurationPresetsMenuItem.setText("Save Configuration Settings...");
toolsMenu.add(saveConfigurationPresetsMenuItem);
final JMenuItem optionsMenuItem = new JMenuItem();
final MMStudioMainFrame thisInstance = this;
optionsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
int oldBufsize = options_.circularBufferSizeMB;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
optionsMenuItem.setText("Options...");
toolsMenu.add(optionsMenuItem);
final JLabel binningLabel = new JLabel();
binningLabel.setFont(new Font("Arial", Font.PLAIN, 10));
binningLabel.setText("Binning");
getContentPane().add(binningLabel);
springLayout_.putConstraint(SpringLayout.SOUTH, binningLabel, 64,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, binningLabel, 43,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1,
SpringLayout.WEST, getContentPane());
labelImageDimensions_ = new JLabel();
labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10));
getContentPane().add(labelImageDimensions_);
springLayout_.putConstraint(SpringLayout.SOUTH, labelImageDimensions_,
-5, SpringLayout.SOUTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, labelImageDimensions_,
-25, SpringLayout.SOUTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, labelImageDimensions_,
-5, SpringLayout.EAST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, labelImageDimensions_,
5, SpringLayout.WEST, getContentPane());
comboBinning_ = new JComboBox();
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
getContentPane().add(comboBinning_);
springLayout_.putConstraint(SpringLayout.EAST, comboBinning_, 275,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, comboBinning_, 200,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.SOUTH, comboBinning_, 66,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, comboBinning_, 43,
SpringLayout.NORTH, getContentPane());
final JLabel cameraSettingsLabel = new JLabel();
cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11));
cameraSettingsLabel.setText("Camera settings");
getContentPane().add(cameraSettingsLabel);
springLayout_.putConstraint(SpringLayout.EAST, cameraSettingsLabel,
211, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, cameraSettingsLabel,
109, SpringLayout.WEST, getContentPane());
configPad_ = new ConfigGroupPad();
// configPad_.setDisplayStyle(options_.displayBackground, guiColors_);
configPad_.setFont(new Font("", Font.PLAIN, 10));
getContentPane().add(configPad_);
springLayout_.putConstraint(SpringLayout.EAST, configPad_, -4,
SpringLayout.EAST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, configPad_, 5,
SpringLayout.EAST, comboBinning_);
springLayout_.putConstraint(SpringLayout.SOUTH, configPad_, 156,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, configPad_, 21,
SpringLayout.NORTH, getContentPane());
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(this);
getContentPane().add(configPadButtonPanel_);
springLayout_.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4,
SpringLayout.EAST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5,
SpringLayout.EAST, comboBinning_);
springLayout_.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, 158,
SpringLayout.NORTH, getContentPane());
final JLabel stateDeviceLabel = new JLabel();
stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11));
stateDeviceLabel.setText("Configuration settings");
getContentPane().add(stateDeviceLabel);
springLayout_.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0,
SpringLayout.SOUTH, cameraSettingsLabel);
springLayout_.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0,
SpringLayout.NORTH, cameraSettingsLabel);
springLayout_.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150,
SpringLayout.WEST, configPad_);
springLayout_.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0,
SpringLayout.WEST, configPad_);
final JButton buttonAcqSetup = new JButton();
buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2));
buttonAcqSetup.setIconTextGap(1);
buttonAcqSetup.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/film.png"));
buttonAcqSetup.setToolTipText("Open Acquistion dialog");
buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAcqSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
buttonAcqSetup.setText("Multi-D Acq.");
getContentPane().add(buttonAcqSetup);
springLayout_.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7,
SpringLayout.WEST, getContentPane());
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.setAutoShutter(autoShutterCheckBox_.isSelected());
if (shutterLabel_.length() > 0) {
try {
setShutterButton(core_.getShutterOpen());
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
getContentPane().add(autoShutterCheckBox_);
springLayout_.putConstraint(SpringLayout.EAST, autoShutterCheckBox_,
202 - 3, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, autoShutterCheckBox_,
110 - 3, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_,
141 - 22, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_,
118 - 22, SpringLayout.NORTH, getContentPane());
final JButton burstButton = new JButton();
burstButton.setMargin(new Insets(2, 2, 2, 2));
burstButton.setIconTextGap(1);
burstButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/film_go.png"));
burstButton.setFont(new Font("Arial", Font.PLAIN, 10));
burstButton.setToolTipText("Open Burst dialog for fast sequence acquisition");
burstButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openSequenceDialog();
}
});
burstButton.setText("Burst");
getContentPane().add(burstButton);
springLayout_.putConstraint(SpringLayout.SOUTH, burstButton, 113,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, burstButton, 92,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, burstButton, 95,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, burstButton, 7,
SpringLayout.WEST, getContentPane());
final JButton refreshButton = new JButton();
refreshButton.setMargin(new Insets(2, 2, 2, 2));
refreshButton.setIconTextGap(1);
refreshButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_refresh.png"));
refreshButton.setFont(new Font("Arial", Font.PLAIN, 10));
refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware");
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateGUI(true);
}
});
refreshButton.setText("Refresh");
getContentPane().add(refreshButton);
springLayout_.putConstraint(SpringLayout.SOUTH, refreshButton, 135,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, refreshButton, 114,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, refreshButton, 95,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, refreshButton, 7,
SpringLayout.WEST, getContentPane());
// add window listeners
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
running_ = false;
closeSequence();
}
public void windowOpened(WindowEvent e) {
// initialize hardware
core_ = new CMMCore();
ReportingUtils.setCore(core_);
core_.enableDebugLog(options_.debugLogEnabled);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
cameraLabel_ = new String("");
shutterLabel_ = new String("");
zStageLabel_ = new String("");
xyStageLabel_ = new String("");
engine_ = new MMAcquisitionEngineMT();
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
// load configuration from the file
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE,
sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
if (!options_.doNotAskForConfigFile) {
MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
// introDlg.setScriptFile(startupScriptFile_);
introDlg.setVisible(true);
sysConfigFile_ = introDlg.getConfigFile();
}
//save the just-selected configfile in the preferences
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
// put the selected config file at the top of the list
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
// startupScriptFile_ = introDlg.getScriptFile();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
// mainPrefs_.put(STARTUP_SCRIPT_FILE, startupScriptFile_);
paint(MMStudioMainFrame.this.getGraphics());
afMgr_ = new AutofocusManager(core_);
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// TODO: If there is an error loading the config file, make sure
// we prompt next time at startup
loadSystemConfiguration();
executeStartupScript();
loadPlugins();
toFront();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
initializeGUI();
initializePluginMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
}
});
final JButton setRoiButton = new JButton();
setRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/shape_handles.png"));
setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle");
setRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setROI();
}
});
getContentPane().add(setRoiButton);
springLayout_.putConstraint(SpringLayout.EAST, setRoiButton, 37,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, setRoiButton, 7,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.SOUTH, setRoiButton, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, setRoiButton, 154,
SpringLayout.NORTH, getContentPane());
final JButton clearRoiButton = new JButton();
clearRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_out.png"));
clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
clearRoiButton.setToolTipText("Reset Region of Interest to full frame");
clearRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearROI();
}
});
getContentPane().add(clearRoiButton);
springLayout_.putConstraint(SpringLayout.EAST, clearRoiButton, 70,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, clearRoiButton, 40,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, clearRoiButton, 154,
SpringLayout.NORTH, getContentPane());
final JLabel regionOfInterestLabel = new JLabel();
regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel.setText("ROI");
getContentPane().add(regionOfInterestLabel);
springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel,
154, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel,
140, SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel,
71, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel,
8, SpringLayout.WEST, getContentPane());
contrastPanel_ = new ContrastPanel();
contrastPanel_.setFont(new Font("", Font.PLAIN, 10));
contrastPanel_.setContrastStretch(stretch);
contrastPanel_.setBorder(new LineBorder(Color.black, 1, false));
getContentPane().add(contrastPanel_);
springLayout_.putConstraint(SpringLayout.SOUTH, contrastPanel_, -26,
SpringLayout.SOUTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, contrastPanel_, 176,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, contrastPanel_, -5,
SpringLayout.EAST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, contrastPanel_, 7,
SpringLayout.WEST, getContentPane());
final JLabel regionOfInterestLabel_1 = new JLabel();
regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel_1.setText("Zoom");
getContentPane().add(regionOfInterestLabel_1);
springLayout_.putConstraint(SpringLayout.SOUTH,
regionOfInterestLabel_1, 154, SpringLayout.NORTH,
getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH,
regionOfInterestLabel_1, 140, SpringLayout.NORTH,
getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1,
139, SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1,
81, SpringLayout.WEST, getContentPane());
final JButton zoomInButton = new JButton();
zoomInButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomIn();
}
});
zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_in.png"));
zoomInButton.setToolTipText("Zoom in");
zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10));
getContentPane().add(zoomInButton);
springLayout_.putConstraint(SpringLayout.SOUTH, zoomInButton, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, zoomInButton, 154,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, zoomInButton, 110,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, zoomInButton, 80,
SpringLayout.WEST, getContentPane());
final JButton zoomOutButton = new JButton();
zoomOutButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomOut();
}
});
zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_out.png"));
zoomOutButton.setToolTipText("Zoom out");
zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10));
getContentPane().add(zoomOutButton);
springLayout_.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, zoomOutButton, 154,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, zoomOutButton, 143,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, zoomOutButton, 113,
SpringLayout.WEST, getContentPane());
// Profile
final JLabel profileLabel_ = new JLabel();
profileLabel_.setFont(new Font("Arial", Font.BOLD, 11));
profileLabel_.setText("Profile");
getContentPane().add(profileLabel_);
springLayout_.putConstraint(SpringLayout.SOUTH, profileLabel_, 154,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, profileLabel_, 140,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, profileLabel_, 217,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, profileLabel_, 154,
SpringLayout.WEST, getContentPane());
final JButton buttonProf = new JButton();
buttonProf.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/chart_curve.png"));
buttonProf.setFont(new Font("Arial", Font.PLAIN, 10));
buttonProf.setToolTipText("Open line profile window (requires line selection)");
buttonProf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openLineProfileWindow();
}
});
// buttonProf.setText("Profile");
getContentPane().add(buttonProf);
springLayout_.putConstraint(SpringLayout.SOUTH, buttonProf, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, buttonProf, 154,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, buttonProf, 183,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, buttonProf, 153,
SpringLayout.WEST, getContentPane());
// Autofocus
final JLabel autofocusLabel_ = new JLabel();
autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11));
autofocusLabel_.setText("Autofocus");
getContentPane().add(autofocusLabel_);
springLayout_.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, autofocusLabel_, 274,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, autofocusLabel_, 194,
SpringLayout.WEST, getContentPane());
buttonAutofocus_ = new JButton();
buttonAutofocus_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/find.png"));
buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocus_.setToolTipText("Autofocus now");
buttonAutofocus_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (afMgr_.getDevice() != null) {
try {
afMgr_.getDevice().fullFocus(); // or any other method from Autofocus.java API
} catch (MMException mE) {
ReportingUtils.showError(mE);
}
}
}
});
getContentPane().add(buttonAutofocus_);
springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193,
SpringLayout.WEST, getContentPane());
buttonAutofocusTools_ = new JButton();
buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/wrench_orange.png"));
buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocusTools_.setToolTipText("Set autofocus options");
buttonAutofocusTools_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAutofocusDialog();
}
});
getContentPane().add(buttonAutofocusTools_);
springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256,
SpringLayout.WEST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226,
SpringLayout.WEST, getContentPane());
/*
final JButton editPreset_ = new JButton();
editPreset_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (configPad_.editPreset()) {
configChanged_ = true;
updateGUI(true);
setConfigSaveButtonStatus(configChanged_);
}
}
});
editPreset_.setToolTipText("Edit selected preset");
editPreset_.setText("Edit");
getContentPane().add(editPreset_);
springLayout_.putConstraint(SpringLayout.SOUTH, editPreset_, 20,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, editPreset_, 2,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, editPreset_, -85,
SpringLayout.EAST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, editPreset_, -160,
SpringLayout.EAST, getContentPane());
*/
saveConfigButton_ = new JButton();
saveConfigButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
}
});
saveConfigButton_.setToolTipText("Save current presets to the configuration file");
saveConfigButton_.setText("Save");
saveConfigButton_.setEnabled(false);
getContentPane().add(saveConfigButton_);
springLayout_.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2,
SpringLayout.NORTH, getContentPane());
springLayout_.putConstraint(SpringLayout.EAST, saveConfigButton_, -5,
SpringLayout.EAST, getContentPane());
springLayout_.putConstraint(SpringLayout.WEST, saveConfigButton_, -80,
SpringLayout.EAST, getContentPane());
/*
* final JButton xyListButton_ = new JButton();
* xyListButton_.setIcon(SwingResourceManager.getIcon(
* MMStudioMainFrame.class, "icons/application_view_list.png"));
* xyListButton_.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent arg0) { showXYPositionList(); } });
* xyListButton_
* .setToolTipText("Refresh all GUI controls directly from the hardware"
* ); xyListButton_.setFont(new Font("Arial", Font.PLAIN, 10));
* xyListButton_.setText("XY List");
* getContentPane().add(xyListButton_);
* springLayout_.putConstraint(SpringLayout.EAST, xyListButton_, 95,
* SpringLayout.WEST, getContentPane());
* springLayout_.putConstraint(SpringLayout.WEST, xyListButton_, 7,
* SpringLayout.WEST, getContentPane());
* springLayout_.putConstraint(SpringLayout.SOUTH, xyListButton_, 135,
* SpringLayout.NORTH, getContentPane());
* springLayout_.putConstraint(SpringLayout.NORTH, xyListButton_, 114,
* SpringLayout.NORTH, getContentPane());
*/
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + "
}
if (options_.debugLogEnabled) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (IsLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
public void makeActive() {
toFront();
}
private void setExposure() {
try {
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
// Interval for Live Mode changes as well
setLiveModeInterval();
} catch (Exception exp) {
// Do nothing.
}
}
private void updateTitle() {
this.setTitle("System: " + sysConfigFile_);
}
public void updateHistogram() {
// !!! ImagePlus imp = WindowManager.getCurrentImage();
if (isImageWindowOpen()) {
ImagePlus imp = imageWin_.getImagePlus();
if (imp != null) {
contrastPanel_.setContrastSettings(MMImageWindow.getContrastSettings8(), MMImageWindow.getContrastSettings16());
contrastPanel_.update();
}
}
}
private void updateLineProfile() {
if (!isImageWindowOpen() || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (imageWin_ == null || imageWin_.isClosed()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground)));
profileWin_.setVisible(true);
}
public Rectangle getROI() throws Exception {
// ROI values are give as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
core_.getROI(a[0], a[1], a[2], a[3]);
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
public void setROI(Rectangle r) throws Exception {
boolean liveRunning = false;
if (liveRunning_) {
liveRunning = liveRunning_;
enableLiveMode(false);
}
core_.setROI(r.x, r.y, r.width, r.height);
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBoundingRect();
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (liveRunning_) {
liveRunning = liveRunning_;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private BooleanLock creatingImageWindow_ = new BooleanLock(false);
private static long waitForCreateImageWindowTimeout_ = 5000;
private MMImageWindow createImageWindow() {
if (creatingImageWindow_.isTrue()) {
try {
creatingImageWindow_.waitToSetFalse(waitForCreateImageWindowTimeout_);
} catch (Exception e) {
ReportingUtils.showError(e);
}
return imageWin_;
}
creatingImageWindow_.setValue(true);
MMImageWindow win = imageWin_;
imageWin_ = null;
try {
if (win != null) {
win.saveAttributes();
WindowManager.removeWindow(imageWin_);
win.dispose();
win = null;
}
win = new MMImageWindow(core_, this, contrastPanel_);
core_.logMessage("createImageWin1");
win.setBackground(guiColors_.background.get((options_.displayBackground)));
setIJCal(win);
// listeners
if (centerAndDragListener_ != null
&& centerAndDragListener_.isRunning()) {
centerAndDragListener_.attach(win.getImagePlus().getWindow());
}
if (zWheelListener_ != null && zWheelListener_.isRunning()) {
zWheelListener_.attach(win.getImagePlus().getWindow());
}
if (xyzKeyListener_ != null && xyzKeyListener_.isRunning()) {
xyzKeyListener_.attach(win.getImagePlus().getWindow());
}
win.getCanvas().requestFocus();
imageWin_ = win;
} catch (Exception e) {
if (win != null) {
win.saveAttributes();
WindowManager.removeWindow(win);
win.dispose();
}
ReportingUtils.showError(e);
}
creatingImageWindow_.setValue(false);
return imageWin_;
}
/**
* Returns instance of the core uManager object;
*/
public CMMCore getMMCore() {
return core_;
}
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
JFileChooser fc = new JFileChooser();
boolean saveFile = true;
File f;
do {
fc.setSelectedFile(new File(model.getFileName()));
int retVal = fc.showSaveDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
f = fc.getSelectedFile();
// check if file already exists
if (f.exists()) {
int sel = JOptionPane.showConfirmDialog(this,
"Overwrite " + f.getName(), "File Save",
JOptionPane.YES_NO_OPTION);
if (sel == JOptionPane.YES_OPTION) {
saveFile = true;
} else {
saveFile = false;
}
}
} else {
return;
}
} while (saveFile == false);
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
private File runAcquisitionBrowser() {
try {
String filename = NativeGUI.runMDABrowser(openAcqDirectory_);
if (filename.length()>0) {
return new File(filename);
} else {
return null;
}
} catch (Exception ex) {
ReportingUtils.logError(ex);
return null;
}
}
/**
* Open an existing acquisition directory and build image5d window.
*
*/
protected void openAcquisitionData() {
// choose the directory
File f = runAcquisitionBrowser();
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
ProgressBar progressBar = new ProgressBar("Opening File...", 0, 1);
AcquisitionData ad = new AcquisitionData();
try {
// attempt to open metafile
ad.load(openAcqDirectory_);
progressBar.setRange(0, ad.getNumberOfChannels()
* ad.getNumberOfFrames() * ad.getNumberOfSlices());
Image5D img5d = null;
if (!virtual_) {
// create image 5d
img5d = new Image5D(openAcqDirectory_, ad.getImageJType(), ad.getImageWidth(), ad.getImageHeight(), ad.getNumberOfChannels(), ad.getNumberOfSlices(), ad.getNumberOfFrames(), false);
img5d.setCalibration(ad.ijCal());
applyChannelSettingsTo5D(ad, img5d);
// set pixels
int singleImageCounter = 0;
for (int i = 0; i < ad.getNumberOfFrames(); i++) {
for (int j = 0; j < ad.getNumberOfChannels(); j++) {
for (int k = 0; k < ad.getNumberOfSlices(); k++) {
++singleImageCounter;
img5d.setCurrentPosition(0, 0, j, k, i);
// read the file
// insert pixels into the 5d image
Object img = ad.getPixels(i, j, k);
if (img != null) {
img5d.setPixels(img);
set5DDisplaySettingsForChannels(k, i, ad, j, img5d);
} else {
// gap detected, let's try to fill in by using
// the most recent channel data
// NOTE: we assume that the gap is only in the
// frame or slice dimension
// we don't know how to deal with channel gaps
if (i > 0) {
Object previousImg = img5d.getPixels(j + 1,
k + 1, i);
if (previousImg != null) {
img5d.setPixels(previousImg, j + 1,
k + 1, i + 1);
}
}
if (k > 0) {
Object previousImg = img5d.getPixels(j + 1,
k, i + 1);
if (previousImg != null) {
img5d.setPixels(previousImg, j + 1,
k + 1, i + 1);
}
}
}
}
}
progressBar.setProgress(singleImageCounter);
progressBar.repaint();
}
} else {
VirtualStack virtualStack = new VirtualStack(ad.getImageWidth(),
ad.getImageHeight(), null, ad.getBasePath());
for (int i = 0; i < ad.getNumberOfFrames(); i++) {
for (int j = 0; j < ad.getNumberOfChannels(); j++) {
for (int k = 0; k < ad.getNumberOfSlices(); k++) {
virtualStack.addSlice(ad.getImageFileName(i, j, k));
}
}
}
img5d = new Image5D(openAcqDirectory_,virtualStack,
ad.getNumberOfChannels(),ad.getNumberOfSlices(),
ad.getNumberOfFrames());
img5d.setCalibration(ad.ijCal());
applyChannelSettingsTo5D(ad, img5d);
}
popUpImage5DWindow(img5d, ad);
} catch (MMAcqDataException e) {
ReportingUtils.showError(e);
} finally {
if (progressBar != null) {
progressBar.setVisible(false);
progressBar = null;
}
}
}
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (liveRunning_) {
liveRunning = liveRunning_;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// calibrationListDlg_.setCore(core_);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
scriptPanel_.setVisible(true);
}
private void updateStaticInfoFromCache() {
String dimText = "Image size: " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
/*
private void updateStaticInfo() {
try {
double zPos = 0.0;
String dimText = "Image size: " + core_.getImageWidth() + " X "
+ core_.getImageHeight() + " X " + core_.getBytesPerPixel()
+ ", Intensity range: " + core_.getImageBitDepth()
+ " bits";
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0.0)
dimText += ", " + TextUtils.FMT0.format(pixSizeUm * 1000)
+ "nm/pix";
else
dimText += ", uncalibrated";
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
dimText += ", Z=" + TextUtils.FMT2.format(zPos) + "um";
}
if (xyStageLabel_.length() > 0) {
double x[] = new double[1];
double y[] = new double[1];
core_.getXYPosition(xyStageLabel_, x, y);
dimText += ", XY=(" + TextUtils.FMT2.format(x[0]) + ","
+ TextUtils.FMT2.format(y[0]) + ")um";
}
labelImageDimensions_.setText(dimText);
} catch (Exception e) {
handleException(e);
}
}
*/
private void setShutterButton(boolean state) {
if (state) {
toggleButtonShutter_.setSelected(true);
toggleButtonShutter_.setText("Close");
} else {
toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
}
}
// public interface available for scripting access
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
if (imageWin_ == null) {
return;
}
imageWin_.getImagePlus().getProcessor().setPixels(obj);
}
public int getImageHeight() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getHeight();
}
return 0;
}
public int getImageWidth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getWidth();
}
return 0;
}
public int getImageDepth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getBitDepth();
}
return 0;
}
public ImageProcessor getImageProcessor() {
if (imageWin_ == null) {
return null;
}
return imageWin_.getImagePlus().getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
public boolean isImageWindowOpen() {
boolean ret = imageWin_ != null;
ret = ret && !imageWin_.isClosed();
if (ret) {
try {
Graphics g = imageWin_.getGraphics();
if (null != g) {
int ww = imageWin_.getWidth();
g.clearRect(0, 0, ww, 40);
imageWin_.drawInfo(g);
} else {
// explicitly clean up if Graphics is null, rather
// than cleaning up in the exception handler below..
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ret = false;
}
} catch (Exception e) {
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ReportingUtils.showError(e);
ret = false;
}
}
return ret;
}
public void updateImageGUI() {
updateHistogram();
}
boolean IsLiveModeOn() {
return liveModeTimer_ != null && liveModeTimer_.isRunning();
}
public void enableLiveMode(boolean enable) {
if (enable) {
if (IsLiveModeOn()) {
return;
}
try {
if (!isImageWindowOpen() && creatingImageWindow_.isFalse()) {
imageWin_ = createImageWindow();
}
// this is needed to clear the subtitle, should be folded into
// drawInfo
imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(),
40);
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.toFront();
// turn off auto shutter and open the shutter
autoShutterOrg_ = core_.getAutoShutter();
if (shutterLabel_.length() > 0) {
shutterOrg_ = core_.getShutterOpen();
}
core_.setAutoShutter(false);
// Hide the autoShutter Checkbox
autoShutterCheckBox_.setEnabled(false);
shutterLabel_ = core_.getShutterDevice();
// only open the shutter when we have one and the Auto shutter
// checkbox was checked
if ((shutterLabel_.length() > 0) && autoShutterOrg_) {
core_.setShutterOpen(true);
}
// attach mouse wheel listener to control focus:
if (zWheelListener_ == null) {
zWheelListener_ = new ZWheelListener(core_, this);
}
zWheelListener_.start(imageWin_);
// attach key listener to control the stage and focus:
if (xyzKeyListener_ == null) {
xyzKeyListener_ = new XYZKeyListener(core_, this);
}
xyzKeyListener_.start(imageWin_);
// Do not display more often than dictated by the exposure time
setLiveModeInterval();
liveModeFullyStarted_ = false;
core_.startContinuousSequenceAcquisition(0.0);
liveModeTimer_.start();
// Only hide the shutter checkbox if we are in autoshuttermode
buttonSnap_.setEnabled(false);
if (autoShutterOrg_) {
toggleButtonShutter_.setEnabled(false);
}
imageWin_.setSubTitle("Live (running)");
liveRunning_ = true;
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to enable live mode.");
if (imageWin_ != null) {
imageWin_.saveAttributes();
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
} else {
if (!IsLiveModeOn()) {
return;
}
try {
liveModeTimer_.stop();
core_.stopSequenceAcquisition();
if (zWheelListener_ != null) {
zWheelListener_.stop();
}
if (xyzKeyListener_ != null) {
xyzKeyListener_.stop();
}
// restore auto shutter and close the shutter
if (shutterLabel_.length() > 0) {
core_.setShutterOpen(shutterOrg_);
}
core_.setAutoShutter(autoShutterOrg_);
if (autoShutterOrg_) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
liveRunning_ = false;
buttonSnap_.setEnabled(true);
autoShutterCheckBox_.setEnabled(true);
while (liveModeTimer_.isRunning()); // Make sure Timer properly stops.
// This is here to avoid crashes when changing ROI in live mode
// with Sensicam
// Should be removed when underlying problem is dealt with
Thread.sleep(100);
imageWin_.setSubTitle("Live (stopped)");
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to disable live mode.");
if (imageWin_ != null) {
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
}
toggleButtonLive_.setIcon(IsLiveModeOn() ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setSelected(IsLiveModeOn());
toggleButtonLive_.setText(IsLiveModeOn() ? "Stop Live" : "Live");
}
public boolean getLiveMode() {
return liveRunning_;
}
public boolean updateImage() {
try {
if (!isImageWindowOpen()) {
// stop live acquistion if the window is not open
if (IsLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do
}
}
long channels = core_.getNumberOfComponents();
core_.snapImage();
Object img;
if (channels == 1) {
img = core_.getImage();
} else {
img = core_.getRGB32Image();
}
if (imageWin_.windowNeedsResizing()) {
createImageWindow();
}
if (!isCurrentImageFormatSupported()) {
return false;
}
imageWin_.newImage(img);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(Object pixels) {
try {
if (!isImageWindowOpen()
|| imageWin_.getImageWindowByteLength()
!= imageWin_.imageByteLenth(pixels)
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
imageWin_.newImage(pixels);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
try {
if (!isImageWindowOpen()
|| imageWin_.getImageWindowByteLength()
!= imageWin_.imageByteLenth(pixels)
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
imageWin_.newImageWithStatusLine(pixels, statusLine);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public void displayStatusLine(String statusLine) {
try {
if (isImageWindowOpen()) {
imageWin_.displayStatusLine(statusLine);
}
} catch (Exception e) {
ReportingUtils.logError(e);
return;
}
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
private void doSnap() {
try {
Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitCursor);
if (!isImageWindowOpen()) {
imageWin_ = createImageWindow();
}
imageWin_.toFront();
setIJCal(imageWin_);
// this is needed to clear the subtite, should be folded into
// drawInfo
imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40);
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.setSubTitle("Snap");
String expStr = textFieldExp_.getText();
if (expStr.length() > 0) {
core_.setExposure(NumberUtils.displayStringToDouble(expStr));
updateImage();
} else {
handleError("Exposure field is empty!");
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(defaultCursor);
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.size() == 0) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
// System.println(DeviceType.ShutterDevice);
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
// items[0] = "";
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null);
buttonAutofocus_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
// Mouse moves stage
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
if (centerAndDragMenuItem_.isSelected()) {
centerAndDragListener_.start();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getVersion() {
return VERSION;
}
private void initializePluginMenu() {
// add plugin menu items
if (plugins_.size() > 0) {
final JMenu pluginMenu = new JMenu();
pluginMenu.setText("Plugins");
menuBar_.add(pluginMenu);
for (int i = 0; i < plugins_.size(); i++) {
final JMenuItem newMenuItem = new JMenuItem();
newMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
ReportingUtils.logMessage("Plugin command: "
+ e.getActionCommand());
// find the coresponding plugin
for (int i = 0; i < plugins_.size(); i++) {
if (plugins_.get(i).menuItem.equals(e.getActionCommand())) {
PluginItem plugin = plugins_.get(i);
plugin.instantiate();
plugin.plugin.show();
break;
}
}
// if (plugins_.get(i).plugin == null) {
// hcsPlateEditor_ = new
// PlateEditor(MMStudioMainFrame.this);
// hcsPlateEditor_.setVisible(true);
}
});
newMenuItem.setText(plugins_.get(i).menuItem);
pluginMenu.add(newMenuItem);
}
}
// add help menu item
final JMenu helpMenu = new JMenu();
helpMenu.setText("Help");
menuBar_.add(helpMenu);
final JMenuItem usersGuideMenuItem = new JMenuItem();
usersGuideMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/documentation.php?object=Userguide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
usersGuideMenuItem.setText("User's Guide...");
helpMenu.add(usersGuideMenuItem);
final JMenuItem configGuideMenuItem = new JMenuItem();
configGuideMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/documentation.php?object=Configguide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
configGuideMenuItem.setText("Configuration Guide...");
helpMenu.add(configGuideMenuItem);
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
final JMenuItem registerMenuItem = new JMenuItem();
registerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
registerMenuItem.setText("Register your copy of Micro-Manager...");
helpMenu.add(registerMenuItem);
}
final JMenuItem aboutMenuItem = new JMenuItem();
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + VERSION;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
aboutMenuItem.setText("About...");
helpMenu.add(aboutMenuItem);
}
public void updateGUI(boolean updateConfigPadStructure) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
GUIUtils.setComboSelection(comboBinning_, binSize);
long bitDepth = 8;
if (imageWin_ != null) {
long hsz = imageWin_.getRawHistogramSize();
bitDepth = (long) Math.log(hsz);
}
bitDepth = core_.getImageBitDepth();
contrastPanel_.setPixelBitDepth((int) bitDepth, false);
}
if (!liveModeTimer_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
autoShutterOrg_ = core_.getAutoShutter();
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
public boolean okToAcquire() {
return !liveModeTimer_.isRunning();
}
public void stopAllActivity() {
enableLiveMode(false);
}
public void refreshImage() {
if (imageWin_ != null) {
imageWin_.getImagePlus().updateAndDraw();
}
}
private void cleanupOnClose() {
// NS: Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
}
liveModeTimer_.stop();
if (imageWin_ != null) {
imageWin_.close();
imageWin_.dispose();
imageWin_ = null;
}
if (profileWin_ != null) {
profileWin_.dispose();
}
if (scriptPanel_ != null) {
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
try {
core_.reset();
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putDouble(CONTRAST_SETTINGS_8_MIN, MMImageWindow.getContrastSettings8().min);
mainPrefs_.putDouble(CONTRAST_SETTINGS_8_MAX, MMImageWindow.getContrastSettings8().max);
mainPrefs_.putDouble(CONTRAST_SETTINGS_16_MIN, MMImageWindow.getContrastSettings16().min);
mainPrefs_.putDouble(CONTRAST_SETTINGS_16_MAX, MMImageWindow.getContrastSettings16().max);
mainPrefs_.putBoolean(MAIN_STRETCH_CONTRAST, contrastPanel_.isContrastStretch());
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
// mainPrefs_.putBoolean(MAIN_AUTO_SHUTTER,
// autoShutterCheckBox_.isSelected());
if (afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new CfgFileFilter());
fc.setSelectedFile(new File(sysConfigFile_));
int retVal = fc.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
private void loadSystemState() {
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new CfgFileFilter());
fc.setSelectedFile(new File(sysStateFile_));
int retVal = fc.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
sysStateFile_ = f.getAbsolutePath();
try {
// WaitDialog waitDlg = new
// WaitDialog("Loading saved state, please wait...");
// waitDlg.showDialog();
core_.loadSystemState(sysStateFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
// waitDlg.closeDialog();
initializeGUI();
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
private void saveSystemState() {
JFileChooser fc = new JFileChooser();
boolean saveFile = true;
File f;
do {
fc.setSelectedFile(new File(sysStateFile_));
int retVal = fc.showSaveDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
f = fc.getSelectedFile();
// check if file already exists
if (f.exists()) {
int sel = JOptionPane.showConfirmDialog(this, "Overwrite "
+ f.getName(), "File Save",
JOptionPane.YES_NO_OPTION);
if (sel == JOptionPane.YES_OPTION) {
saveFile = true;
} else {
saveFile = false;
}
}
} else {
return;
}
} while (saveFile == false);
sysStateFile_ = f.getAbsolutePath();
try {
core_.saveSystemState(sysStateFile_);
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
public void closeSequence() {
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return;
}
}
stopAllActivity();
cleanupOnClose();
saveSettings();
configPad_.saveSettings();
options_.saveSettings();
dispose();
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
}
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
contrastPanel_.applyContrastSettings(contrast8, contrast16);
}
public ContrastSettings getContrastSettings() {
return contrastPanel_.getContrastSettings();
}
public boolean is16bit() {
if (isImageWindowOpen()
&& imageWin_.getImagePlus().getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.showError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/*
private void waitForErrorToPass() {
boolean passed = false;
while(!passed) {
try {
JFrame testWin = new JFrame("test");
testWin.setVisible(true);
passed = true;
} catch (ArrayIndexOutOfBoundsException e) {
ReportingUtils.logMessage("testWin failed!!!!");
}
}
}
*/
/**
* Loads sytem configuration from the cfg file.
*/
private void loadSystemConfiguration() {
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
// remember the selected file name
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
core_.loadSystemConfiguration(sysConfigFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
//waitForErrorToPass();
}
} catch (final Exception err) {
// handleException(err);
// handle long error messages
GUIUtils.preventDisplayAdapterChangeExceptions();
ReportingUtils.showError(err);
}
waitDlg.closeDialog();
this.setEnabled(true);
this.initializeGUI();
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
//acqControlWin_.updateGUIContents();
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
/**
* Opens streaming sequence acquisition dialog.
*/
protected void openSequenceDialog() {
try {
if (fastAcqWin_ == null) {
fastAcqWin_ = new FastAcqDlg(core_, this);
}
fastAcqWin_.setVisible(true);
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nSequence window failed to open due to internal error.");
}
}
/**
* Opens Split View dialog.
*/
protected void splitViewDialog() {
try {
if (splitView_ == null) {
splitView_ = new SplitView(core_, this, options_);
}
splitView_.setVisible(true);
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nSplit View Window failed to open due to internal error.");
}
}
* /** Opens a dialog to record stage positions
*/
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, posList_, options_);
posListDlg_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/*
* Changes background color of this window
*/
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((options_.displayBackground)));
paint(MMStudioMainFrame.this.getGraphics());
// configPad_.setDisplayStyle(options_.displayBackground, guiColors_);
if (acqControlWin_ != null) {
acqControlWin_.setBackgroundStyle(options_.displayBackground);
}
if (profileWin_ != null) {
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
if (posListDlg_ != null) {
posListDlg_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
if (imageWin_ != null) {
imageWin_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
if (fastAcqWin_ != null) {
fastAcqWin_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
if (scriptPanel_ != null) {
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
if (splitView_ != null) {
splitView_.setBackground(guiColors_.background.get((options_.displayBackground)));
}
}
public String getBackgroundStyle() {
return options_.displayBackground;
}
// Set ImageJ pixel calibration
private void setIJCal(MMImageWindow imageWin) {
if (imageWin != null) {
imageWin.setIJCal();
}
}
// Scripting interface
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private class LoadAcq implements Runnable {
private String filePath_;
public LoadAcq(String path) {
filePath_ = path;
}
public void run() {
// stop current acquisition if any
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(filePath_);
}
}
}
private class RefreshPositionList implements Runnable {
public RefreshPositionList() {
}
public void run() {
if (posListDlg_ != null) {
posListDlg_.setPositionList(posList_);
engine_.setPositionList(posList_);
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
public void startBurstAcquisition() throws MMScriptException {
testForAbortRequests();
if (fastAcqWin_ != null) {
fastAcqWin_.start();
}
}
public void runBurstAcquisition() throws MMScriptException {
testForAbortRequests();
if (fastAcqWin_ == null) {
fastAcqWin_ = new FastAcqDlg(core_, this);
}
fastAcqWin_.setVisible(true);
fastAcqWin_.start();
try {
while (fastAcqWin_.isBusy()) {
Thread.sleep(20);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
if (fastAcqWin_ == null) {
fastAcqWin_ = new FastAcqDlg(core_, this);
}
fastAcqWin_.setSequenceLength(nr);
fastAcqWin_.setDirRoot(root);
fastAcqWin_.setName(name);
runBurstAcquisition();
}
public void runBurstAcquisition(int nr) throws MMScriptException {
if (fastAcqWin_ == null) {
fastAcqWin_ = new FastAcqDlg(core_, this);
}
fastAcqWin_.setSequenceLength(nr);
runBurstAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
testForAbortRequests();
if (fastAcqWin_ != null) {
return fastAcqWin_.isBusy();
} else {
return false;
}
}
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
public void runAcquisition() throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
public void runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
public void runAcqusition(String name, String root) throws MMScriptException {
runAcquisition(name, root);
}
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new LoadAcq(path));
}
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = PositionList.newInstance(pl);
SwingUtilities.invokeLater(new RefreshPositionList());
}
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return PositionList.newInstance(posList_);
}
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices);
}
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices);
}
private void openAcquisitionSnap(String name, String rootDir, boolean show)
throws MMScriptException {
MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this,
show);
acq.setDimensions(0, 1, 1);
try {
// acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm());
acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm()));
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void initializeAcquisition(String name, int width, int height,
int depth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, depth);
acq.initialize();
}
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
public void closeAcquisitionImage5D(String title) throws MMScriptException {
acqMgr_.closeImage5D(title);
}
public void loadBurstAcquisition(String path) {
// TODO Auto-generated method stub
}
public void refreshGUI() {
updateGUI(true);
}
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
public void snapAndAddImage(String name, int frame, int channel, int slice)
throws MMScriptException {
Metadata md = new Metadata();
try {
Object img;
if (core_.isSequenceRunning()) {
img = core_.getLastImage();
core_.getLastImageMD(0, 0, md);
} else {
core_.snapImage();
long channels = core_.getNumberOfComponents();
if (channels == 1) {
img = core_.getImage();
} else {
img = core_.getRGB32Image();
}
}
MMAcquisition acq = acqMgr_.getAcquisition(name);
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
if (!acq.isInitialized()) {
acq.setImagePhysicalDimensions((int) width, (int) height,
(int) depth);
acq.initialize();
}
acq.insertImage(img, frame, channel, slice);
// Insert exposure in metadata
acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
acq.setSystemState(frame, channel, slice, state);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void addToSnapSeries(Object img, String acqName) {
try {
// boolean liveRunning = liveRunning_;
// if (liveRunning)
// enableLiveMode(false);
if (acqName == null) {
acqName = "Snap" + snapCount_;
}
Boolean newSnap = false;
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
MMAcquisitionSnap acq = null;
if (acqMgr_.hasActiveImage5D(acqName)) {
acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName);
newSnap = !acq.isCompatibleWithCameraSettings();
} else {
newSnap = true;
}
if (newSnap) {
snapCount_++;
acqName = "Snap" + snapCount_;
this.openAcquisitionSnap(acqName, null, true); // (dir=null) ->
// keep in
// memory; don't
// save to file.
initializeAcquisition(acqName, (int) width, (int) height,
(int) depth);
}
setChannelColor(acqName, 0, Color.WHITE);
setChannelName(acqName, 0, "Snap");
acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName);
acq.appendImage(img);
// add exposure to metadata
acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state);
// if (liveRunning)
// enableLiveMode(true);
// closeAcquisition(acqName);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
public void run() {
scriptPanel_.message(msg_);
}
}
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
public boolean runWellScan(WellAcquisitionData wad) throws MMScriptException {
System.out.println("Inside MMStudioMainFrame -- Run Well Scan");
boolean result = true;
testForAbortRequests();
if (acqControlWin_ == null) {
openAcqControlDialog();
}
engine_.setPositionList(posList_);
result = acqControlWin_.runWellScan(wad);
if (result == false) {
return result;
//throw new MMScriptException("Scanning error.");
}
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(500);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
result = false;
return result;
}
return result;
}
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public String getXYStageName() {
return core_.getXYStageDevice();
}
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionEngine getAcquisitionEngine() {
return engine_;
}
public String installPlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = new String(className + " module loaded.");
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
return className + " already loaded.";
}
}
PluginItem pi = new PluginItem();
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logError(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
//core_.logMessage(className + " fails to implement static String menuName.");
}
pi.pluginClass = cl;
plugins_.add(pi);
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
return msg;
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
public String installPlugin(String className) {
String msg = "";
try {
return installPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = new String(autofocus.getSimpleName() + " module loaded.");
if (afMgr_ != null) {
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
public void snapAndAddToImage5D(String acqName) {
Object img;
try {
boolean liveRunning = liveRunning_;
if (liveRunning) {
img = core_.getLastImage();
} else {
core_.snapImage();
img = core_.getImage();
}
addToSnapSeries(img, acqName);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
//Returns true if there is a newer image to display that can be get from MMCore
//Implements "optimistic" approach: returns true even
//if there was an error while getting the image time stamp
private boolean isNewImageAvailable() {
boolean ret = true;
/* disabled until metadata-related methods in MMCoreJ can handle exceptions
Metadata md = new Metadata();
MetadataSingleTag tag = null;
try
{
core_.getLastImageMD(0, 0, md);
String strTag=MMCoreJ.getG_Keyword_Elapsed_Time_ms();
tag = md.GetSingleTag(strTag);
if(tag != null)
{
double newFrameTimeStamp = Double.valueOf(tag.GetValue());
ret = newFrameTimeStamp > lastImageTimeMs_;
if (ret)
{
lastImageTimeMs_ = newFrameTimeStamp;
}
}
}
catch(Exception e)
{
ReportingUtils.logError(e);
}
*/
return ret;
}
;
public void suspendLiveMode() {
liveModeSuspended_ = IsLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
private void loadPlugins() {
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
for (Class<?> plugin : pluginClasses) {
try {
installPlugin(plugin);
} catch (Exception e) {
ReportingUtils.logError(e, "Attempted to install the \"" + plugin.getName() + "\" plugin .");
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Attempted to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
private void setLiveModeInterval() {
double interval = 33.0;
try {
if (core_.getExposure() > 33.0) {
interval = core_.getExposure();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
liveModeInterval_ = interval;
liveModeTimer_.setDelay((int) liveModeInterval_);
liveModeTimer_.setInitialDelay(liveModeTimer_.getDelay());
}
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
public void logError(Exception e) {
ReportingUtils.logError(e);
}
public void logError(String msg) {
ReportingUtils.logError(msg);
}
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
public void showError(Exception e) {
ReportingUtils.showError(e);
}
public void showError(String msg) {
ReportingUtils.showError(msg);
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
} |
/**
* DataProcessor thread allows for on-the-fly modification of image
* data during acquisition.
*
* Inherit from this class and use the AcquisitionEngine functions
* addImageProcessor and removeImageProcessor to insert your code into the
* acquisition pipeline
*
*/
package org.micromanager.api;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.micromanager.utils.ReportingUtils;
/**
*
* @author arthur
*/
public abstract class DataProcessor<E> extends Thread {
private BlockingQueue<E> input_;
private BlockingQueue<E> output_;
private boolean stopRequested_ = false;
private boolean started_ = false;
/*
* The process method should be overridden by classes implementing
* DataProcessor, to provide a processing function.
*
* For example, an "Identity" DataProcessor (where nothing is
* done to the data) would override process() thus:
*
* @Override
* public void process() {
* produce(poll());
* }
*/
protected abstract void process();
/*
* The run method that causes images to be processed. As DataProcessor
* extends java's Thread class, this method will be executed whenever
* DataProcessor.start() is called.
*/
@Override
public void run() {
setStarted(true);
while (!stopRequested_) {
process();
}
}
/*
* Request that the data processor stop processing. The current
* processing event will continue, but no others will be started.
*/
public synchronized void requestStop() {
stopRequested_ = true;
}
/*
* Private method for tracking when processing has started.
*/
private synchronized void setStarted(boolean started) {
started_ = started;
}
/*
* Returns true if the DataProcessor has started up and objects
* are being processed as they arrive.
*/
public synchronized boolean isStarted() {
return started_;
}
/*
* The constructor.
*/
public DataProcessor() {}
/*
* Sets the input queue where objects to be processed
* are received by the DataProcessor.
*/
public void setInput(BlockingQueue<E> input) {
input_ = input;
}
/*
* Sets the output queue where objects that have been processed
* exit the DataProcessor.
*/
public void setOutput(BlockingQueue<E> output) {
output_ = output;
}
/*
* A protected method that reads the next object from the input
* queue.
*/
protected E poll() {
while (!stopRequested()) {
try {
E datum = (E) input_.poll(100, TimeUnit.MILLISECONDS);
if (datum != null) {
return datum;
}
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
}
return null;
}
/*
* A convenience method for draining all available data objects
* on the input queue to a collection.
*/
protected void drainTo(Collection<E> data) {
input_.drainTo(data);
}
/*
* A convenience method for posting a data object to the output queue.
*/
protected void produce(E datum) {
try {
output_.put(datum);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
};
/*
* Returns true if stop has been requested.
*/
protected synchronized boolean stopRequested() {
return stopRequested_;
}
} |
//FILE: SliderPanel.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id: ConfigGroupPad.java 747 2008-01-04 01:08:50Z nenad $
package org.micromanager.utils;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.text.ParseException;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderPanel extends JPanel {
private static final long serialVersionUID = -6039226355990936685L;
private SpringLayout springLayout_;
private JTextField textField_;
private double lowerLimit_ = 0.0;
private double upperLimit_ = 10.0;
private final int STEPS = 1000;
private double factor_ = 1.0;
private boolean integer_ = false;
private ChangeListener sliderChangeListener_;
private JScrollBar slider_;
/**
* Create the panel
*/
public SliderPanel() {
super();
springLayout_ = new SpringLayout();
setLayout(springLayout_);
setPreferredSize(new Dimension(304, 18));
textField_ = new JTextField();
textField_.setFont(new Font("", Font.PLAIN, 10));
textField_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent arg0) {
onEditChange();
}
});
add(textField_);
springLayout_.putConstraint(SpringLayout.EAST, textField_, 40, SpringLayout.WEST, this);
springLayout_.putConstraint(SpringLayout.WEST, textField_, 0, SpringLayout.WEST, this);
springLayout_.putConstraint(SpringLayout.SOUTH, textField_, 0, SpringLayout.SOUTH, this);
springLayout_.putConstraint(SpringLayout.NORTH, textField_, 0, SpringLayout.NORTH, this);
sliderChangeListener_ = new ChangeListener() {
public void stateChanged(final ChangeEvent arg0) {
onSliderMove();
}
};
slider_ = new JScrollBar(JScrollBar.HORIZONTAL);
slider_.getModel().addChangeListener(sliderChangeListener_);
add(slider_);
springLayout_.putConstraint(SpringLayout.EAST, slider_, 0, SpringLayout.EAST, this);
springLayout_.putConstraint(SpringLayout.WEST, slider_, 41, SpringLayout.WEST, this);
springLayout_.putConstraint(SpringLayout.SOUTH, slider_, 0, SpringLayout.SOUTH, this);
springLayout_.putConstraint(SpringLayout.NORTH, slider_, 0, SpringLayout.NORTH, this);
}
public String getText() {
// implicitly enforce limits
setText(textField_.getText());
return textField_.getText();
}
public void enableEdit(boolean state) {
textField_.setEditable(state);
}
public void setLimits(double lowerLimit, double upperLimit) {
integer_ = false;
factor_ = (upperLimit - lowerLimit) / (STEPS);
upperLimit_ = upperLimit;
lowerLimit_ = lowerLimit;
slider_.setMinimum(0);
slider_.setMaximum(STEPS);
slider_.setVisibleAmount(0);
}
public void setLimits(int lowerLimit, int upperLimit) {
integer_ = true;
factor_ = 1.0;
upperLimit_ = upperLimit;
lowerLimit_ = lowerLimit;
slider_.setMinimum(0);
slider_.setMaximum(upperLimit - lowerLimit + 1);
slider_.setVisibleAmount(1);
}
private void setSliderValue(double val) {
slider_.setValue((int) ((val - lowerLimit_)/factor_) );
}
private void onSliderMove() {
double value = 0.0;
value = slider_.getValue() * factor_ + lowerLimit_;
if (integer_) {
textField_.setText(NumberUtils.intToDisplayString((int)(value)));
} else {
textField_.setText(NumberUtils.doubleToDisplayString(value));
}
}
protected void onEditChange() {
double val;
try {
val = enforceLimits(NumberUtils.displayStringToDouble(textField_.getText()));
slider_.getModel().removeChangeListener(sliderChangeListener_);
setSliderValue(val);
slider_.getModel().addChangeListener(sliderChangeListener_);
} catch (ParseException p) {
handleException (p);
}
}
public void setText(String txt) {
double val;
try {
if (integer_) {
val = enforceLimits(NumberUtils.displayStringToInt(txt));
textField_.setText(NumberUtils.intToDisplayString((int) val));
} else {
val = enforceLimits(NumberUtils.displayStringToDouble(txt));
textField_.setText(NumberUtils.doubleToDisplayString(val));
}
slider_.getModel().removeChangeListener(sliderChangeListener_);
setSliderValue(val);
slider_.getModel().addChangeListener(sliderChangeListener_);
} catch (ParseException p) {
handleException (p);
}
}
private double enforceLimits(double value) {
double val = value;
if (val < lowerLimit_)
val = lowerLimit_;
if (val > upperLimit_)
val = upperLimit_;
return val;
}
private int enforceLimits(int value) {
int val = value;
if (val < lowerLimit_)
val = (int)(lowerLimit_);
if (val > upperLimit_)
val = (int)(upperLimit_);
return val;
}
public void addEditActionListener(ActionListener al) {
textField_.addActionListener(al);
}
public void addSliderMouseListener(MouseAdapter md) {
slider_.addMouseListener(md);
}
@Override
public void setBackground(Color bg) {
super.setBackground(bg);
if (slider_ != null)
slider_.setBackground(bg);
if (textField_ != null)
textField_.setBackground(bg);
}
@Override
public void setEnabled(boolean enabled) {
textField_.setEnabled(enabled);
slider_.setEnabled(enabled);
}
private void handleException (Exception e) {
ReportingUtils.showError(e);
}
} |
package controller;
import model.FixFile;
import model.Operations;
import model.Record;
import java.io.File;
import java.util.ArrayList;
import static controller.Controller.setUIFlavour;
public class Main {
public static ArrayList<Record> dataRecords = new ArrayList<>();
public static final ArrayList<Record> attendeesRecords = new ArrayList<>();
public static final String CREATED_CSV = "created.csv";
public static final String ATTENDEES_CSV = "attendees.csv";
private static final String SOURCE_CSV = "source.csv";
public static void main(String[] args) {
if (new File(CREATED_CSV).isFile()) Operations.setFileName(CREATED_CSV);
else if (new File(SOURCE_CSV).isFile())
new FixFile(SOURCE_CSV, CREATED_CSV);
Operations.setFileName(CREATED_CSV);
setUIFlavour();
new Controller();
Operations.countUnique();
}
} |
package controller;
import java.util.Iterator;
import java.util.LinkedList;
import org.junit.Assert;
import org.junit.Test;
import config.Config;
import config.Options;
public class Main {
public static void main(String[] args) {
Main main = new Main();
Options option = new Options().build(args);
Config cfg = new Config(option);
if (option.isAsync() && option.isAllScenario()) {
main.runAsyncAll(cfg, option);
} else if (option.isAsync()) {
main.runAsync(cfg, option);
} else {
main.runSync(cfg, option);
}
main = null;
option = null;
cfg = null;
}
public void runSync(Config cfg, Options option) {
String[] scenarios = option.getScenarioArray();
for (String s : scenarios) {
String s_name = get_scenario_name(s);
int s_count = get_loop_count(s);
for (int i = 0; i < s_count; i++) {
new Ruberdriver(cfg, s_name).run();
}
}
}
public void runAsyncAll(Config cfg, Options option) {
LinkedList<Thread> threads = new LinkedList<>();
Iterator<String> it = cfg.getScenarios().keySet().iterator();
while (it.hasNext()) {
String scenario = (String) it.next();
Thread rd = new Ruberdriver(cfg, scenario);
threads.add(rd);
rd.start();
}
Iterator<Thread> tit = threads.iterator();
try {
while (tit.hasNext()) {
Thread thread = (Thread) tit.next();
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
public void runAsync(Config cfg, Options option) {
LinkedList<Thread> threads = new LinkedList<>();
String[] scenarios = option.getScenarioArray();
for (String s : scenarios) {
String s_name = get_scenario_name(s);
int s_count = get_loop_count(s);
for (int i = 0; i < s_count; i++) {
Thread rd = new Ruberdriver(cfg, s_name);
threads.add(rd);
rd.start();
}
}
Iterator<Thread> it = threads.iterator();
try {
while (it.hasNext()) {
Thread thread = (Thread) it.next();
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
private int get_loop_count(String scenario) {
String str = scenario.trim();
if (str.matches("^.+\\:\\s*\\d+\\s*$")) {
int colon_loc = 1 + str.lastIndexOf(":");
return Integer.parseInt(str.substring(colon_loc).trim());
}
return 1;
}
private String get_scenario_name(String scenario) {
String str = scenario.trim();
if (str.matches("^.+\\:\\s*(\\d+\\s*)?$")) {
int colon_loc = str.lastIndexOf(":");
return str.substring(0, colon_loc).trim();
}
return str;
}
@Test
public void test_get_loop_count() {
Assert.assertEquals(1, get_loop_count("test"));
Assert.assertEquals(2, get_loop_count("test:2"));
Assert.assertEquals(1, get_loop_count("test:"));
Assert.assertEquals(1, get_loop_count("t:est:"));
Assert.assertEquals(23, get_loop_count(" test: 23 "));
}
@Test
public void test_get_scenario_name() {
Assert.assertTrue("test".equals(get_scenario_name("test")));
Assert.assertTrue("test".equals(get_scenario_name("test:2")));
Assert.assertTrue("test".equals(get_scenario_name("test:")));
Assert.assertTrue("t:est".equals(get_scenario_name("t:est:")));
Assert.assertTrue("test".equals(get_scenario_name(" test: 23 ")));
}
@Test
public void mainTest() {
String[] args = {
"--source", "test.json",
//"--scenario", "purchase_test,login_test", "-a" //
// "--scenario", "purchase_test", "-a", "-l" //
// "-c", "purchase_test", "-d" //
// "-c", "purchase_test" //
"-c", "login_test:2,purchase_test:2"
};
Main.main(args);
}
} |
package core;
import java.util.Arrays;
import java.util.EnumSet;
import core.Position.File;
import core.Position.Rank;
import engine.MoveGeneration;
public class ChessBoard {
public static final int BOTH_COLOR = 2;
private final int[] board; // indexed by position
private final int[] materialScore; // indexed by color;
private final Bitboard[][] pieces; // Indexed by color and type
private final Bitboard[] occupancy; // Indexed by color plus one for both
private final State[] savedStates;
private int stateIndex;
private int castlingPermissions;
private int enPassantPosition;
private int activeColor;
private int halfMoveClock;
private class State {
public final int castlingPermissions;
public final int enPassantPosition;
public final int halfMoveClock;
public State(int castling, int enPassant, int clock) {
this.castlingPermissions = castling;
this.enPassantPosition = enPassant;
this.halfMoveClock = clock;
}
}
public ChessBoard() {
this.board = new int[Position.NUM_TOTAL_VALUES];
Arrays.fill(this.board, ChessPiece.NULL_PIECE);
this.materialScore = new int[ChessColor.values().length];
this.pieces = new Bitboard[ChessColor.values().length][PieceType.values().length];
for (ChessColor color : ChessColor.values()) {
for (PieceType type : PieceType.values()) {
pieces[color.value()][type.value()] = new Bitboard();
}
}
this.occupancy = new Bitboard[ChessColor.values().length + 1];
for (int i = 0; i < occupancy.length; i++) {
occupancy[i] = new Bitboard();
}
// TODO Implement a standard for this and a class with this as a
// constant
this.savedStates = new State[1024];
this.stateIndex = 0;
this.castlingPermissions = CastlingBitFlags.NO_CASTLING;
this.enPassantPosition = Position.NULL_POSITION;
this.activeColor = ChessColor.WHITE.value();
this.halfMoveClock = 0;
}
public int getCastling() {
return castlingPermissions;
}
public int getEnPassantPosition() {
return enPassantPosition;
}
public int getActiveColor() {
return activeColor;
}
public int getHalfTurnClock() {
return halfMoveClock;
}
public int getScore(int color) {
assert ChessColor.isValid(color);
return materialScore[color];
}
public ChessPiece getObject(int position) {
assert Position.isValid(position);
int piece = board[position];
return (piece != ChessPiece.NULL_PIECE) ? ChessPiece.from(piece) : null;
}
public int get(int position) {
assert Position.isValid(position);
return board[position];
}
public Bitboard getPieces(int color, int type) {
assert ChessColor.isValid(color);
assert PieceType.isValid(type);
return pieces[color][type].clone();
}
public Bitboard getOccupany(int color) {
assert ChessColor.isValid(color) || color == BOTH_COLOR;
return occupancy[color].clone();
}
private void set(int position, int piece) {
assert Position.isValid(position);
assert ChessPiece.isValid(piece);
assert isEmpty(position);
materialScore[ChessPiece.getColor(piece)] -= ChessPiece.getScore(piece);
pieces[ChessPiece.getColor(piece)][ChessPiece.getPieceType(piece)].set(position);
occupancy[ChessPiece.getColor(piece)].set(position);
occupancy[BOTH_COLOR].set(position);
board[position] = piece;
}
private int clear(int position) {
assert Position.isValid(position);
assert !isEmpty(position);
int oldPiece = board[position];
materialScore[ChessPiece.getColor(oldPiece)] -= ChessPiece.getScore(oldPiece);
pieces[ChessPiece.getColor(oldPiece)][ChessPiece.getPieceType(oldPiece)].clear(position);
occupancy[ChessPiece.getColor(oldPiece)].clear(position);
occupancy[BOTH_COLOR].clear(position);
board[position] = ChessPiece.NULL_PIECE;
return oldPiece;
}
public boolean isEmpty(int position) {
assert Position.isValid(position);
return board[position] == ChessPiece.NULL_PIECE;
}
public boolean isEmptyMask(Bitboard board) {
return isEmptyOfColorMask(board, BOTH_COLOR);
}
public boolean isEmptyOfColorMask(Bitboard board, int psuedoColor) {
return Bitboard.and(board, occupancy[psuedoColor]).size() == 0;
}
public boolean isCheck() {
return isCheck(activeColor);
}
public boolean isCheck(int color) {
return isAttacked(pieces[color][PieceType.KING.value()].getSingle(),
ChessColor.opposite(color));
}
public int staticExchangeEvaluation(int move) {
return 1; // TODO (wait until chess engine started) implement static
// exchange evaluation
}
// fast return, returns as soon as it finds an attacker
public boolean isAttacked(int position, int attackerColor) {
int attackingPawn = ChessPiece.fromRaw(attackerColor, PieceType.PAWN.value());
int attackingKnight = ChessPiece.fromRaw(attackerColor, PieceType.KNIGHT.value());
int attackingKing = ChessPiece.fromRaw(attackerColor, PieceType.KING.value());
int attackingBishop = ChessPiece.fromRaw(attackerColor, PieceType.BISHOP.value());
int attackingRook = ChessPiece.fromRaw(attackerColor, PieceType.ROOK.value());
int attackingQueen = ChessPiece.fromRaw(attackerColor, PieceType.QUEEN.value());
for (int i = 1; i < MoveGeneration.pawnOffsets[attackerColor].length; i++) {
int pawnPos = position - MoveGeneration.pawnOffsets[attackerColor][i];
if (Position.isValid(pawnPos) && this.get(pawnPos) == attackingPawn) {
return true;
}
}
for (int i = 0; i < MoveGeneration.knightOffsets.length; i++) {
int knightPos = position - MoveGeneration.knightOffsets[i];
if (Position.isValid(knightPos) && this.get(knightPos) == attackingKnight) {
return true;
}
}
for (int i = 0; i < MoveGeneration.rookDirections.length; i++) {
int rookPos = position - MoveGeneration.rookDirections[i];
while (Position.isValid(rookPos)) {
if (this.get(rookPos) != ChessPiece.NULL_PIECE) {
if (this.get(rookPos) == attackingRook
|| this.get(position) == attackingQueen) {
return true;
} else if (ChessPiece.getColor(this.get(rookPos)) == ChessColor
.opposite(attackerColor)) {
break;
}
}
rookPos -= MoveGeneration.rookDirections[i];
}
}
for (int i = 0; i < MoveGeneration.bishopDirections.length; i++) {
int bishopPos = position - MoveGeneration.bishopDirections[i];
while (Position.isValid(bishopPos)) {
if (this.get(bishopPos) != ChessPiece.NULL_PIECE) {
if (this.get(bishopPos) == attackingBishop
|| this.get(position) == attackingQueen) {
return true;
} else if (ChessPiece.getColor(this.get(bishopPos)) == ChessColor
.opposite(attackerColor)) {
break;
}
}
bishopPos -= MoveGeneration.bishopDirections[i];
}
}
for (int i = 0; i < MoveGeneration.kingOffsets.length; i++) {
int kingPos = position - MoveGeneration.kingOffsets[i];
if (Position.isValid(kingPos) && this.get(kingPos) == attackingKing) {
return true;
}
}
return false;
}
public void move(int move) {
assert Move.isValid(move);
int startPos = Move.getStartPosition(move);
int endPos = Move.getEndPosition(move);
int startPiece = Move.getStartPiece(move);
int endPiece = Move.getEndPiece(move);
int flags = Move.getFlags(move);
int promotionType = Move.getPromotionPieceType(move);
move(startPos, endPos, startPiece, ChessPiece.getColor(startPiece), endPiece, flags,
promotionType);
}
public void move(Move move) {
int startPos = move.getStartPosition();
int endPos = move.getEndPosition();
int startPiece = move.getStartPiece();
int endPiece = move.getEndPiece();
int flags = move.getFlags();
int promotionType = move.getPromotionPieceType();
move(startPos, endPos, startPiece, ChessPiece.getColor(startPiece), endPiece, flags,
promotionType);
}
private void move(int startPos, int endPos, int startPiece, int startColor, int endPiece,
int flags, int promotionType) {
savedStates[stateIndex++] =
new State(this.castlingPermissions, this.enPassantPosition, this.halfMoveClock);
// Check for capture, and remove from the board
// Covers en passant captures
if (endPiece != ChessPiece.NULL_PIECE) {
int effectiveCapturePos = endPos;
if (flags == Move.Flags.EN_PASSANT.value()) {
effectiveCapturePos +=
(startColor == ChessColor.WHITE.value() ? Position.S : Position.N);
}
clear(effectiveCapturePos);
updateCastlingPerm(effectiveCapturePos);
}
// Move start piece to new position
// Covers promotion and
// Quiet moves
clear(startPos);
if (flags == Move.Flags.PROMOTION.value()) {
set(endPos, ChessPiece.fromRaw(startColor, promotionType));
} else {
set(endPos, startPiece);
}
// implements castling moves
if (flags == Move.Flags.CASTLE.value()) {
int castlingRookStart = Position.NULL_POSITION;
int castlingRookEnd = Position.NULL_POSITION;
if (endPos == Position.from(File.F_G, Rank.R_1)) {
castlingRookStart = Position.from(File.F_H, Rank.R_1);
castlingRookEnd = Position.from(File.F_F, Rank.R_1);
} else if (endPos == Position.from(File.F_C, Rank.R_1)) {
castlingRookStart = Position.from(File.F_A, Rank.R_1);
castlingRookEnd = Position.from(File.F_D, Rank.R_1);
} else if (endPos == Position.from(File.F_G, Rank.R_8)) {
castlingRookStart = Position.from(File.F_H, Rank.R_8);
castlingRookEnd = Position.from(File.F_F, Rank.R_8);
} else if (endPos == Position.from(File.F_G, Rank.R_8)) {
castlingRookStart = Position.from(File.F_A, Rank.R_8);
castlingRookEnd = Position.from(File.F_D, Rank.R_8);
} else {
assert false;
}
set(castlingRookEnd, clear(castlingRookStart));
}
updateCastlingPerm(startPos);
// check for pawn double and update passant
if (flags == Move.Flags.DOUBLE_PAWN_PUSH.value()) {
this.enPassantPosition =
endPos + (startColor == ChessColor.WHITE.value() ? Position.S : Position.N);
} else {
this.enPassantPosition = Position.NULL_POSITION;
}
// flip color and update half move clock
this.activeColor = ChessColor.opposite(activeColor);
if (endPiece != ChessPiece.NULL_PIECE
|| ChessPiece.getPieceType(startPiece) == PieceType.PAWN.value()) {
this.halfMoveClock = 0;
} else {
this.halfMoveClock++;
}
}
public void unmove(int move) {
assert Move.isValid(move);
int startPos = Move.getStartPosition(move);
int endPos = Move.getEndPosition(move);
int startPiece = Move.getStartPiece(move);
int endPiece = Move.getEndPiece(move);
int moveType = Move.getFlags(move);
int promotionPieceType = Move.getPromotionPieceType(move);
unmove(startPos, endPos, startPiece, ChessPiece.getColor(startPiece), endPiece, moveType,
promotionPieceType);
}
public void unmove(Move move) {
int startPos = move.getStartPosition();
int endPos = move.getEndPosition();
int startPiece = move.getStartPiece();
int endPiece = move.getEndPiece();
int moveType = move.getFlags();
int promotionPieceType = move.getPromotionPieceType();
unmove(startPos, endPos, startPiece, ChessPiece.getColor(startPiece), endPiece, moveType,
promotionPieceType);
}
private void unmove(int startPos, int endPos, int startPiece, int startColor, int endPiece,
int moveType, int promotionType) {
this.activeColor = ChessColor.opposite(activeColor);
if (moveType == Move.Flags.CASTLE.value()) {
int castlingRookStart = Position.NULL_POSITION;
int castlingRookEnd = Position.NULL_POSITION;
if (endPos == Position.from(File.F_G, Rank.R_1)) {
castlingRookStart = Position.from(File.F_H, Rank.R_1);
castlingRookEnd = Position.from(File.F_F, Rank.R_1);
} else if (endPos == Position.from(File.F_C, Rank.R_1)) {
castlingRookStart = Position.from(File.F_A, Rank.R_1);
castlingRookEnd = Position.from(File.F_D, Rank.R_1);
} else if (endPos == Position.from(File.F_G, Rank.R_8)) {
castlingRookStart = Position.from(File.F_H, Rank.R_8);
castlingRookEnd = Position.from(File.F_F, Rank.R_8);
} else if (endPos == Position.from(File.F_G, Rank.R_8)) {
castlingRookStart = Position.from(File.F_A, Rank.R_8);
castlingRookEnd = Position.from(File.F_D, Rank.R_8);
} else {
assert false;
}
set(castlingRookStart, clear(castlingRookEnd));
}
clear(endPos);
set(startPos, startPiece);
if (endPiece != ChessPiece.NULL_PIECE) {
int effectiveCapturePos = endPos;
if (moveType == Move.Flags.EN_PASSANT.value()) {
effectiveCapturePos +=
(startColor == ChessColor.WHITE.value() ? Position.S : Position.N);
}
set(effectiveCapturePos, endPiece);
}
State saved = savedStates[--stateIndex];
this.castlingPermissions = saved.castlingPermissions;
this.enPassantPosition = saved.enPassantPosition;
this.halfMoveClock = saved.halfMoveClock;
}
private void updateCastlingPerm(int position) {
int updatedPermissions = this.castlingPermissions;
if (position == Position.from(File.F_A, Rank.R_1)) {
updatedPermissions &= ~CastlingBitFlags.WHITE_QUEENSIDE.value();
} else if (position == Position.from(File.F_A, Rank.R_8)) {
updatedPermissions &= ~CastlingBitFlags.BLACK_QUEENSIDE.value();
} else if (position == Position.from(File.F_H, Rank.R_1)) {
updatedPermissions &= ~CastlingBitFlags.WHITE_KINGSIDE.value();
} else if (position == Position.from(File.F_H, Rank.R_8)) {
updatedPermissions &= ~CastlingBitFlags.BLACK_KINGSIDE.value();
} else if (position == Position.from(File.F_E, Rank.R_1)) {
updatedPermissions &= ~(CastlingBitFlags.WHITE_QUEENSIDE.value()
| CastlingBitFlags.WHITE_KINGSIDE.value());
} else if (position == Position.from(File.F_E, Rank.R_8)) {
updatedPermissions &= ~(CastlingBitFlags.BLACK_QUEENSIDE.value()
| CastlingBitFlags.BLACK_KINGSIDE.value());
} else {
return;
}
this.castlingPermissions = updatedPermissions;
}
public static class ChessBoardFactory {
public static ChessBoard startingBoard() {
ChessBoard board = new ChessBoard();
board.castlingPermissions =
CastlingBitFlags.value(EnumSet.allOf(CastlingBitFlags.class));
for (File f : Position.File.values()) {
board.set(Position.from(f, Rank.R_2), ChessPiece.WHITE_PAWN.value());
board.set(Position.from(f, Rank.R_7), ChessPiece.BLACK_PAWN.value());
}
board.set(Position.from(File.F_A, Rank.R_1), ChessPiece.WHITE_ROOK.value());
board.set(Position.from(File.F_H, Rank.R_1), ChessPiece.WHITE_ROOK.value());
board.set(Position.from(File.F_A, Rank.R_8), ChessPiece.BLACK_ROOK.value());
board.set(Position.from(File.F_H, Rank.R_8), ChessPiece.BLACK_ROOK.value());
board.set(Position.from(File.F_B, Rank.R_1), ChessPiece.WHITE_KNIGHT.value());
board.set(Position.from(File.F_G, Rank.R_1), ChessPiece.WHITE_KNIGHT.value());
board.set(Position.from(File.F_B, Rank.R_8), ChessPiece.BLACK_KNIGHT.value());
board.set(Position.from(File.F_G, Rank.R_8), ChessPiece.BLACK_KNIGHT.value());
board.set(Position.from(File.F_C, Rank.R_1), ChessPiece.WHITE_BISHOP.value());
board.set(Position.from(File.F_F, Rank.R_1), ChessPiece.WHITE_BISHOP.value());
board.set(Position.from(File.F_C, Rank.R_8), ChessPiece.BLACK_BISHOP.value());
board.set(Position.from(File.F_F, Rank.R_8), ChessPiece.BLACK_BISHOP.value());
board.set(Position.from(File.F_D, Rank.R_1), ChessPiece.WHITE_QUEEN.value());
board.set(Position.from(File.F_D, Rank.R_8), ChessPiece.BLACK_QUEEN.value());
board.set(Position.from(File.F_E, Rank.R_1), ChessPiece.WHITE_KING.value());
board.set(Position.from(File.F_E, Rank.R_8), ChessPiece.BLACK_KING.value());
return board;
}
// TODO (Optional) Implement chessboard from fen string
public static ChessBoard fromFEN(String fen) {
throw new UnsupportedOperationException();
}
}
} |
package creatures;
import java.io.File;
import java.io.IOException;
import javax.media.opengl.GL2;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.glu.GLUquadric;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;
import game.Building;
import game.PlayerMotionWatcher;
import game.PlayerStats;
public class Mummy implements Creature, PlayerMotionWatcher, ProjectileWatcher{
float locx, locy, locz;
float eyeAngle = 0;
final float moveSpeed = 1f;
final float runSpeed = 2f;
final float rotateSpeed = 2f;
final float sightRadius = 20;
private Texture bodyTexture;
private GLUquadric bodyQuadric;
boolean facingFront = true;
boolean agro, dead;
static float T = 0;
public Mummy(float x, float z, GL2 gl, GLU glu){
locx = x;
locy = 0;
locz = z;
bodyTexture = Building.setupTexture(gl, "liangmummy.jpg");
bodyQuadric = glu.gluNewQuadric();
glu.gluQuadricDrawStyle(bodyQuadric, GLU.GLU_FILL); // GLU_POINT, GLU_LINE, GLU_FILL, GLU_SILHOUETTE
glu.gluQuadricNormals (bodyQuadric, GLU.GLU_NONE); // GLU_NONE, GLU_FLAT, or GLU_SMOOTH
glu.gluQuadricTexture (bodyQuadric, true); // false, or true to generate texture coordinates
agro = false;
dead = false;
}
private void drawMoving(GL2 gl, GLU glu, float T){
if (agro){drawAgro(gl,glu,T);}
else
drawPassive(gl, glu, T);
}
private void drawAgro(GL2 gl, GLU glu, float T) {
T *= 2;
gl.glEnable(GL2.GL_TEXTURE_2D);
bodyTexture.bind(gl);
drawHead(gl, glu);
drawLeg(gl, glu, T);
gl.glPushMatrix();
gl.glTranslatef(0f,4.75f,4.5f);
gl.glRotatef(90, -1, 0, 0);
drawArm(gl, glu, T+.5f);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
drawBody(gl,glu);
drawEye(gl,glu);
gl.glPushMatrix();
gl.glScalef(-1,1,1);
gl.glEnable(GL2.GL_TEXTURE_2D);
bodyTexture.bind(gl);
drawLeg(gl, glu, T+.5f);
gl.glPushMatrix();
gl.glTranslatef(0f,4.75f,4.5f);
gl.glRotatef(90, -1, 0, 0);
drawArm(gl, glu, T);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
drawEye(gl, glu);
gl.glPopMatrix();
}
private void drawPassive(GL2 gl, GLU glu, float T) {
//Head
gl.glEnable(GL2.GL_TEXTURE_2D);
bodyTexture.bind(gl);
drawHead(gl, glu);
drawLeg(gl, glu, T);
drawArm(gl, glu, T+.5f);
gl.glDisable(GL2.GL_TEXTURE_2D);
drawBody(gl, glu);
drawEye(gl,glu);
gl.glPushMatrix();
gl.glScalef(-1,1,1);
gl.glEnable(GL2.GL_TEXTURE_2D);
bodyTexture.bind(gl);
drawLeg(gl, glu, T+.5f);
drawArm(gl, glu, T);
gl.glDisable(GL2.GL_TEXTURE_2D);
drawEye(gl, glu);
gl.glPopMatrix();
}
private void drawHead(GL2 gl, GLU glu){
gl.glColor3f(.8007f, .7539f, .7695f);
gl.glPushMatrix();
gl.glTranslatef(0f,6.5f,0f);
//gl.glRotated(90,1f,0f,0f);
glu.gluSphere(bodyQuadric, 1.5f, 20, 10);
gl.glPopMatrix();
}
private void drawBody(GL2 gl, GLU glu){
gl.glColor3f(.8007f, .7539f, .7695f);
gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glEnable(GL2.GL_TEXTURE_GEN_S);
gl.glEnable(GL2.GL_TEXTURE_GEN_T);
gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR);
gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR);
float[] coef_s = {.2f,0f,.5f,0};
gl.glTexGenfv(GL2.GL_S, GL2.GL_OBJECT_PLANE, coef_s, 0);
float[] coef_t = {0f,1f,0f,0};
gl.glTexGenfv(GL2.GL_T, GL2.GL_OBJECT_PLANE, coef_t, 0);
bodyTexture.bind(gl);
gl.glPushMatrix();
gl.glTranslatef(0f,.6f,-2.5f);
gl.glRotatef(25f, 1f, 0f, 0f);
gl.glBegin(GL2.GL_QUADS);
gl.glVertex3f(1.75f, 3, 0.5f);
gl.glVertex3f(1.75f, 3, -0.5f);
gl.glVertex3f(2.f, 5, -0.75f);
gl.glVertex3f(2.f, 5, 0.75f);
gl.glVertex3f(-1.75f, 3, 0.5f);
gl.glVertex3f(-1.75f, 3, -0.5f);
gl.glVertex3f(-2.f, 5, -0.75f);
gl.glVertex3f(-2.f, 5, 0.75f);
gl.glVertex3f(-1.75f, 3, 0.5f);
gl.glVertex3f(-2f, 5, 0.75f);
gl.glVertex3f(2f, 5, 0.75f);
gl.glVertex3f(1.75f, 3, 0.5f);
gl.glVertex3f(-1.75f, 3, -0.5f);
gl.glVertex3f(-2.f, 5, -0.75f);
gl.glVertex3f(2.f, 5, -0.75f);
gl.glVertex3f(1.75f, 3, -0.5f);
gl.glVertex3f(-2.f, 5, 0.75f);
gl.glVertex3f(-2.f, 5, -0.75f);
gl.glVertex3f(2.f, 5, -0.75f);
gl.glVertex3f(2.f, 5, 0.75f);
gl.glColor3f(0f, 0f, 0f);
gl.glVertex3f(1.75f, 3, 0.5f);
gl.glVertex3f(1.75f, 3, -0.5f);
gl.glVertex3f(.75f, 2, -0.2f);
gl.glVertex3f(.75f, 2, 0.2f);
gl.glVertex3f(-1.75f, 3, 0.5f);
gl.glVertex3f(-1.75f, 3, -0.5f);
gl.glVertex3f(-.75f, 2, -0.2f);
gl.glVertex3f(-.75f, 2, 0.2f);
gl.glVertex3f(-1.75f, 3, 0.5f);
gl.glVertex3f(-.75f, 2, 0.2f);
gl.glVertex3f(.75f, 2, 0.2f);
gl.glVertex3f(1.75f, 3, 0.5f);
gl.glVertex3f(-1.75f, 3, -0.5f);
gl.glVertex3f(-.75f, 2, -0.2f);
gl.glVertex3f(.75f, 2, -0.2f);
gl.glVertex3f(1.75f, 3, -0.5f);
gl.glEnd();
gl.glColor3f(.8007f, .7539f, .7695f);
gl.glTranslatef(0f,5.5f,0.1f);
gl.glRotatef(90f, 1f, 0f, 0f);
glu.gluCylinder(bodyQuadric, .5f, .6f, 1f, 20, 10);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
private void drawLeg(GL2 gl, GLU glu,float T){
gl.glColor3f(.8007f, .7539f, .7695f);
gl.glPushMatrix();
float angle = (float) (15*Math.cos(Math.toRadians(T*360)));
gl.glTranslatef(-1.2f, 3f,-1.3f);
gl.glRotated(90, 1, 0, 0);
gl.glRotated(angle, 3f, 0,0);
glu.gluCylinder(bodyQuadric, .4f, .3f, 2.5f, 20, 10);
gl.glPopMatrix();
}
private void drawArm(GL2 gl, GLU glu,float T){
gl.glColor3f(.8007f, .7539f, .7695f);
gl.glPushMatrix();
float angle = (float) (15*Math.cos(Math.toRadians(T*360)));
gl.glTranslatef(-2f, 4.75f,-0.5f);
gl.glRotated(90, 1, 0, 0);
gl.glRotated(angle, 5f, 0,0);
glu.gluSphere(bodyQuadric, .4f, 20, 10);
glu.gluCylinder(bodyQuadric, .4f, .3f, 2.5f, 20, 10);
gl.glPopMatrix();
}
private void drawEye(GL2 gl, GLU glu) {
gl.glColor3f(1f, 1f, 1f);
gl.glPushMatrix();
gl.glTranslatef(-0.5f,6.3f,1.1f);
glu.gluSphere(bodyQuadric, .3f, 20, 10);
gl.glPopMatrix();
}
public void move(){
float speed;
if (!agro) {
speed = moveSpeed;
if (eyeAngle == 360) eyeAngle = 0;
if (locz < -20 ) {
if (!facingFront)eyeAngle-=rotateSpeed;
if (eyeAngle == 0) {facingFront = true;
locz +=speed*Math.cos(Math.toRadians(eyeAngle));
locx -=speed*Math.sin(Math.toRadians(eyeAngle));
}
}
else if (locz > 20){
if (facingFront) eyeAngle+=rotateSpeed;
if (eyeAngle == 180) {facingFront = false;
locz +=speed*Math.cos(Math.toRadians(eyeAngle));
locx -=speed*Math.sin(Math.toRadians(eyeAngle));
}
}
else {
locz +=speed*Math.cos(Math.toRadians(eyeAngle));
locx -=speed*Math.sin(Math.toRadians(eyeAngle));
}
}
else {speed = runSpeed;
//if player within range, turn and face player
locz +=speed*Math.cos(Math.toRadians(eyeAngle));
locx -=speed*Math.sin(Math.toRadians(eyeAngle));
}
}
public void draw(GL2 gl, GLU glu) {
move();
gl.glTranslatef(locx, (float) (locy + 0.1*Math.sin(Math.toRadians((T/60)*360))), locz);
gl.glRotatef(eyeAngle, 0, 1, 0);
drawMoving(gl, glu, T/60);
System.out.println("Position: " + locx + " " + locz);
T+=1f;
if (T > 60) T = 0;
}
@Override
public void projectileMoved(double x, double z) {
// TODO Auto-generated method stub
}
@Override
public void playerMoved(float x, float y, float z, float angle, float y_angle, PlayerStats s) {
float distance = (float) Math.sqrt(Math.pow((x-locx),2) + Math.pow((y-locy),2));
if (distance < sightRadius) {agro = true;}
if(distance < 2){s.changeHealth(-1);
};
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dae.io;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import java.io.IOException;
import java.io.Writer;
import org.w3c.dom.NamedNodeMap;
/**
*
* @author Koen Samyn
*/
public class XMLUtils {
public static void writeAttribute(Writer w, String key, String value) throws IOException {
if ( value == null){
return;
}
w.write(key);
w.write("='");
w.write(value);
w.write("' ");
}
public static void writeAttribute(Writer w, String key, boolean value) throws IOException {
w.write(key);
w.write("='");
if (value) {
w.write("true");
} else {
w.write("false");
}
w.write("' ");
}
public static void writeAttribute(Writer w, String key, int value) throws IOException {
w.write(key);
w.write("='");
w.write(Integer.toString(value));
w.write("' ");
}
public static void writeAttribute(Writer w, String key, float value) throws IOException {
w.write(key);
w.write("='");
w.write(Float.toString(value));
w.write("' ");
}
public static void writeAttribute(Writer w, String key, Vector3f value) throws IOException {
if ( value == null){
return;
}
w.write(key);
w.write("='[");
w.write(Float.toString(value.x));
w.write(",");
w.write(Float.toString(value.y));
w.write(",");
w.write(Float.toString(value.z));
w.write("]' ");
}
public static void writeAttribute(Writer w, String key, Quaternion value) throws IOException {
if (value == null) {
return;
}
w.write(key);
w.write("='[");
w.write(Float.toString(value.getX()));
w.write(',');
w.write(Float.toString(value.getY()));
w.write(',');
w.write(Float.toString(value.getZ()));
w.write(',');
w.write(Float.toString(value.getW()));
w.write("]' ");
}
/**
* Parses a float3 from a string defined as [x,y,z] with x, y and z floats
*
* @param float3 a string that defines 3 floating point variables.
* @return a new Vector3f object.
*/
public static Vector3f parseFloat3(String float3) {
if (float3.length() > 0) {
String withoutBrackets = float3.substring(1, float3.length() - 1);
String[] cs = withoutBrackets.split(",");
if (cs.length == 3) {
try {
float x = Float.parseFloat(cs[0]);
float y = Float.parseFloat(cs[1]);
float z = Float.parseFloat(cs[2]);
return new Vector3f(x, y, z);
} catch (NumberFormatException ex) {
return new Vector3f(0, 0, 0);
}
} else {
return new Vector3f(0, 0, 0);
}
} else {
return Vector3f.ZERO;
}
}
/**
* Parses a quaternion from a string defined as [x,y,z,w]
*
* @param quat a string that defines a quaternion.
* @return a new Quaternion object.
*/
public static Quaternion parseQuaternion(String quat) {
String withoutBrackets = quat.substring(1, quat.length() - 1);
String[] cs = withoutBrackets.split(",");
if (cs.length == 4) {
try {
float x = Float.parseFloat(cs[0]);
float y = Float.parseFloat(cs[1]);
float z = Float.parseFloat(cs[2]);
float w = Float.parseFloat(cs[3]);
return new Quaternion(x, y, z, w);
} catch (NumberFormatException ex) {
return Quaternion.IDENTITY;
}
} else {
return Quaternion.IDENTITY;
}
}
/**
* Parses a string that contains a color parameter defined as [r,g,b,a]. The
* r,g,b and a value should be in the range [0,1].
*
* @param color a string that defines a color.
* @return a new ColorRGBA color.
*/
public static ColorRGBA parseColor(String color) {
String withoutBrackets = color.substring(1, color.length() - 1);
String[] cs = withoutBrackets.split(",");
if (cs.length == 4) {
try {
float x = Float.parseFloat(cs[0]);
float y = Float.parseFloat(cs[1]);
float z = Float.parseFloat(cs[2]);
float w = Float.parseFloat(cs[3]);
return new ColorRGBA(x, y, z, w);
} catch (NumberFormatException ex) {
return ColorRGBA.White;
}
} else {
return ColorRGBA.Magenta;
}
}
/**
* Parses the value of the given attribute as a float.
* @param attributeName the name of the attribute.
* @param map the map that contains all the attributes.
* @return the float value.
*/
public static float parseFloat(String attributeName, NamedNodeMap map) {
org.w3c.dom.Node attr = map.getNamedItem(attributeName);
try {
return attr != null ? Float.parseFloat(attr.getTextContent()) : 0f;
} catch (NumberFormatException ex) {
return 0.0f;
}
}
/**
* Parses the value of the given attribute as an float.
* @param attributeName the name of the attribute.
* @param map the map that contains all the attributes.
* @return the float value.
*/
public static int parseInt(String attributeName, NamedNodeMap map) {
org.w3c.dom.Node attr = map.getNamedItem(attributeName);
try {
return attr != null ? Integer.parseInt(attr.getTextContent()) : 0;
} catch (NumberFormatException ex) {
return 0;
}
}
/**
* Parses the value of the given attribute as an boolean.
* @param attributeName the name of the attribute.
* @param map the map that contains all the attributes.
* @return the float value.
*/
public static boolean parseBoolean(String attributeName, NamedNodeMap map) {
org.w3c.dom.Node attr = map.getNamedItem(attributeName);
return attr != null ? Boolean.parseBoolean(attr.getTextContent()) : false;
}
} |
package game.math;
public class Vec2D {
private double x, y;
public Vec2D() {
x=y=0;
}
public Vec2D(Vec2D start, Vec2D end) {
this.x=end.x-start.x;
this.y=end.y-start.y;
}
public Vec2D(double x, double y) {
this.x=x;
this.y=y;
}
public Vec2D(Vec2D v) {
x=v.x;
y=v.y;
}
public void set(double value) {
x=y=value;
}
public void set(double x, double y) {
this.x=x;
this.y=y;
}
public void set(Vec2D v) {
this.x=v.x;
this.y=v.y;
}
public void setX(double x) {
this.x=x;
}
public void setY(double y) {
this.y=y;
}
public void setLength(double newLength) {
double t=newLength/length();
this.x*=t;
this.y*=t;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public void add(Vec2D v) {
this.x+=v.x;
this.y+=v.y;
}
public void sub(Vec2D v) {
this.x-=v.x;
this.y-=v.y;
}
public void add(double x, double y) {
this.x+=x;
this.y+=y;
}
public void sub(double x, double y) {
this.x-=x;
this.y-=y;
}
public void scale(double s) {
this.x*=s;
this.y*=s;
}
public double length() {
return Math.sqrt(x*x+y*y);
}
public double lengthSq() {
return x*x+y*y;
}
public double distanceTo(Vec2D v) {
double a=this.x-v.x;
double b=this.y-v.y;
return Math.sqrt(a*a+b*b);
}
public double distanceToSq(Vec2D v) {
double a=this.x-v.x;
double b=this.y-v.y;
return a*a+b*b;
}
public void abs() {
x=Math.abs(x);
y=Math.abs(y);
}
public void normalize() {
double inv=1/length();
x*=inv;
y*=inv;
}
public void validate() {
if (x==Double.NaN || x==Double.NEGATIVE_INFINITY || x==Double.POSITIVE_INFINITY ||
y==Double.NaN || y==Double.NEGATIVE_INFINITY || y==Double.POSITIVE_INFINITY) {
throw new RuntimeException("Invalid vector: "+this.toString());
}
}
@Override
public boolean equals(Object obj) {
return ((Vec2D)obj).x==this.x && ((Vec2D)obj).y==this.y;
}
@Override
public int hashCode() {
long l1 = Double.doubleToRawLongBits(x);
long l2 = Double.doubleToRawLongBits(y);
long l3 = l1 ^ l2;
int i1 = (int) (l3 >>> 32);
int i2 = (int) (l3 & 0x00000000FFFFFFFF);
return i1 ^ i2;
}
@Override
public String toString() {
return "["+x+", "+y+"]";
}
public static Vec2D add(Vec2D a, Vec2D b) {
return new Vec2D(a.x+b.x, a.y+b.y);
}
public static Vec2D add(Vec2D a, double x, double y) {
return new Vec2D(a.x+x, a.y+y);
}
public static Vec2D normalize(Vec2D v) {
double inv=1/v.length();
return new Vec2D(v.x*inv, v.y*inv);
}
public static Vec2D sub(Vec2D a, Vec2D b) {
return new Vec2D(a.x-b.x, a.y-b.y);
}
public static double distanceSquared(Vec2D a, Vec2D b) {
double v = a.x-b.x;
double u = a.y-b.y;
return v*v+u*u;
}
public static Vec2D distanceVec(Vec2D from, Vec2D to) {
return new Vec2D(to.x-from.x, to.y-from.y);
}
public static double dot(Vec2D v1, Vec2D v2) {
return v1.x*v2.x+v1.y*v2.y;
}
public static double angleBetween(Vec2D v1, Vec2D v2) {
return Math.acos(dot(v1, v2)/Math.sqrt(v1.lengthSq()*v2.lengthSq()));
}
public static double pointLineDistance(Vec2D a, Vec2D b, Vec2D p) {
return Math.abs((p.x-a.x)*(b.y-a.y)-(p.y-a.y)*(b.x-a.x))/Math.hypot(b.x-a.x, b.y-a.y);
}
public static double pointLineSegmentDistanceSquared(Vec2D a, Vec2D b, Vec2D p) {
double l2 = distanceSquared(a, b);
if (l2 == 0.0) {
return distanceSquared(p, a);
}
double t = ((p.x-a.x)*(b.x-a.x) + (p.y-a.y)*(b.y-a.y)) / l2;
if (t < 0) {
return distanceSquared(p, a);
} else if (t > 0) {
return distanceSquared(p, b);
} else {
Vec2D q = new Vec2D(a.x + t*(b.x-a.x),
a.y + t*(b.y-a.y));
return distanceSquared(p, q);
}
}
public static double pointLineSegmentDistance(Vec2D a, Vec2D b, Vec2D p) {
return Math.sqrt(pointLineSegmentDistanceSquared(a, b, p));
}
} |
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import service.UserService;
import json.JSONFailureException;
/**
* The class ScoreREport, a populated BackgroundPanel.
*
* @author Taylor Calder
* @version 1.0
*/
@SuppressWarnings("serial")
public class ScoreReport extends BackgroundPanel {
/**
* Instantiates a PasswordReset instance.
*
* @param controller the controller
*/
public ScoreReport(Controller controller, int correct, int level) {
//Calls superclass constructor to create the background panel
super("http://jbaron6.cs2212.ca/img/default_background.png", new GridBagLayout());
//Create the components
JLabel score1 = new JLabel("You got " + correct + " out of 12 questions right.");
JLabel score2 = new JLabel("Your previous high score is " + "<highscore goes here>");
JLabel score3 = new JLabel("<Post to Facebook Goes Here>");
JButton fbB = new JButton("Post to Facebook!");
JButton levelB = new JButton("Play the level game!");
levelB.setMaximumSize(new Dimension(200,20));
levelB.setMinimumSize(new Dimension(200,20));
levelB.setPreferredSize(new Dimension(200,20));
fbB.setMaximumSize(new Dimension(200,20));
fbB.setMinimumSize(new Dimension(200,20));
fbB.setPreferredSize(new Dimension(200,20));
score1.setFont(Controller.getFont().deriveFont(Font.PLAIN, 28));
score2.setFont(Controller.getFont().deriveFont(Font.PLAIN, 28));
score3.setFont(Controller.getFont().deriveFont(Font.PLAIN, 28));
//Add the components to the view
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0,50,25,50);
c.fill = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 0;
add(score1, c); //Score message 1
c.gridy++;
add(score2, c); //Score message 2
// c.gridy++;
// add(score3, c); //Score message 3
c.gridwidth = 1;
c.gridy++;
c.gridy++;
add(fbB, c); // Facebook button
c.gridy++;
c.gridy++;
add(levelB, c); // Level game button
}
} |
/*
* $Id: HighWirePdfFilterFactory.java,v 1.21 2008-02-27 23:17:57 thib_gc Exp $
*/
package org.lockss.plugin.highwire;
import java.io.*;
import java.util.*;
import org.lockss.filter.pdf.*;
import org.lockss.filter.pdf.PageTransformUtil.ExtractStringsToOutputStream;
import org.lockss.plugin.*;
import org.lockss.util.*;
import org.pdfbox.cos.*;
import org.pdfbox.pdmodel.*;
import org.pdfbox.pdmodel.common.PDRectangle;
import org.pdfbox.pdmodel.interactive.action.type.*;
import org.pdfbox.pdmodel.interactive.annotation.*;
import org.pdfbox.util.operator.OperatorProcessor;
public class HighWirePdfFilterFactory implements FilterFactory {
/**
* <p>Bypasses {@link TextScrapingDocumentTransform}, which fails on
* zero-length results. To be fixed in the PDF framework later.</p>
* @see TextScrapingDocumentTransform
*/
public static abstract class ResilientTextScrapingDocumentTransform extends OutputStreamDocumentTransform {
public abstract DocumentTransform makePreliminaryTransform() throws IOException;
public DocumentTransform makeTransform() throws IOException {
return new ConditionalDocumentTransform(makePreliminaryTransform(),
false, // Difference with TextScrapingDocumentTransform
new TransformEachPage(new ExtractStringsToOutputStream(outputStream) {
@Override
public void processStream(PDPage arg0, PDResources arg1, COSStream arg2) throws IOException {
logger.debug3("ResilientTextScrapingDocumentTransform: unconditional signalChange()");
signalChange(); // Difference with TextScrapingDocumentTransform
super.processStream(arg0, arg1, arg2);
}
}));
}
}
public static abstract class AbstractOnePartDownloadedFromOperatorProcessor
extends ConditionalMergeOperatorProcessor {
/* Inherit documentation */
public boolean identify(List tokens) {
boolean ret = false;
int progress = 0;
// Iterate from the end
iteration: for (int tok = tokens.size() - 1 ; tok >= 0 ; --tok) {
switch (progress) {
case 0:
// End of subsequence
if (tok != tokens.size() - 1) { break iteration; }
if (PdfUtil.isEndTextObject(tokens, tok)) { ++progress; }
break;
case 1:
// Not BT
if (PdfUtil.isBeginTextObject(tokens,tok)) { break iteration; }
// Tj and its argument is the string "Downloaded from "
if (PdfUtil.matchShowText(tokens, tok, "Downloaded from ")) { ++progress; }
break;
case 2:
// Not BT
if (PdfUtil.isBeginTextObject(tokens,tok)) { break iteration; }
// Tj and its argument is a domain name string
if (PdfUtil.matchShowTextMatches(tokens, tok, "(?:http://)?[-0-9A-Za-z]+(?:\\.[-0-9A-Za-z]+)+")) { ++progress; }
break;
case 3:
// Not BT
if (PdfUtil.isBeginTextObject(tokens,tok)) { break iteration; }
// Tj and its string argument
if (PdfUtil.matchShowText(tokens, tok)) { ++progress; }
break;
case 4:
// BT; beginning of subsequence
if (PdfUtil.isBeginTextObject(tokens,tok)) { ret = (tok == 0); break iteration; }
break;
}
}
if (logger.isDebug3()) {
logger.debug3("AbstractOnePartDownloadedFromOperatorProcessor candidate match: " + ret);
}
return ret;
}
}
public static abstract class AbstractThreePartDownloadedFromOperatorProcessor
extends ConditionalSubsequenceOperatorProcessor {
/* Inherit documentation */
public int getSubsequenceLength() {
// Examine the last 54 tokens in the output sequence
return 54;
}
/* Inherit documentation */
public boolean identify(List tokens) {
boolean ret = false;
int progress = 0;
// Iterate from the end
iteration: for (int tok = tokens.size() - 1 ; tok >= 0 ; --tok) {
switch (progress) {
case 0:
// End of subsequence
if (tok != tokens.size() - 1) { break iteration; }
if (PdfUtil.isEndTextObject(tokens, tok)) { ++progress; }
break;
case 1:
// Not BT
if (PdfUtil.isBeginTextObject(tokens,tok)) { break iteration; }
// Tj and its argument is the string "Downloaded from "
if (PdfUtil.matchShowText(tokens, tok, "Downloaded from ")) { ++progress; }
break;
case 2:
if (PdfUtil.isBeginTextObject(tokens,tok)) { ++progress; }
break;
case 3:
if (PdfUtil.isEndTextObject(tokens,tok)) { ++progress; }
break;
case 4:
// Not BT
if (PdfUtil.isBeginTextObject(tokens,tok)) { break iteration; }
// Tj and its argument is a domain name string
if (PdfUtil.matchShowTextMatches(tokens, tok, "(?:http://)?[-0-9A-Za-z]+(?:\\.[-0-9A-Za-z]+)+")) { ++progress; }
break;
case 5:
if (PdfUtil.isBeginTextObject(tokens,tok)) { ++progress; }
break;
case 6:
if (PdfUtil.isEndTextObject(tokens,tok)) { ++progress; }
break;
case 7:
// Not BT
if (PdfUtil.isBeginTextObject(tokens,tok)) { break iteration; }
// Tj and its string argument
if (PdfUtil.matchShowText(tokens, tok)) { ++progress; }
break;
case 8:
if (PdfUtil.isBeginTextObject(tokens,tok)) { ret = true; break iteration; }
break;
}
}
if (logger.isDebug3()) {
logger.debug3("AbstractThreePartDownloadedFromOperatorProcessor candidate match: " + ret);
}
return ret;
}
}
public static class CollapseDownloadedFrom extends AggregatePageTransform {
public CollapseDownloadedFrom(ArchivalUnit au) throws IOException {
super(PdfUtil.OR,
new CollapseOnePartDownloadedFrom(au),
new CollapseThreePartDownloadedFrom(au));
}
}
public static class CollapseDownloadedFromAndNormalizeHyperlinks
extends AggregatePageTransform {
public CollapseDownloadedFromAndNormalizeHyperlinks(ArchivalUnit au) throws IOException {
super(new CollapseDownloadedFrom(au),
new NormalizeHyperlinks());
}
}
public static class CollapseOnePartDownloadedFrom extends PageStreamTransform {
public static class CollapseOnePartDownloadedFromOperatorProcessor
extends AbstractOnePartDownloadedFromOperatorProcessor {
public List getReplacement(List tokens) {
// Replace by an empty text object
return ListUtil.list(// Known to be "BT"
tokens.get(0),
// Known to be "ET"
tokens.get(tokens.size() - 1));
}
}
public CollapseOnePartDownloadedFrom(final ArchivalUnit au) throws IOException {
super(new OperatorProcessorFactory() {
public OperatorProcessor newInstanceForName(String className) throws LinkageError, ExceptionInInitializerError, ClassNotFoundException, IllegalAccessException, InstantiationException, SecurityException {
return (OperatorProcessor)au.getPlugin().newAuxClass(className,
OperatorProcessor.class);
}
},
// "BT" operator: split unconditionally
PdfUtil.BEGIN_TEXT_OBJECT, SplitOperatorProcessor.class,
// "ET" operator: merge conditionally using CollapseOnePartDownloadedFromOperatorProcessor
PdfUtil.END_TEXT_OBJECT, CollapseOnePartDownloadedFromOperatorProcessor.class);
}
}
public static class CollapseThreePartDownloadedFrom extends PageStreamTransform {
public static class CollapseThreePartDownloadedFromOperatorProcessor
extends AbstractThreePartDownloadedFromOperatorProcessor {
public List getReplacement(List tokens) {
// Known to have at least three "BT" tokens
int bt = -1; int counter = 0;
for (int tok = tokens.size() - 1 ; counter < 3 && tok >= 0 ; --tok) {
if (PdfUtil.isBeginTextObject(tokens, tok)) {
bt = tok; ++counter;
}
}
// Replace by an empty text object, preserving earlier tokens
List ret = new ArrayList(bt + 2);
ret.addAll(// Tokens before the three text objects
tokens.subList(0, bt));
ret.addAll(ListUtil.list(// Known to be "BT"
tokens.get(bt),
// Known to be "ET"
tokens.get(tokens.size() - 1)));
return ret;
}
}
public CollapseThreePartDownloadedFrom(final ArchivalUnit au) throws IOException {
super(new OperatorProcessorFactory() {
public OperatorProcessor newInstanceForName(String className) throws LinkageError, ExceptionInInitializerError, ClassNotFoundException, IllegalAccessException, InstantiationException, SecurityException {
return (OperatorProcessor)au.getPlugin().newAuxClass(className,
OperatorProcessor.class);
}
},
// "ET" operator: inspect subsequences ending in "ET" using CollapseThreePartDownloadedFromOperatorProcessor
PdfUtil.END_TEXT_OBJECT, CollapseThreePartDownloadedFromOperatorProcessor.class);
}
}
public static class EraseMetadataSection implements DocumentTransform {
public boolean transform(PdfDocument pdfDocument) throws IOException {
pdfDocument.setMetadata(" ");
return true;
}
}
public static class NormalizeHyperlinks implements PageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
boolean ret = false; // Expecting at least one
for (Iterator iter = pdfPage.getAnnotationIterator() ; iter.hasNext() ; ) {
PDAnnotation pdAnnotation = (PDAnnotation)iter.next();
if (pdAnnotation instanceof PDAnnotationLink) {
PDAnnotationLink pdAnnotationLink = (PDAnnotationLink)pdAnnotation;
PDAction pdAction = pdAnnotationLink.getAction();
if (pdAction instanceof PDActionURI) {
PDRectangle rect = pdAnnotation.getRectangle();
rect.setLowerLeftY(12.34f); // 12.34f is arbitrary
rect.setUpperRightY(56.78f); // 56.78f is arbitrary
ret = true; // Found at least one
}
}
}
return ret;
}
}
public static class NormalizeMetadata extends AggregateDocumentTransform {
public NormalizeMetadata() {
super(// Remove the modification date
new RemoveModificationDate(),
// Remove the text in the metadata section
new EraseMetadataSection(),
// Remove the variable part of the document ID
new NormalizeTrailerId());
}
}
public static class NormalizeTrailerId implements DocumentTransform {
public boolean transform(PdfDocument pdfDocument) throws IOException {
COSDictionary trailer = pdfDocument.getTrailer();
if (trailer != null) {
// Put bogus ID to prevent autogenerated (variable) ID
COSArray id = new COSArray();
id.add(new COSString("12345678901234567890123456789012"));
id.add(id.get(0));
trailer.setItem(COSName.getPDFName("ID"), id);
return true; // success
}
return false; // all other cases are unexpected
}
}
public static class RemoveModificationDate implements DocumentTransform {
public boolean transform(PdfDocument pdfDocument) throws IOException {
pdfDocument.removeModificationDate();
return true;
}
}
public InputStream createFilteredInputStream(ArchivalUnit au,
InputStream in,
String encoding) {
logger.debug2("PDF filter factory for: " + au.getName());
OutputDocumentTransform documentTransform = PdfUtil.getOutputDocumentTransform(au);
if (documentTransform == null) {
logger.debug2("Unfiltered");
return in;
}
else {
if (documentTransform instanceof ArchivalUnitDependent) {
logger.debug2("Filtered with " + documentTransform.getClass().getName());
ArchivalUnitDependent aud = (ArchivalUnitDependent)documentTransform;
aud.setArchivalUnit(au);
}
else {
logger.debug2("Filtered with " + documentTransform.getClass().getName() + " but not AU-dependent");
}
return PdfUtil.applyFromInputStream(documentTransform, in);
}
}
/**
* <p>A logger for use by this class.</p>
*/
private static Logger logger = Logger.getLogger("HighWirePdfFilterFactory");
} |
package utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.webdsl.WebDSLEntity;
import org.webdsl.lang.Environment;
import org.webdsl.logging.Logger;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public abstract class AbstractPageServlet{
protected abstract void renderDebugJsVar(PrintWriter sout);
protected abstract boolean logSqlCheckAccess();
protected abstract void initTemplateClass();
protected abstract void redirectHttpHttps();
protected abstract boolean isActionSubmit();
protected abstract String[] getUsedSessionEntityJoins();
protected TemplateServlet templateservlet = null;
protected abstract org.webdsl.WebDSLEntity getRequestLogEntry();
protected abstract void addPrincipalToRequestLog(org.webdsl.WebDSLEntity rle);
protected abstract void addLogSqlToSessionMessages();
public Session hibernateSession = null;
protected static Pattern isMarkupLangMimeType= Pattern.compile("html|xml$");
protected static Pattern baseURLPattern= Pattern.compile("(^\\w{0,6})(:
protected AbstractPageServlet commandingPage = this;
public boolean isReadOnly = false;
public boolean isWebService(){ return false; }
public String placeholderId = "1";
static{
common_css_link_tag_suffix = "/stylesheets/" + CachedResourceFileNameHelper.getNameWithHash("stylesheets", "common_.css") + "\" rel=\"stylesheet\" type=\"text/css\" />";
fav_ico_link_tag_suffix = "/" + CachedResourceFileNameHelper.getNameWithHash("", "favicon.ico") + "\" rel=\"shortcut icon\" type=\"image/x-icon\" />";
ajax_js_include_name = "ajax.js";
}
public void serve(HttpServletRequest request, HttpServletResponse httpServletResponse, Map<String, String> parammap, Map<String, List<String>> parammapvalues, Map<String,List<utils.File>> fileUploads) throws Exception
{
initTemplateClass();
this.startTime = System.currentTimeMillis();
ThreadLocalPage.set(this);
this.request=request;
this.httpServletResponse = httpServletResponse;
this.response = new ResponseWrapper(httpServletResponse);
this.parammap = parammap;
this.parammapvalues = parammapvalues;
this.fileUploads=fileUploads;
redirectHttpHttps();
String ajaxParam = parammap.get( "__ajax_runtime_request__" );
if( ajaxParam != null ){
this.setAjaxRuntimeRequest( true );
if( ajaxParam != "1" ){
placeholderId = ajaxParam;
}
}
org.webdsl.WebDSLEntity rle = getRequestLogEntry();
org.apache.log4j.MDC.put("request", rle.getId().toString());
org.apache.log4j.MDC.put("template", "/" + getPageName());
utils.RequestAppender reqAppender = null;
if(parammap.get("disableopt") != null){
this.isOptimizationEnabled = false;
}
if(parammap.get("logsql") != null){
this.isLogSqlEnabled = true;
this.isPageCacheDisabled = true;
reqAppender = utils.RequestAppender.getInstance();
}
if(reqAppender != null){
reqAppender.addRequest(rle.getId().toString());
}
if(parammap.get("nocache") != null){
this.isPageCacheDisabled = true;
}
initRequestVars();
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
if(isReadOnly){
hibernateSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
}
else{
hibernateSession.setFlushMode(org.hibernate.FlushMode.COMMIT);
}
try
{
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
ThreadLocalServlet.get().loadSessionManager(hibernateSession, getUsedSessionEntityJoins());
ThreadLocalServlet.get().retrieveIncomingMessagesFromHttpSession();
initVarsAndArgs();
enterPlaceholderIdContext();
if(isActionSubmit()) {
if(parammap.get("__action__link__") != null) {
this.setActionLinkUsed(true);
}
templateservlet.storeInputs(null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
//storeinputs also finds which action is executed, since validation might be ignored using [ignore-validation] on the submit
boolean ignoreValidation = actionToBeExecutedHasDisabledValidation;
if (!ignoreValidation){
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
}
if(validated){
templateservlet.handleActions(null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
}
}
if(isNotValid()){
// mark transaction so it will be aborted at the end
// entered form data can be used to update the form on the client with ajax, taking into account if's and other control flow template elements
// this also means that data in vars/args and hibernate session should not be cleared until form is rendered
abortTransaction();
}
String outstream = s.toString();
if(download != null) { //File.download() excecuted in action
download();
}
else {
boolean isAjaxResponse = true;
// regular render, or failed action render
if( hasNotExecutedAction() || isNotValid() ){
// ajax replace performed during validation, assuming that handles all validation
// all inputajax templates use rollback() to prevent making actual changes -> check for isRollback()
if(isAjaxRuntimeRequest() && outstream.length() > 0 && isRollback()){
response.getWriter().write("[");
response.getWriter().write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}");
}
response.getWriter().write(",");
}
response.getWriter().write("{}]");
}
// action called but no action found
else if( !isWebService() && isValid() && isActionSubmit() ){
org.webdsl.logging.Logger.error("Error: server received POST request but was unable to dispatch to a proper action (" + getRequestURL() + ")" );
httpServletResponse.setStatus( 404 );
response.getWriter().write("404 \n Error: server received POST request but was unable to dispatch to a proper action");
}
// action inside ajax template called and failed
else if( isAjaxTemplateRequest() && isActionSubmit() ){
StringWriter s1 = renderPageOrTemplateContents();
response.getWriter().write("[{action:\"replace\", id:{type:'enclosing-placeholder'}, value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(s1.toString()) + "\"}]");
}
//actionLink or ajax action used (request came through js runtime), and action failed
else if( isActionLinkUsed() || isAjaxRuntimeRequest() ){
validationFormRerender = true;
renderPageOrTemplateContents();
if(submittedFormId != null){
response.getWriter().write("[{action:\"replace\", id:\"" + submittedFormId + "\", value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]");
}
else{
response.getWriter().write("[{action:\"replace\", id:{submitid:'" + submittedSubmitId + "'}, value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]");
}
}
// 1 regular render without any action being executed
// 2 regular action submit, and action failed
// 3 redirect in page init
// 4 download in page init
else{
isAjaxResponse = false;
renderOrInitAction();
}
}
// successful action, always redirect, no render
else {
// actionLink or ajax action used and replace(placeholder) invoked
if( isReRenderPlaceholders() ){
response.getWriter().write( "[" );
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
renderDynamicFormWithOnlyDirtyData = true;
renderPageOrTemplateContents(); // content of placeholders is collected in reRenderPlaceholdersContent map
StringWriter replacements = new StringWriter();
boolean addComma = false;
for(String ph : reRenderPlaceholders){
if(addComma){ replacements.write(","); }
else { addComma = true; }
replacements.write("{action:\"replace\", id:\""+ph+"\", value:\""
+ org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(reRenderPlaceholdersContent.get(ph))
+ "\"}");
}
response.getWriter().write( replacements.toString() );
if( outstream.length() > 0 ){
response.getWriter().write( "," + outstream.substring(0, outstream.length() - 1) + "]" ); // Other ajax updates, such as clear(ph). Done after ph rerendering to allow customization.
}
else{
response.getWriter().write( "]" );
}
}
//hasExecutedAction() && isValid()
else if( isAjaxRuntimeRequest() ){
response.getWriter().write("[");
response.getWriter().write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}");
}
response.getWriter().write(",");
}
response.getWriter().write("{}]");
}
else if( isActionLinkUsed() ){
//action link also uses ajax when ajax is not enabled
//, send only redirect location, so the client can simply set
// window.location = req.responseText;
response.getWriter().write("[{action:\"relocate\", value:\""+this.getRedirectUrl() + "\"}]");
} else {
isAjaxResponse = false;
}
if(!isAjaxRuntimeRequest()) {
addLogSqlToSessionMessages();
}
//else: action successful + no validation error + regular submit
// -> always results in a redirect, no further action necessary here
}
if(isAjaxResponse){
response.setContentType("application/json");
}
}
updatePageRequestStatistics();
hibernateSession = utils.HibernateUtil.getCurrentSession();
if( isTransactionAborted() || isRollback() ){
try{
hibernateSession.getTransaction().rollback();
response.sendContent();
}
catch (org.hibernate.SessionException e){
if(!e.getMessage().equals("Session is closed!")){ // closed session is not an issue when rolling back
throw e;
}
}
}
else {
ThreadLocalServlet.get().storeOutgoingMessagesInHttpSession( !isRedirected() || isPostRequest() );
addPrincipalToRequestLog(rle);
if(!this.isAjaxRuntimeRequest()){
ThreadLocalServlet.get().setEndTimeAndStoreRequestLog(utils.HibernateUtil.getCurrentSession());
}
ThreadLocalServlet.get().setCookie(hibernateSession);
if(isReadOnly || !hasWrites){ // either page has read-only modifier, or no writes have been detected
hibernateSession.getTransaction().rollback();
}
else{
hibernateSession.flush();
validateEntities();
hibernateSession.getTransaction().commit();
invalidatePageCacheIfNeeded();
}
if(exceptionInHibernateInterceptor != null){
throw exceptionInHibernateInterceptor;
}
response.sendContent();
}
ThreadLocalOut.popChecked(out);
}
catch(utils.MultipleValidationExceptions mve){
String url = getRequestURL();
org.webdsl.logging.Logger.error("Validation exceptions occurred while handling request URL [ " + url + " ]. Transaction is rolled back.");
for(utils.ValidationException vex : mve.getValidationExceptions()){
org.webdsl.logging.Logger.error( "Validation error: " + vex.getErrorMessage() , vex );
}
hibernateSession.getTransaction().rollback();
setValidated(false);
throw mve;
}
catch(utils.EntityNotFoundException enfe) {
org.webdsl.logging.Logger.error( enfe.getMessage() + ". Transaction is rolled back." );
if(hibernateSession.isOpen()){
hibernateSession.getTransaction().rollback();
}
throw enfe;
}
catch (Exception e) {
String url = getRequestURL();
org.webdsl.logging.Logger.error("exception occurred while handling request URL [ " + url + " ]. Transaction is rolled back.");
org.webdsl.logging.Logger.error("exception message: "+e.getMessage(), e);
if(hibernateSession.isOpen()){
hibernateSession.getTransaction().rollback();
}
throw e;
}
finally{
cleanupThreadLocals();
org.apache.log4j.MDC.remove("request");
org.apache.log4j.MDC.remove("template");
if(reqAppender != null) reqAppender.removeRequest(rle.getId().toString());
}
}
// LoadingCache is thread-safe
public static boolean pageCacheEnabled = utils.BuildProperties.getNumCachedPages() > 0;
public static Cache<String, CacheResult> cacheAnonymousPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateAllPageCache = false;
protected boolean shouldTryCleanPageCaches = false;
public String invalidateAllPageCacheMessage;
public void invalidateAllPageCache(String entityname){
commandingPage.invalidateAllPageCacheInternal(entityname);
}
private void invalidateAllPageCacheInternal(String entityname){
invalidateAllPageCache = true;
invalidateAllPageCacheMessage = entityname;
}
public void shouldTryCleanPageCaches(){
commandingPage.shouldTryCleanPageCachesInternal();
}
private void shouldTryCleanPageCachesInternal(){
shouldTryCleanPageCaches = true;
}
public static Cache<String, CacheResult> cacheUserSpecificPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateUserSpecificPageCache = false;
public String invalidateUserSpecificPageCacheMessage;
public void invalidateUserSpecificPageCache(String entityname){
commandingPage.invalidateUserSpecificPageCacheInternal(entityname);
}
private void invalidateUserSpecificPageCacheInternal(String entityname){
invalidateUserSpecificPageCache = true;
String propertySetterTrace = Warning.getStackTraceLineAtIndex(4);
invalidateUserSpecificPageCacheMessage = entityname + " - " + propertySetterTrace;
}
public boolean pageCacheWasUsed = false;
public void invalidatePageCacheIfNeeded(){
if(pageCacheEnabled && shouldTryCleanPageCaches){
if(invalidateAllPageCache){
Logger.info("All page caches invalidated, triggered by change in: "+invalidateAllPageCacheMessage);
cacheAnonymousPages.invalidateAll();
cacheUserSpecificPages.invalidateAll();
}
else if(invalidateUserSpecificPageCache){
Logger.info("user-specific page cache invalidated, triggered by change in: "+invalidateUserSpecificPageCacheMessage);
cacheUserSpecificPages.invalidateAll();
}
}
}
public void renderOrInitAction() throws IOException{
String key = getRequestURL();
String s = "";
Cache<String, CacheResult> cache = null;
AbstractDispatchServletHelper servlet = ThreadLocalServlet.get();
if( // not using page cache if:
this.isPageCacheDisabled // ?nocache added to URL
|| this.isPostRequest() // post parameters are not included in cache key
|| isNotValid() // data validation errors need to be rendered
|| !servlet.getIncomingSuccessMessages().isEmpty() // success messages need to be rendered
){
StringWriter renderedContent = renderPageOrTemplateContents();
if(!mimetypeChanged){
s = renderResponse(renderedContent);
}
else{
s = renderedContent.toString();
}
}
else{ // using page cache
if( // use user-specific page cache if:
servlet.sessionHasChanges() // not necessarily login, any session data changes can be included in a rendered page
|| webdsl.generated.functions.loggedIn_.loggedIn_() // user might have old session from before application start, this check is needed to avoid those logged in pages ending up in the anonymous page cache
){
key = key + servlet.getSessionManager().getId();
cache = cacheUserSpecificPages;
}
else{
cache = cacheAnonymousPages;
}
try{
pageCacheWasUsed = true;
CacheResult result = cache.get(key,
new Callable<CacheResult>(){
public CacheResult call(){
// System.out.println("key not found");
pageCacheWasUsed = false;
StringWriter renderedContent = renderPageOrTemplateContents();
CacheResult result = new CacheResult();
if(!mimetypeChanged){
result.body = renderResponse(renderedContent);
}
else{
result.body = renderedContent.toString();
}
result.mimetype = getMimetype();
return result;
}
});
s = result.body;
setMimetype(result.mimetype);
}
catch(java.util.concurrent.ExecutionException e){
e.printStackTrace();
}
}
// redirect in init action can be triggered with GET request, the render call in the line above will execute such inits
if( !isPostRequest() && isRedirected() ){
redirect();
if(cache != null){ cache.invalidate(key); }
}
else if( download != null ){ //File.download() executed in page/template init block
download();
if(cache != null){ cache.invalidate(key); } // don't cache binary file response in this page response cache, can be cached on client with expires header
}
else{
response.setContentType(getMimetype());
PrintWriter sout = response.getWriter(); //reponse.getWriter() must be called after file download checks
sout.write(s);
}
}
public boolean renderDynamicFormWithOnlyDirtyData = false;
public StringWriter renderPageOrTemplateContents(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
if(getParammap().get("dynamicform") == null){
// regular pages and forms
if(isNotValid()){
clearHibernateCache();
}
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
else{
// dynamicform uses submitted variable data to process form content
// render form with newly entered data, rest with the current persisted data
if(isNotValid() && !renderDynamicFormWithOnlyDirtyData){
StringWriter theform = new StringWriter();
PrintWriter pwform = new PrintWriter(theform);
ThreadLocalOut.push(pwform);
// render, when encountering submitted form save in abstractpage
validationFormRerender = true;
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(pwform);
clearHibernateCache();
}
ThreadLocalOut.push(out);
// render, when isNotValid and encountering submitted form render old
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
return s;
}
public StringWriter renderPageOrTemplateContentsSingle(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
return s;
}
private boolean validationFormRerender = false;
public boolean isValidationFormRerender(){
return validationFormRerender;
}
public String submittedFormContent = null;
public String submittedFormId = null;
public String submittedSubmitId = null;
// helper methods that enable a submit without enclosing form to be ajax-refreshed when validation error occurs
protected StringWriter submitWrapSW;
protected PrintWriter submitWrapOut;
public void submitWrapOpenHelper(String submitId){
if( ! inSubmittedForm && validationFormRerender && request != null && getParammap().get(submitId) != null ){
submittedSubmitId = submitId;
submitWrapSW = new java.io.StringWriter();
submitWrapOut = new java.io.PrintWriter(submitWrapSW);
ThreadLocalOut.push(submitWrapOut);
ThreadLocalOut.peek().print("<span submitid=" + submitId + ">");
}
}
public void submitWrapCloseHelper(){
if( ! inSubmittedForm && validationFormRerender && submitWrapSW != null ){
ThreadLocalOut.peek().print("</span>");
ThreadLocalOut.pop();
submittedFormContent = submitWrapSW.toString();
submitWrapSW = null;
}
}
private static String common_css_link_tag_suffix;
private static String fav_ico_link_tag_suffix;
private static String ajax_js_include_name;
public String renderResponse(StringWriter s) {
StringWriter sw = new StringWriter();
PrintWriter sout = new PrintWriter(sw);
ThreadLocalOut.push(sout);
addJavascriptInclude( utils.IncludePaths.jQueryJS() );
addJavascriptInclude( ajax_js_include_name );
sout.println("<!DOCTYPE html>");
sout.println("<html>");
sout.println("<head>");
sout.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
sout.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
sout.println("<title>"+getPageTitle().replaceAll("<[^>]*>","")+"</title>");
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+fav_ico_link_tag_suffix);
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+common_css_link_tag_suffix);
renderDebugJsVar(sout);
sout.println("<script type=\"text/javascript\">var contextpath=\""+ThreadLocalPage.get().getAbsoluteLocation()+"\";</script>");
for(String sheet : this.stylesheets) {
if(sheet.startsWith("
sout.print("<link rel=\"stylesheet\" href=\""+ sheet + "\" type=\"text/css\" />");
}
else{
String hashedName = CachedResourceFileNameHelper.getNameWithHash("stylesheets", sheet);
sout.print("<link rel=\"stylesheet\" href=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/stylesheets/"+hashedName+"\" type=\"text/css\" />");
}
}
for(String script : this.javascripts) {
if(script.startsWith("
sout.println("<script type=\"text/javascript\" src=\"" + script + "\"></script>");
}
else{
String hashedName = CachedResourceFileNameHelper.getNameWithHash("javascript", script);
sout.println("<script type=\"text/javascript\" src=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/javascript/"+hashedName+"\"></script>");
}
}
for(Map.Entry<String,String> headEntry : customHeadNoDuplicates.entrySet()) {
// sout.println("<!-- " + headEntry.getKey() + " -->");
sout.println(headEntry.getValue());
}
for(String headEntry : customHeads) {
sout.println(headEntry);
}
sout.println("</head>");
sout.print("<body id=\""+this.getPageName()+"\"");
for(String attribute : this.bodyAttributes) {
sout.print(attribute);
}
sout.print(">");
renderLogSqlMessage();
renderIncomingSuccessMessages();
s.flush();
sout.write(s.toString());
if(this.isLogSqlEnabled()){
if(logSqlCheckAccess()){
sout.print("<hr/><div class=\"logsql\">");
utils.HibernateLog.printHibernateLog(sout, this, null);
sout.print("</div>");
}
else{
sout.print("<hr/><div class=\"logsql\">Access to SQL logs was denied.</div>");
}
}
sout.print("</body>");
sout.println("</html>");
ThreadLocalOut.popChecked(sout);
return sw.toString();
}
//ajax/js runtime request related
protected abstract void initializeBasics(AbstractPageServlet ps, Object[] args);
public boolean isServingAsAjaxResponse = false;
public void serveAsAjaxResponse(Object[] args, TemplateCall templateArg, String placeholderId)
{
AbstractPageServlet ps = ThreadLocalPage.get();
TemplateServlet ts = ThreadLocalTemplate.get();
//inherit commandingPage
commandingPage = ps.commandingPage;
//use passed PageServlet ps here, since this is the context for this type of response
initializeBasics(ps, args);
ThreadLocalPage.set(this);
//outputstream threadlocal is already set, see to-java-servlet/ajax/ajax.str
this.isServingAsAjaxResponse = true;
this.placeholderId = placeholderId;
enterPlaceholderIdContext();
templateservlet.render(null, args, Environment.createNewLocalEnvironment(envGlobalAndSession), null); // new clean environment with only the global templates, and global/session vars
ThreadLocalTemplate.set(ts);
ThreadLocalPage.set(ps);
}
protected boolean isTemplate() { return false; }
public static AbstractPageServlet getRequestedPage(){
return ThreadLocalPage.get();
}
private boolean passedThroughAjaxTemplate = false;
public boolean passedThroughAjaxTemplate(){
return passedThroughAjaxTemplate;
}
public void setPassedThroughAjaxTemplate(boolean b){
passedThroughAjaxTemplate = b;
}
protected boolean isLogSqlEnabled = false;
public boolean isLogSqlEnabled() { return isLogSqlEnabled; }
public boolean isPageCacheDisabled = false;
protected boolean isOptimizationEnabled = true;
public boolean isOptimizationEnabled() { return isOptimizationEnabled; }
public String getExtraQueryArguments(String firstChar) { // firstChar is expected to be ? or &, depending on whether there are more query arguments
HttpServletRequest req = getRequest();
return (req != null && req.getQueryString() != null) ? (firstChar + req.getQueryString()) : "";
}
public abstract String getPageName();
public abstract String getUniqueName();
protected MessageDigest messageDigest = null;
public MessageDigest getMessageDigest(){
if(messageDigest == null){
try{
messageDigest = MessageDigest.getInstance("MD5");
}
catch(NoSuchAlgorithmException ae)
{
org.webdsl.logging.Logger.error("MD5 not available: "+ae.getMessage());
return null;
}
}
return messageDigest;
}
public boolean actionToBeExecutedHasDisabledValidation = false;
public boolean actionHasAjaxPageUpdates = false;
//TODO merge getActionTarget and getPageUrlWithParams
public String getActionTarget() {
if (isServingAsAjaxResponse){
return this.getUniqueName();
}
return getPageName();
}
//TODO merge getActionTarget and getPageUrlWithParams
public String getPageUrlWithParams(){ //used for action field in forms
if(isServingAsAjaxResponse){
return ThreadLocalPage.get().getAbsoluteLocation()+"/"+ThreadLocalPage.get().getActionTarget();
}
else{
//this doesn't work with ajax template render from action, since an ajax template needs to submit to a different page than the original request
return getRequestURL();
}
}
protected abstract void renderIncomingSuccessMessages();
protected abstract void renderLogSqlMessage();
public boolean isPostRequest(){
return ThreadLocalServlet.get().isPostRequest;
}
public boolean isNotPostRequest(){
return !ThreadLocalServlet.get().isPostRequest;
}
public boolean isAjaxTemplateRequest(){
return ThreadLocalServlet.get().getPages().get(ThreadLocalServlet.get().getRequestedPage()).isAjaxTemplate();
}
public abstract String getHiddenParams();
public abstract String getUrlQueryParams();
public abstract String getHiddenPostParamsJson();
//public javax.servlet.http.HttpSession session;
public static void cleanupThreadLocals(){
ThreadLocalEmailContext.set(null);
ThreadLocalPage.set(null);
ThreadLocalTemplate.setNull();
}
//templates scope
public static Environment staticEnv = Environment.createSharedEnvironment();
public Environment envGlobalAndSession = Environment.createLocalEnvironment();
//emails
protected static Map<String, Class<?>> emails = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getEmails() {
return emails;
}
public boolean sendEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = renderEmail(name,emailargs,emailenv);
return temp.send();
}
public EmailServlet renderEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = null;
try
{
temp = ((EmailServlet)getEmails().get(name).newInstance());
}
catch(IllegalAccessException iae)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + iae.getMessage());
}
catch(InstantiationException ie)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + ie.getMessage());
}
temp.render(emailargs, emailenv);
return temp;
}
//rendertemplate function
public String renderTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(RENDER_PHASE, name, args, env);
}
//validatetemplate function
public String validateTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(VALIDATE_PHASE, name, args, env);
}
public static final int DATABIND_PHASE = 1;
public static final int VALIDATE_PHASE = 2;
public static final int ACTION_PHASE = 3;
public static final int RENDER_PHASE = 4;
public String executeTemplatePhase(int phase, String name, Object[] args, Environment env){
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
TemplateServlet enclosingTemplateObject = ThreadLocalTemplate.get();
try{
TemplateServlet temp = ((TemplateServlet)env.getTemplate(name).newInstance());
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(name, args, env, null); break;
case RENDER_PHASE: temp.render(name, args, env, null); break;
}
}
catch(Exception oe){
try {
TemplateCall tcall = env.getWithcall(name); //'elements' or requires arg
TemplateServlet temp = ((TemplateServlet)env.getTemplate(tcall.name).newInstance());
String parent = env.getWithcall(name)==null?null:env.getWithcall(name).parentName;
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(parent, tcall.args, env, null); break;
case RENDER_PHASE: temp.render(parent, tcall.args, env, null); break;
}
}
catch(Exception ie){
org.webdsl.logging.Logger.error("EXCEPTION",oe);
org.webdsl.logging.Logger.error("EXCEPTION",ie);
}
}
ThreadLocalTemplate.set(enclosingTemplateObject);
ThreadLocalOut.popChecked(out);
return s.toString();
}
//ref arg
protected static Map<String, Class<?>> refargclasses = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getRefArgClasses() {
return refargclasses;
}
public abstract String getAbsoluteLocation();
public String getXForwardedProto() {
if (request == null) {
return null;
} else {
return request.getHeader("x-forwarded-proto");
}
}
protected TemplateContext templateContext = new TemplateContext();
public String getTemplateContextString() {
return templateContext.getTemplateContextString();
}
public void enterPlaceholderIdContext() {
if( ! "1".equals( placeholderId ) ){
templateContext.enterTemplateContext( placeholderId );
}
}
public void enterTemplateContext(String s) {
templateContext.enterTemplateContext(s);
}
public void leaveTemplateContext() {
templateContext.leaveTemplateContext();
}
public void leaveTemplateContextChecked(String s) {
templateContext.leaveTemplateContextChecked(s);
}
public void clearTemplateContext(){
templateContext.clearTemplateContext();
enterPlaceholderIdContext();
}
public void setTemplateContext(TemplateContext tc){
templateContext = tc;
}
public TemplateContext getTemplateContext(){
return templateContext;
}
// objects scheduled to be checked after action completes, filled by hibernate event listener in hibernate util class
ArrayList<WebDSLEntity> entitiesToBeValidated = new ArrayList<WebDSLEntity>();
boolean allowAddingEntitiesForValidation = true;
public void clearEntitiesToBeValidated(){
entitiesToBeValidated = new ArrayList<WebDSLEntity>();
allowAddingEntitiesForValidation = true;
}
public void addEntityToBeValidated(WebDSLEntity w){
if(allowAddingEntitiesForValidation){
entitiesToBeValidated.add(w);
}
}
public void validateEntities(){
allowAddingEntitiesForValidation = false; //adding entities must be disabled when checking is performed, new entities may be loaded for checks, but do not have to be checked themselves
java.util.Set<WebDSLEntity> set = new java.util.HashSet<WebDSLEntity>(entitiesToBeValidated);
java.util.List<utils.ValidationException> exceptions = new java.util.LinkedList<utils.ValidationException>();
for(WebDSLEntity w : set){
if(w.isChanged()){
try {
// System.out.println("validating: "+ w.get_WebDslEntityType() + ":" + w.getName());
w.validateSave();
//System.out.println("done validating");
} catch(utils.ValidationException ve){
exceptions.add(ve);
} catch(utils.MultipleValidationExceptions ve) {
for(utils.ValidationException vex : ve.getValidationExceptions()){
exceptions.add(vex);
}
}
}
}
if(exceptions.size() > 0){
throw new utils.MultipleValidationExceptions(exceptions);
}
clearEntitiesToBeValidated();
}
protected List<utils.ValidationException> validationExceptions = new java.util.LinkedList<utils.ValidationException>();
public List<utils.ValidationException> getValidationExceptions() {
return validationExceptions;
}
public void addValidationException(String name, String message){
validationExceptions.add(new ValidationException(name,message));
}
public List<utils.ValidationException> getValidationExceptionsByName(String name) {
List<utils.ValidationException> list = new java.util.LinkedList<utils.ValidationException>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v);
}
}
return list;
}
public List<String> getValidationErrorsByName(String name) {
List<String> list = new java.util.ArrayList<String>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v.getErrorMessage());
}
}
return list;
}
public boolean hasExecutedAction = false;
public boolean hasExecutedAction(){ return hasExecutedAction; }
public boolean hasNotExecutedAction(){ return !hasExecutedAction; }
protected boolean abortTransaction = false;
public boolean isTransactionAborted(){ return abortTransaction; }
public void abortTransaction(){ abortTransaction = true; }
public java.util.List<String> ignoreset= new java.util.ArrayList<String>();
public boolean hibernateCacheCleared = false;
protected java.util.List<String> javascripts = new java.util.ArrayList<String>();
protected java.util.List<String> stylesheets = new java.util.ArrayList<String>();
protected java.util.List<String> customHeads = new java.util.ArrayList<String>();
protected java.util.List<String> bodyAttributes = new java.util.ArrayList<String>();
protected java.util.Map<String,String> customHeadNoDuplicates = new java.util.HashMap<String,String>();
public void addJavascriptInclude(String filename) { commandingPage.addJavascriptIncludeInternal( filename ); }
public void addJavascriptIncludeInternal(String filename) {
if(!javascripts.contains(filename))
javascripts.add(filename);
}
public void addStylesheetInclude(String filename) { commandingPage.addStylesheetIncludeInternal( filename ); }
public void addStylesheetIncludeInternal(String filename) {
if(!stylesheets.contains(filename)){
stylesheets.add(filename);
}
}
public void addStylesheetInclude(String filename, String media) { commandingPage.addStylesheetIncludeInternal( filename, media ); }
public void addStylesheetIncludeInternal(String filename, String media) {
String combined = media != null && !media.isEmpty() ? filename + "\" media=\""+ media : filename;
if(!stylesheets.contains(combined)){
stylesheets.add(combined);
}
}
public void addCustomHead(String header) { commandingPage.addCustomHeadInternal(header, header); }
public void addCustomHead(String key, String header) { commandingPage.addCustomHeadInternal(key, header); }
public void addCustomHeadInternal(String key, String header) {
customHeadNoDuplicates.put(key, header);
}
public void addBodyAttribute(String key, String value) { commandingPage.addBodyAttributeInternal(key, value); }
public void addBodyAttributeInternal(String key, String value) {
bodyAttributes.add(" "+key+"=\""+value+"\"");
}
protected abstract void initialize();
protected abstract void conversion();
protected abstract void loadArguments();
public abstract void initVarsAndArgs();
public void clearHibernateCache() {
// used to be only ' hibSession.clear(); ' but that doesn't revert already flushed changes.
// since flushing now happens automatically when querying, this could produce wrong results.
// e.g. output in page with validation errors shows changes that were not persisted to the db.
// see regression test in test/succeed-web/validate-false-and-flush.app
utils.HibernateUtil.getCurrentSession().getTransaction().rollback();
openNewTransactionThroughGetCurrentSession();
ThreadLocalServlet.get().reloadSessionManager(hibernateSession);
initVarsAndArgs();
hibernateCacheCleared = true;
}
protected org.hibernate.Session openNewTransactionThroughGetCurrentSession(){
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
return hibernateSession;
}
protected HttpServletRequest request;
protected ResponseWrapper response;
protected HttpServletResponse httpServletResponse;
protected Object[] args;
// public void setHibSession(Session s) {
// hibSession = s;
// public Session getHibSession() {
// return hibSession;
public HttpServletRequest getRequest() {
return request;
}
private String requestURLCached = null;
private String requestURICached = null;
public String getRequestURL(){
if(requestURLCached == null) {
requestURLCached = AbstractDispatchServletHelper.get().getRequestURL();
}
return requestURLCached;
}
public String getRequestURI(){
if(requestURICached == null) {
requestURICached = AbstractDispatchServletHelper.get().getRequestURI();
}
return requestURICached;
}
public ResponseWrapper getResponse() {
return response;
}
protected boolean validated=true;
/*
* when this is true, it can mean:
* 1 no validation has been performed yet
* 2 some validation has been performed without errors
* 3 all validation has been performed without errors
*/
public boolean isValid() {
return validated;
}
public boolean isNotValid() {
return !validated;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
/*
* complete action regularly but rollback hibernate session
* skips validation of entities at end of action, if validation messages are necessary
* use cancel() instead of rollback()
* can be used to replace templates with ajax without saving, e.g. for validation
*/
protected boolean rollback = false;
public boolean isRollback() {
return rollback;
}
public void setRollback() {
//by setting validated true, the action will succeed
this.setValidated(true);
//the session will be rolled back, to cancel persisting any changes
this.rollback = true;
}
public List<String> failedCaptchaResponses = new ArrayList<String>();
protected boolean inSubmittedForm = false;
public boolean inSubmittedForm() {
return inSubmittedForm;
}
public void setInSubmittedForm(boolean b) {
this.inSubmittedForm = b;
}
// used for runtime check to detect nested forms
protected String inForm = null;
public boolean isInForm() {
return inForm != null;
}
public void enterForm(String t) {
inForm = t;
}
public String getEnclosingForm() {
return inForm;
}
public void leaveForm() {
inForm = null;
}
public void clearParammaps(){
parammap.clear();
parammapvalues.clear();
fileUploads.clear();
}
protected java.util.Map<String, String> parammap;
public java.util.Map<String, String> getParammap() {
return parammap;
}
protected Map<String,List<utils.File>> fileUploads;
public Map<String, List<utils.File>> getFileUploads() {
return fileUploads;
}
public List<utils.File> getFileUploads(String key) {
return fileUploads.get(key);
}
protected Map<String, List<String>> parammapvalues;
public Map<String, List<String>> getParammapvalues() {
return parammapvalues;
}
protected String pageTitle = "";
public String getPageTitle() {
return pageTitle;
}
public void setPageTitle(String pageTitle) {
this.pageTitle = pageTitle;
}
protected String formIdent = "";
public String getFormIdent() {
return formIdent;
}
public void setFormIdent(String fi) {
this.formIdent = fi;
}
protected boolean actionLinkUsed = false;
public boolean isActionLinkUsed() {
return actionLinkUsed;
}
public void setActionLinkUsed(boolean a) {
this.actionLinkUsed = a;
}
protected boolean ajaxRuntimeRequest = false;
public boolean isAjaxRuntimeRequest() {
return ajaxRuntimeRequest;
}
public void setAjaxRuntimeRequest(boolean a) {
ajaxRuntimeRequest = a;
}
protected String redirectUrl = "";
public boolean isRedirected(){
return !"".equals(redirectUrl);
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String a) {
this.redirectUrl = a;
}
// perform the actual redirect
public void redirect(){
try { response.sendRedirect(this.getRedirectUrl()); }
catch (IOException ioe) { org.webdsl.logging.Logger.error("redirect failed", ioe); }
}
protected String mimetype = "text/html; charset=UTF-8";
protected boolean mimetypeChanged = false;
public String getMimetype() {
return mimetype;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
mimetypeChanged = true;
if(!isMarkupLangMimeType.matcher(mimetype).find()){
enableRawoutput();
}
disableTemplateSpans();
}
protected boolean downloadInline = false;
public boolean getDownloadInline() {
return downloadInline;
}
public void enableDownloadInline() {
this.downloadInline = true;
}
protected boolean ajaxActionExecuted = false;
public boolean isAjaxActionExecuted() {
return ajaxActionExecuted;
}
public void enableAjaxActionExecuted() {
ajaxActionExecuted = true;
}
protected boolean rawoutput = false;
public boolean isRawoutput() {
return rawoutput;
}
public void enableRawoutput() {
rawoutput = true;
}
public void disableRawoutput() {
rawoutput = false;
}
protected String[] pageArguments = null;
public void setPageArguments(String[] pa) {
pageArguments = pa;
}
public String[] getPageArguments() {
return pageArguments;
}
protected String httpMethod = null;
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public String getHttpMethod() {
return httpMethod;
}
protected boolean templateSpans = true;
public boolean templateSpans() {
return templateSpans;
}
public void disableTemplateSpans() {
templateSpans = false;
}
protected List<String> reRenderPlaceholders = null;
protected Map<String,String> reRenderPlaceholdersContent = null;
public boolean isReRenderPlaceholders() {
return reRenderPlaceholders != null;
}
public void addReRenderPlaceholders(String placeholder) {
if(reRenderPlaceholders == null){
reRenderPlaceholders = new ArrayList<String>();
reRenderPlaceholdersContent = new HashMap<String,String>();
}
reRenderPlaceholders.add(placeholder);
}
public void addReRenderPlaceholdersContent(String placeholder, String content) {
if(reRenderPlaceholders != null && reRenderPlaceholders.contains(placeholder)){
reRenderPlaceholdersContent.put(placeholder,content);
}
}
protected utils.File download = null;
public void setDownload(utils.File file){
this.download = file;
}
public boolean isDownloadSet(){
return this.download != null;
}
protected void download()
{
/*
Long id = download.getId();
org.hibernate.Session hibSession = HibernateUtilConfigured.getSessionFactory().openSession();
hibSession.beginTransaction();
hibSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
utils.File download = (utils.File)hibSession.load(utils.File.class,id);
*/
try
{
javax.servlet.ServletOutputStream outstream;
outstream = response.getOutputStream();
java.sql.Blob blob = download.getContent();
java.io.InputStream in;
in = blob.getBinaryStream();
response.setContentType(download.getContentType());
if(!downloadInline) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + download.getFileNameForDownload() + "\"");
}
java.io.BufferedOutputStream bufout = new java.io.BufferedOutputStream(outstream);
byte bytes[] = new byte[32768];
int index = in.read(bytes, 0, 32768);
while(index != -1)
{
bufout.write(bytes, 0, index);
index = in.read(bytes, 0, 32768);
}
bufout.flush();
}
catch(java.sql.SQLException ex)
{
org.webdsl.logging.Logger.error("exception in download serve", ex);
}
catch (IOException ex) {
if(ex.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
org.webdsl.logging.Logger.error( "ClientAbortException - " + ex.getMessage() );
} else {
org.webdsl.logging.Logger.error("exception in download serve",ex);
}
}
/*
hibSession.flush();
hibSession.getTransaction().commit();
*/
}
//data validation
public java.util.LinkedList<String> validationContext = new java.util.LinkedList<String>();
public String getValidationContext() {
//System.out.println("using" + validationContext.peek());
return validationContext.peek();
}
public void enterValidationContext(String ident) {
validationContext.add(ident);
//System.out.println("entering" + ident);
}
public void leaveValidationContext() {
/*String s = */ validationContext.removeLast();
//System.out.println("leaving" +s);
}
public boolean inValidationContext() {
return validationContext.size() != 0;
}
//form
public boolean formRequiresMultipartEnc = false;
//formGroup
public String formGroupLeftSize = "150";
//public java.util.Stack<utils.FormGroupContext> formGroupContexts = new java.util.Stack<utils.FormGroupContext>();
public utils.FormGroupContext getFormGroupContext() {
return (utils.FormGroupContext) tableContexts.peek();
}
public void enterFormGroupContext() {
tableContexts.push(new utils.FormGroupContext());
}
public void leaveFormGroupContext() {
tableContexts.pop();
}
public boolean inFormGroupContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.FormGroupContext;
}
public java.util.Stack<String> formGroupContextClosingTags = new java.util.Stack<String>();
public void formGroupContextsCheckEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()){ // ignore defaults when in scope of a double column
if(!temp.isInColumnContext()){ //don't nest left and right
temp.enterColumnContext();
if(temp.isInLeftContext()) {
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else {
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
}
else{
formGroupContextClosingTags.push("none");
}
}
}
}
public void formGroupContextsCheckLeave(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()) {
String tags = formGroupContextClosingTags.pop();
if(tags.equals("left")){
//temp.toRightContext();
temp.leaveColumnContext();
out.print("</div>");
}
else if(tags.equals("right")){
//temp.toLeftContext();
temp.leaveColumnContext();
out.print("</div>");
}
}
}
}
public void formGroupContextsDisplayLeftEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
public void formGroupContextsDisplayRightEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
//label
public String getLabelString() {
return getLabelStringForTemplateContext(ThreadLocalTemplate.get().getUniqueId());
}
public java.util.Stack<String> labelStrings = new java.util.Stack<String>();
public java.util.Set<String> usedPageElementIds = new java.util.HashSet<String>();
public static java.util.Random rand = new java.util.Random();
//avoid duplicate ids; if multiple inputs are in a label, only the first is connected to the label
public String getLabelStringOnce() {
String s = labelStrings.peek();
if(usedPageElementIds.contains(s)){
do{
s += rand.nextInt();
}
while(usedPageElementIds.contains(s));
}
usedPageElementIds.add(s);
return s;
}
public java.util.Map<String,String> usedPageElementIdsTemplateContext = new java.util.HashMap<String,String>();
//subsequent calls from the same defined template (e.g. in different phases) should produce the same id
public String getLabelStringForTemplateContext(String context) {
String labelid = usedPageElementIdsTemplateContext.get(context);
if(labelid == null){
labelid = getLabelStringOnce();
usedPageElementIdsTemplateContext.put(context, labelid);
}
return labelid;
}
public void enterLabelContext(String ident) {
labelStrings.push(ident);
}
public void leaveLabelContext() {
labelStrings.pop();
}
public boolean inLabelContext() {
return !labelStrings.empty();
}
//section
public int sectionDepth = 0;
public int getSectionDepth() {
return sectionDepth;
}
public void enterSectionContext() {
sectionDepth++;
}
public void leaveSectionContext() {
sectionDepth
}
public boolean inSectionContext() {
return sectionDepth > 0;
}
//table
public java.util.Stack<Object> tableContexts = new java.util.Stack<Object>();
public utils.TableContext getTableContext() {
return (utils.TableContext) tableContexts.peek();
}
public void enterTableContext() {
tableContexts.push(new utils.TableContext());
}
public void leaveTableContext() {
tableContexts.pop();
}
public boolean inTableContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.TableContext;
}
public java.util.Stack<String> tableContextClosingTags = new java.util.Stack<String>();
//separate row and column checks, used by label
public void rowContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(!x_temp.isInRowContext()) {
out.print("<tr>");
x_temp.enterRowContext();
tableContextClosingTags.push("</tr>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void rowContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</tr>")){
x_temp.leaveRowContext();
out.print(tags);
}
}
}
public void columnContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(x_temp.isInRowContext() && !x_temp.isInColumnContext()) {
out.print("<td>");
x_temp.enterColumnContext();
tableContextClosingTags.push("</td>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void columnContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</td>")){
x_temp.leaveColumnContext();
out.print(tags);
}
}
}
//session manager
public void reloadSessionManagerFromExistingSessionId(UUID sessionId){
ThreadLocalServlet.get().reloadSessionManagerFromExistingSessionId(hibernateSession, sessionId);
initialize(); //reload session variables
}
//request vars
public HashMap<String, Object> requestScopedVariables = new HashMap<String, Object>();
public void initRequestVars(){
initRequestVars(null);
}
public abstract void initRequestVars(PrintWriter out);
protected long startTime = 0L;
public long getStartTime() {
return startTime;
}
public long getElapsedTime() {
return System.currentTimeMillis() - startTime;
}
public Object getRequestScopedVar(String key){
return commandingPage.requestScopedVariables.get(key);
}
public void addRequestScopedVar(String key, Object val){
if(val != null){
commandingPage.requestScopedVariables.put(key, val);
}
}
public void addRequestScopedVar(String key, WebDSLEntity val){
if(val != null){
val.setRequestVar();
commandingPage.requestScopedVariables.put(key, val);
}
}
// statistics to be shown in log
protected abstract void increaseStatReadOnly();
protected abstract void increaseStatReadOnlyFromCache();
protected abstract void increaseStatUpdate();
protected abstract void increaseStatActionFail();
protected abstract void increaseStatActionReadOnly();
protected abstract void increaseStatActionUpdate();
// register whether entity changes were made, see isChanged property of entities
protected boolean hasWrites = false;
public void setHasWrites(boolean b){
commandingPage.hasWrites = b;
}
protected void updatePageRequestStatistics(){
if(hasNotExecutedAction()){
if(!hasWrites || isRollback()){
if(pageCacheWasUsed){
increaseStatReadOnlyFromCache();
}
else{
increaseStatReadOnly();
}
}
else{
increaseStatUpdate();
}
}
else{
if(isNotValid()){
increaseStatActionFail();
}
else{
if(!hasWrites || isRollback()){
increaseStatActionReadOnly();
}
else{
increaseStatActionUpdate();
}
}
}
}
// Hibernate interceptor hooks (such as beforeTransactionCompletion) catch Throwable but then only log the error, e.g. when db transaction conflict occurs
// this causes the problem that a page might be rendered with data that was not actually committed
// workaround: store the exception in this variable and explicitly rethrow before sending page content to output stream
public Exception exceptionInHibernateInterceptor = null;
public static Environment loadTemplateMap(Class<?> clazz) {
return loadTemplateMap(clazz, null, staticEnv);
}
public static Environment loadTemplateMap(Class<?> clazz, String keyOverwrite, Environment env) {
reflectionLoadClassesHelper(clazz, "loadTemplateMap", new Object[] { keyOverwrite, env });
return env;
}
public static Object[] loadEmailAndTemplateMapArgs = new Object[] { staticEnv, emails };
public static void loadEmailAndTemplateMap(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadEmailAndTemplateMap", loadEmailAndTemplateMapArgs);
}
public static Object[] loadLiftedTemplateMapArgs = new Object[] { staticEnv };
public static void loadLiftedTemplateMap(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadLiftedTemplateMap", loadLiftedTemplateMapArgs);
}
public static Object[] loadRefArgClassesArgs = new Object[] { refargclasses };
public static void loadRefArgClasses(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadRefArgClasses", loadRefArgClassesArgs);
}
public static void reflectionLoadClassesHelper(Class<?> clazz, String method, Object[] args) {
for (java.lang.reflect.Method m : clazz.getMethods()) {
if (method.equals(m.getName())) { // will just skip if not defined, so the code generator does not need to generate empty methods
try {
m.invoke(null, args);
} catch (IllegalAccessException | IllegalArgumentException | java.lang.reflect.InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
} |
package jolie.net;
import java.io.IOException;
import java.io.InputStream;
public class PreBufferedInputStream extends InputStream
{
private static final int INITIAL_BUFFER_SIZE = 10;
private final InputStream istream;
private byte[] buffer = new byte[ INITIAL_BUFFER_SIZE ];
private int writePos = 0;
private int readPos = 0;
private int count = 0;
public PreBufferedInputStream( InputStream istream )
{
this.istream = istream;
}
public synchronized boolean hasCachedData()
{
return count > 0;
}
public synchronized void append( byte b )
throws IOException
{
if ( buffer == null ) {
throw new IOException( "Stream closed" );
}
if ( count < 0 ) {
count = 0;
}
count++;
if ( count >= buffer.length ) { // We need to enlarge the buffer
byte[] newBuffer = new byte[ buffer.length * 2] ;
System.arraycopy( buffer, 0, newBuffer, 0, buffer.length );
buffer = newBuffer;
}
if ( writePos >= buffer.length ) {
writePos = 0;
}
buffer[ writePos++ ] = b;
}
@Override
public synchronized int available()
throws IOException
{
if ( buffer == null ) {
throw new IOException( "Stream closed" );
}
// works only on the underlying stream, not on our cached data
// for which we have hasCachedData()
return istream.available();
}
@Override
public synchronized int read()
throws IOException
{
if ( buffer == null ) {
throw new IOException( "Stream closed" );
}
if ( count < 1 ) { // No bytes to read
return istream.read();
}
count
if ( readPos >= buffer.length ) {
readPos = 0;
}
return buffer[ readPos++ ];
}
@Override
public synchronized int read( byte[] b )
throws IOException
{
return read( b, 0, b.length );
}
@Override
public synchronized int read( byte[] b, int off, int len )
throws IOException
{
if ( buffer == null ) {
throw new IOException( "Stream closed" );
}
int lenFromBuffer = count >= len ? len : count;
if ( lenFromBuffer > 0 ) {
// match implementation of read()
count -= lenFromBuffer;
if ( readPos >= buffer.length ) {
readPos = 0;
}
System.arraycopy( buffer, readPos, b, off, lenFromBuffer );
readPos += lenFromBuffer;
} else {
// count could have been negative, so reset lenFromBuffer to 0
lenFromBuffer = 0;
}
int lenFromStream = 0;
if ( lenFromBuffer != len ) {
lenFromStream = istream.read( b, off+lenFromBuffer, len-lenFromBuffer );
if ( lenFromStream < 0 && lenFromBuffer > 0 ) {
// we return -1 (EOF) only when lenFromBuffer == 0
lenFromStream = 0;
}
}
return lenFromBuffer + lenFromStream;
}
@Override
public synchronized long skip( long n )
throws IOException
{
if ( buffer == null ) {
throw new IOException( "Stream closed" );
}
if ( n < 0 ) {
return 0;
}
count -= n;
if ( count >= 0 ) {
return n;
}
return count + n + istream.skip( -count );
}
@Override
public synchronized void close()
throws IOException
{
buffer = null;
// Java's semantic: a stream closes also its underlying ones
istream.close();
}
} |
package com.opengamma.web.server;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.cometd.Bayeux;
import org.cometd.Client;
import org.cometd.ClientBayeuxListener;
import org.cometd.Message;
import org.cometd.server.BayeuxService;
import org.fudgemsg.FudgeContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.core.change.ChangeEvent;
import com.opengamma.core.change.ChangeListener;
import com.opengamma.core.marketdatasnapshot.impl.ManageableMarketDataSnapshot;
import com.opengamma.core.position.PositionSource;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.marketdata.live.LiveMarketDataSourceRegistry;
import com.opengamma.engine.marketdata.spec.MarketData;
import com.opengamma.engine.marketdata.spec.MarketDataSpecification;
import com.opengamma.engine.view.ViewProcessor;
import com.opengamma.engine.view.client.ViewClient;
import com.opengamma.engine.view.execution.ExecutionFlags;
import com.opengamma.engine.view.execution.ExecutionOptions;
import com.opengamma.engine.view.execution.ViewExecutionFlags;
import com.opengamma.engine.view.execution.ViewExecutionOptions;
import com.opengamma.financial.aggregation.AggregationFunction;
import com.opengamma.financial.view.ManageableViewDefinitionRepository;
import com.opengamma.id.UniqueId;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster;
import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotSearchRequest;
import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotSearchResult;
import com.opengamma.master.portfolio.PortfolioMaster;
import com.opengamma.master.position.PositionMaster;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.web.server.conversion.ConversionMode;
import com.opengamma.web.server.conversion.ResultConverterCache;
/**
* The core of the back-end to the web client, providing the implementation of the Bayeux protocol.
*/
public class LiveResultsService extends BayeuxService implements ClientBayeuxListener {
private static final String DEFAULT_LIVE_MARKET_DATA_NAME = "Automatic";
private static final Logger s_logger = LoggerFactory.getLogger(LiveResultsService.class);
private static final Pattern s_guidPattern = Pattern.compile("(\\{?([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}?)");
private final Map<String, WebView> _clientViews = new HashMap<String, WebView>();
/**
* The executor service used to call web clients back asynchronously.
*/
private final ExecutorService _executorService;
private final ViewProcessor _viewProcessor;
private final MarketDataSnapshotMaster _snapshotMaster;
private final UserPrincipal _user;
private final ResultConverterCache _resultConverterCache;
private final LiveMarketDataSourceRegistry _liveMarketDataSourceRegistry;
private final AggregatedViewDefinitionManager _aggregatedViewDefinitionManager;
public LiveResultsService(final Bayeux bayeux, final ViewProcessor viewProcessor,
final PositionSource positionSource, final SecuritySource securitySource,
final PortfolioMaster userPortfolioMaster, final PositionMaster userPositionMaster,
final ManageableViewDefinitionRepository userViewDefinitionRepository,
final MarketDataSnapshotMaster snapshotMaster, final UserPrincipal user, final ExecutorService executorService,
final FudgeContext fudgeContext, final LiveMarketDataSourceRegistry liveMarketDataSourceRegistry,
final List<AggregationFunction<?>> portfolioAggregators) {
super(bayeux, "processPortfolioRequest");
ArgumentChecker.notNull(bayeux, "bayeux");
ArgumentChecker.notNull(viewProcessor, "viewProcessor");
ArgumentChecker.notNull(positionSource, "positionSource");
ArgumentChecker.notNull(securitySource, "securitySource");
ArgumentChecker.notNull(userPortfolioMaster, "userPortfolioMaster");
ArgumentChecker.notNull(userPositionMaster, "userPositionMaster");
ArgumentChecker.notNull(userViewDefinitionRepository, "userViewDefinitionRepository");
ArgumentChecker.notNull(snapshotMaster, "snapshotMaster");
ArgumentChecker.notNull(user, "user");
ArgumentChecker.notNull(executorService, "executorService");
ArgumentChecker.notNull(liveMarketDataSourceRegistry, "liveMarketDataSourceRegistry");
ArgumentChecker.notNull(portfolioAggregators, "portfolioAggregators");
_viewProcessor = viewProcessor;
_snapshotMaster = snapshotMaster;
_user = user;
_executorService = executorService;
_resultConverterCache = new ResultConverterCache(fudgeContext);
_liveMarketDataSourceRegistry = liveMarketDataSourceRegistry;
_aggregatedViewDefinitionManager = new AggregatedViewDefinitionManager(positionSource, securitySource,
viewProcessor.getViewDefinitionRepository(), userViewDefinitionRepository, userPortfolioMaster, userPositionMaster,
mapPortfolioAggregators(portfolioAggregators));
viewProcessor.getViewDefinitionRepository().changeManager().addChangeListener(new ChangeListener() {
@Override
public void entityChanged(ChangeEvent event) {
sendInitData(false);
}
});
s_logger.info("Subscribing to services");
subscribe("/service/getInitData", "processInitDataRequest");
subscribe("/service/changeView", "processChangeViewRequest");
subscribe("/service/updates", "processUpdateRequest");
subscribe("/service/updates/mode", "processUpdateModeRequest");
subscribe("/service/updates/depgraph", "processDepGraphRequest");
subscribe("/service/currentview/pause", "processPauseRequest");
subscribe("/service/currentview/resume", "processResumeRequest");
getBayeux().addListener(this);
s_logger.info("Finished subscribing to services");
}
private Map<String, AggregationFunction<?>> mapPortfolioAggregators(List<AggregationFunction<?>> portfolioAggregators) {
Map<String, AggregationFunction<?>> result = new HashMap<String, AggregationFunction<?>>();
for (AggregationFunction<?> portfolioAggregator : portfolioAggregators) {
result.put(portfolioAggregator.getName(), portfolioAggregator);
}
return result;
}
@Override
public void clientAdded(Client client) {
s_logger.debug("Client " + client.getId() + " connected");
}
@Override
public void clientRemoved(Client client) {
// Tidy up
s_logger.debug("Client " + client.getId() + " disconnected");
if (_clientViews.containsKey(client.getId())) {
WebView view = _clientViews.remove(client.getId());
shutDownWebView(view);
}
}
public WebView getClientView(String clientId) {
synchronized (_clientViews) {
return _clientViews.get(clientId);
}
}
private void initializeClientView(final Client remote, final UniqueId baseViewDefinitionId, final String aggregatorName, final ViewExecutionOptions executionOptions, final UserPrincipal user) {
synchronized (_clientViews) {
WebView webView = _clientViews.get(remote.getId());
if (webView != null) {
if (webView.matches(baseViewDefinitionId, aggregatorName, executionOptions)) {
// Already initialized
webView.reconnected();
return;
}
// Existing view is different - client is switching views
shutDownWebView(webView);
_clientViews.remove(remote.getId());
}
ViewClient viewClient = getViewProcessor().createViewClient(user);
try {
UniqueId viewDefinitionId = _aggregatedViewDefinitionManager.getViewDefinitionId(baseViewDefinitionId, aggregatorName);
webView = new WebView(getClient(), remote, viewClient, baseViewDefinitionId, aggregatorName, viewDefinitionId,
executionOptions, user, getExecutorService(), getResultConverterCache());
} catch (Exception e) {
_aggregatedViewDefinitionManager.releaseViewDefinition(baseViewDefinitionId, aggregatorName);
viewClient.shutdown();
throw new OpenGammaRuntimeException("Error attaching client to view definition '" + baseViewDefinitionId + "'", e);
}
_clientViews.put(remote.getId(), webView);
}
}
private void shutDownWebView(WebView webView) {
webView.shutdown();
_aggregatedViewDefinitionManager.releaseViewDefinition(webView.getBaseViewDefinitionId(), webView.getAggregatorName());
}
private UserPrincipal getUser(Client remote) {
return _user;
}
private ExecutorService getExecutorService() {
return _executorService;
}
private ViewProcessor getViewProcessor() {
return _viewProcessor;
}
private ResultConverterCache getResultConverterCache() {
return _resultConverterCache;
}
public void processUpdateRequest(Client remote, Message message) {
s_logger.info("Received portfolio data request from {}, getting client view...", remote);
WebView webView = getClientView(remote.getId());
if (webView == null) {
// Disconnected client has come back to life
return;
}
webView.triggerUpdate(message);
}
@SuppressWarnings("unchecked")
public void processUpdateModeRequest(Client remote, Message message) {
WebView webView = getClientView(remote.getId());
if (webView == null) {
return;
}
Map<String, Object> dataMap = (Map<String, Object>) message.getData();
String gridName = (String) dataMap.get("gridName");
long jsRowId = (Long) dataMap.get("rowId");
long jsColId = (Long) dataMap.get("colId");
ConversionMode mode = ConversionMode.valueOf((String) dataMap.get("mode"));
WebViewGrid grid = webView.getGridByName(gridName);
if (grid == null) {
s_logger.warn("Request to change update mode for cell in unknown grid '{}'", gridName);
}
grid.setConversionMode(WebGridCell.of((int) jsRowId, (int) jsColId), mode);
}
@SuppressWarnings("unchecked")
public void processDepGraphRequest(Client remote, Message message) {
WebView webView = getClientView(remote.getId());
if (webView == null) {
return;
}
Map<String, Object> dataMap = (Map<String, Object>) message.getData();
String gridName = (String) dataMap.get("gridName");
long jsRowId = (Long) dataMap.get("rowId");
long jsColId = (Long) dataMap.get("colId");
boolean includeDepGraph = (Boolean) dataMap.get("includeDepGraph");
webView.setIncludeDepGraph(gridName, WebGridCell.of((int) jsRowId, (int) jsColId), includeDepGraph);
}
public void processInitDataRequest(Client remote, Message message) {
s_logger.info("processInitDataRequest");
sendInitData(true);
}
private void sendInitData(boolean includeSnapshots) {
Map<String, Object> reply = new HashMap<String, Object>();
Object availableViewDefinitions = getViewDefinitions();
reply.put("viewDefinitions", availableViewDefinitions);
List<String> aggregatorNames = getAggregatorNames();
reply.put("aggregatorNames", aggregatorNames);
if (includeSnapshots) {
List<String> liveMarketDataSourceDetails = getLiveMarketDataSourceDetails();
reply.put("liveSources", liveMarketDataSourceDetails);
Map<String, Map<String, String>> snapshotDetails = getSnapshotDetails();
reply.put("snapshots", snapshotDetails);
}
getBayeux().getChannel("/initData", true).publish(getClient(), reply, null);
}
private List<Map<String, String>> getViewDefinitions() {
List<Map<String, String>> result = new ArrayList<Map<String, String>>();
Map<UniqueId, String> availableViewEntries = _viewProcessor.getViewDefinitionRepository().getDefinitionEntries();
s_logger.debug("Available view entries: " + availableViewEntries);
for (Map.Entry<UniqueId, String> entry : availableViewEntries.entrySet()) {
if (s_guidPattern.matcher(entry.getValue()).find()) {
s_logger.debug("Ignoring view definition which appears to have an auto-generated name: {}", entry.getValue());
continue;
}
Map<String, String> resultEntry = new HashMap<String, String>();
resultEntry.put("id", entry.getKey().toString());
resultEntry.put("name", entry.getValue());
result.add(resultEntry);
}
Collections.sort(result, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
return o1.get("name").compareTo(o2.get("name"));
}
});
return result;
}
private List<String> getAggregatorNames() {
List<String> result = new ArrayList<String>();
result.addAll(_aggregatedViewDefinitionManager.getAggregatorNames());
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
return result;
}
private List<String> getLiveMarketDataSourceDetails() {
Collection<String> allDataSources = _liveMarketDataSourceRegistry.getDataSources();
List<String> filteredDataSources = new ArrayList<String>();
filteredDataSources.add(DEFAULT_LIVE_MARKET_DATA_NAME);
for (String dataSource : allDataSources) {
if (StringUtils.isBlank(dataSource)) {
continue;
}
filteredDataSources.add(dataSource);
}
return filteredDataSources;
}
private Map<String, Map<String, String>> getSnapshotDetails() {
MarketDataSnapshotSearchRequest snapshotSearchRequest = new MarketDataSnapshotSearchRequest();
snapshotSearchRequest.setIncludeData(false);
MarketDataSnapshotSearchResult snapshotSearchResult = _snapshotMaster.search(snapshotSearchRequest);
List<ManageableMarketDataSnapshot> snapshots = snapshotSearchResult.getMarketDataSnapshots();
Map<String, Map<String, String>> snapshotsByBasisView = new HashMap<String, Map<String, String>>();
for (ManageableMarketDataSnapshot snapshot : snapshots) {
if (snapshot.getUniqueId() == null) {
s_logger.warn("Ignoring snapshot with null unique identifier {}", snapshot.getName());
continue;
}
if (StringUtils.isBlank(snapshot.getName())) {
s_logger.warn("Ignoring snapshot {} with no name", snapshot.getUniqueId());
continue;
}
if (s_guidPattern.matcher(snapshot.getName()).find()) {
s_logger.debug("Ignoring snapshot which appears to have an auto-generated name: {}", snapshot.getName());
continue;
}
String basisViewName = snapshot.getBasisViewName() != null ? snapshot.getBasisViewName() : "unknown";
Map<String, String> snapshotsForBasisView = snapshotsByBasisView.get(basisViewName);
if (snapshotsForBasisView == null) {
snapshotsForBasisView = new HashMap<String, String>();
snapshotsByBasisView.put(basisViewName, snapshotsForBasisView);
}
snapshotsForBasisView.put(snapshot.getUniqueId().toString(), snapshot.getName());
}
return snapshotsByBasisView;
}
@SuppressWarnings("unchecked")
public void processChangeViewRequest(Client remote, Message message) {
try {
Map<String, Object> data = (Map<String, Object>) message.getData();
String viewIdString = (String) data.get("viewId");
UniqueId baseViewDefinitionId;
try {
baseViewDefinitionId = UniqueId.parse(viewIdString);
} catch (IllegalArgumentException e) {
sendChangeViewError(remote, "Invalid view definition identifier format: '" + viewIdString);
return;
}
if (!validateViewDefinitionId(baseViewDefinitionId)) {
sendChangeViewError(remote, "No view definition with identifier " + baseViewDefinitionId + " could be found");
return;
}
String aggregatorName = (String) data.get("aggregatorName");
String marketDataType = (String) data.get("marketDataType");
MarketDataSpecification marketDataSpec;
EnumSet<ViewExecutionFlags> flags;
if ("snapshot".equals(marketDataType)) {
String snapshotIdString = (String) data.get("snapshotId");
if (StringUtils.isBlank(snapshotIdString)) {
sendChangeViewError(remote, "Unknown snapshot");
return;
}
UniqueId snapshotId = UniqueId.parse(snapshotIdString);
marketDataSpec = MarketData.user(snapshotId.toLatest());
flags = ExecutionFlags.none().triggerOnMarketData().get();
} else if ("live".equals(marketDataType)) {
String liveMarketDataProvider = (String) data.get("provider");
if (StringUtils.isBlank(liveMarketDataProvider) || DEFAULT_LIVE_MARKET_DATA_NAME.equals(liveMarketDataProvider)) {
marketDataSpec = MarketData.live();
} else {
marketDataSpec = MarketData.live(liveMarketDataProvider);
}
flags = ExecutionFlags.triggersEnabled().get();
} else {
throw new OpenGammaRuntimeException("Unknown market data type: " + marketDataType);
}
ViewExecutionOptions executionOptions = ExecutionOptions.infinite(marketDataSpec, flags);
s_logger.info("Initializing view '{}', aggregated by '{}' with execution options '{}' for client '{}'", new Object[] {baseViewDefinitionId, aggregatorName, executionOptions, remote});
initializeClientView(remote, baseViewDefinitionId, aggregatorName, executionOptions, getUser(remote));
} catch (Exception e) {
sendChangeViewError(remote, "Unexpected error with message: " + e.getMessage());
}
}
private void sendChangeViewError(Client remote, String errorMessage) {
s_logger.info("Notifying client of error changing view: " + errorMessage);
Map<String, String> reply = new HashMap<String, String>();
reply.put("isError", "true");
reply.put("message", "Unable to change view. " + errorMessage + ".");
remote.deliver(getClient(), "/changeView", reply, null);
}
private boolean validateViewDefinitionId(UniqueId viewDefinitionId) {
try {
return _viewProcessor.getViewDefinitionRepository().getDefinition(viewDefinitionId) != null;
} catch (Exception e) {
s_logger.warn("Error validating view definition ID " + viewDefinitionId, e);
return false;
}
}
public void processPauseRequest(Client remote, Message message) {
WebView webView = getClientView(remote.getId());
if (webView == null) {
return;
}
webView.pause();
}
public void processResumeRequest(Client remote, Message message) {
WebView webView = getClientView(remote.getId());
if (webView == null) {
return;
}
webView.resume();
}
} |
package org.fidonet.jftn;
import org.fidonet.config.JFtnConfig;
import org.fidonet.config.ParseConfigException;
import org.fidonet.jftn.engine.script.JFtnShare;
import org.fidonet.jftn.engine.script.ScriptManager;
import org.fidonet.jftn.share.Command;
import org.fidonet.jftn.share.CommandCollection;
import org.fidonet.jftn.share.CommandInterpreter;
import org.fidonet.jftn.share.HookInterpreter;
import org.fidonet.jftn.tosser.Tosser;
import org.fidonet.logger.ILogger;
import org.fidonet.logger.LoggerFactory;
public class JToss {
private static ILogger logger = LoggerFactory.getLogger(JToss.class.getName());
private static void Help() {
System.out.println("java ftn usage:");
System.out.println("jftn <action>:");
System.out.println(" help - show this help");
System.out.println(" toss - toss incoming echomail");
}
public static void main(String[] args) throws Exception {
logger.debug("Starting JToss...");
final long starttime = System.currentTimeMillis();
JFtnConfig config = new JFtnConfig();
try {
config.load("jftn.conf");
} catch (ParseConfigException e) {
logger.error("Error during parsing config.", e);
System.exit(1);
}
// Loading Script engine
ScriptManager scriptManager = new ScriptManager("scripts");
HookInterpreter hooks = new HookInterpreter();
CommandCollection commands = new CommandCollection();
CommandInterpreter commandInterpreter = new CommandInterpreter(commands);
JFtnShare shareObject = new JFtnShare(scriptManager, hooks, commandInterpreter);
shareObject.setConfig(config);
scriptManager.addScriptVar("jftn", shareObject);
// Loading all scripts
scriptManager.reloadScripts();
if (args.length == 0) {
System.out.println("Error: No action in commandline.");
Help();
} else {
String commandString = args[0];
Command command = commands.findCommandByName(commandString);
if (command != null) {
logger.info("Executing " + commandString + " command...");
command.execute(args);
} else {
logger.debug("Trying to OOTB command...");
if (args[0].equalsIgnoreCase("toss")) {
Tosser tosser = new Tosser(config);
tosser.runFast(config.getValue("inbound"));
} else if (args[0].equalsIgnoreCase("help")) {
Help();
} else {
System.out.println("Error: Unknown commandline argument.");
Help();
}
}
}
logger.debug("Finish working (time: " + (System.currentTimeMillis() - starttime) / 1000.0 + " sec)");
}
} |
// $Id: JORARepository.java,v 1.2 2004/02/25 13:16:05 mdb Exp $
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc;
import java.sql.*;
import com.samskivert.io.PersistenceException;
import com.samskivert.jdbc.jora.*;
/**
* The JORA repository simplifies the process of building persistence
* services that make use of the JORA object relational mapping package.
*
* @see com.samskivert.jdbc.jora.Session
*/
public abstract class JORARepository extends SimpleRepository
{
/**
* Creates and initializes a JORA repository which will access the
* database identified by the supplied database identifier.
*
* @param provider the connection provider which will be used to
* obtain our database connection.
* @param dbident the identifier of the database that will be accessed
* by this repository.
*/
public JORARepository (ConnectionProvider provider, String dbident)
{
super(provider, dbident);
// create our JORA session
_session = new Session((Connection)null);
// create our tables
createTables(_session);
}
/**
* Updates the specified field in the supplied object which must
* correspond to the supplied table.
*/
protected void updateField (
final Table table, final Object object, String field)
throws PersistenceException
{
final FieldMask mask = table.getFieldMask();
mask.setModified(field);
execute(new Operation() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
table.update(object, mask);
return null;
}
});
}
/**
* After the database session is begun, this function will be called
* to give the repository implementation the opportunity to create its
* table objects.
*
* @param session the session instance to use when creating your table
* instances.
*/
protected abstract void createTables (Session session);
protected void gotConnection (Connection conn)
{
// let our session know about this connection
_session.setConnection(conn);
}
protected Session _session;
} |
package de.nrw.hbz.regal.api.helper;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigInteger;
import java.net.URL;
import java.util.Date;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.openrdf.model.BNode;
import org.openrdf.model.Literal;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.BasicWriterSettings;
import org.openrdf.rio.helpers.JSONLDMode;
import org.openrdf.rio.helpers.JSONLDSettings;
import org.openrdf.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stringtemplate.v4.ST;
import de.nrw.hbz.regal.datatypes.Node;
/**
* @author Jan Schnasse schnasse@hbz-nrw.de
*
*/
@SuppressWarnings("serial")
public class OaiOreMaker {
final static Logger logger = LoggerFactory.getLogger(OaiOreMaker.class);
String server = null;
String uriPrefix = null;
Node node = null;
String dcNamespace = "http://purl.org/dc/elements/1.1/";
String dctermsNamespace = "http://purl.org/dc/terms/";
String foafNamespace = "http://xmlns.com/foaf/0.1/";
String oreNamespace = "http:
String rdfNamespace = " http://www.w3.org/1999/02/22-rdf-syntax-ns
String rdfsNamespace = "http://www.w3.org/2000/01/rdf-schema
String regalNamespace = "http://hbz-nrw.de/regal
String fpNamespace = "http://downlode.org/Code/RDF/File_Properties/schema
String wnNamespace = "http://xmlns.com/wordnet/1.6/";
RepositoryConnection con = null;
@SuppressWarnings("javadoc")
public OaiOreMaker(Node node, String server, String uriPrefix) {
this.server = server;
this.uriPrefix = uriPrefix;
this.node = node;
try {
con = createRdfRepository();
} catch (RepositoryException e) {
throw new CreateRepositoryException(e);
}
}
/**
* @param format
* application/rdf+xml text/plain application/json
* @param parents
* all parents of the pid
* @param children
* all children of the pid
* @return a oai_ore resource map
*/
public String getReM(String format, List<String> parents,
List<String> children) {
String result = null;
addDescriptiveData();
addStructuralData(parents, children);
result = write(format);
closeRdfRepository();
return result;
}
private void addDescriptiveData() {
try {
URL metadata = new URL(server + "/fedora/objects/" + node.getPID()
+ "/datastreams/metadata/content");
InputStream in = metadata.openStream();
con.add(in, node.getPID(), RDFFormat.N3);
} catch (Exception e) {
throw new AddDescriptiveDataException(e);
}
}
private String write(String format) {
try {
if (format.compareTo("text/html") == 0) {
return getHtml();
}
StringWriter out = new StringWriter();
RDFWriter writer = null;
String result = null;
writer = configureWriter(format, out, writer);
return write(out, writer, result);
} catch (Exception e) {
throw new WriteRdfException(e);
}
}
private String write(StringWriter out, RDFWriter writer, String result)
throws RepositoryException {
try {
writer.startRDF();
RepositoryResult<Statement> statements = con.getStatements(null,
null, null, false);
while (statements.hasNext()) {
Statement statement = statements.next();
writer.handleStatement(statement);
}
writer.endRDF();
result = out.toString();
} catch (RDFHandlerException e) {
logger.error(e.getMessage());
}
return result;
}
private RDFWriter configureWriter(String format, StringWriter out,
RDFWriter writer) {
if (format.equals("application/rdf+xml")) {
writer = Rio.createWriter(RDFFormat.RDFXML, out);
} else if (format.compareTo("text/plain") == 0) {
writer = Rio.createWriter(RDFFormat.NTRIPLES, out);
} else if (format.compareTo("application/json") == 0) {
writer = Rio.createWriter(RDFFormat.JSONLD, out);
writer.getWriterConfig().set(JSONLDSettings.JSONLD_MODE,
JSONLDMode.EXPAND);
writer.getWriterConfig()
.set(BasicWriterSettings.PRETTY_PRINT, true);
} else {
throw new HttpArchiveException(406, format + " is not supported");
}
return writer;
}
private String getHtml() throws RDFHandlerException, RepositoryException {
StringWriter out = new StringWriter();
RDFWriter writer = null;
String result = null;
writer = Rio.createWriter(RDFFormat.NTRIPLES, out);
writer.startRDF();
RepositoryResult<Statement> statements = con.getStatements(null, null,
null, false);
while (statements.hasNext()) {
Statement statement = statements.next();
writer.handleStatement(statement);
}
writer.endRDF();
result = out.toString();
return getHtml(result, node.getMimeType(), node.getPID());
}
private RepositoryConnection createRdfRepository()
throws RepositoryException {
RepositoryConnection con = null;
SailRepository myRepository = new SailRepository(new MemoryStore());
myRepository.initialize();
con = myRepository.getConnection();
return con;
}
private void closeRdfRepository() {
try {
if (con != null)
con.close();
} catch (Exception e) {
throw new CreateRepositoryException(e);
}
}
private void addStructuralData(List<String> parents, List<String> children) {
try {
String pid = node.getPID();
Date lastModified = node.getLastModified();
// Graph remGraph = new org.openrdf.model.impl.GraphImpl();
ValueFactory f = con.getValueFactory();
// Things
URI aggregation = f.createURI(/* uriPrefix + */pid);
URI rem = f.createURI(/* uriPrefix + */pid + ".rdf");
URI regal = f.createURI("https://github.com/edoweb/regal/");
URI data = f.createURI(aggregation.stringValue() + "/data");
URI fulltext = f.createURI(aggregation.stringValue() + "/fulltext");
Literal cType = f.createLiteral(node.getContentType());
Literal lastTimeModified = f.createLiteral(lastModified);
String mime = node.getMimeType();
String label = node.getFileLabel();
String fileSize = null;
BigInteger fs = node.getFileSize();
if (fs != null)
fileSize = fs.toString();
String fileChecksum = node.getChecksum();
// Predicates
// ore
URI describes = f.createURI(oreNamespace, "describes");
URI isDescribedBy = f.createURI(oreNamespace, "isDescribedBy");
URI aggregates = f.createURI(oreNamespace, "aggregates");
URI isAggregatedBy = f.createURI(oreNamespace, "isAggregatedBy");
URI similarTo = f.createURI(oreNamespace, "similarTo");
URI isPartOf = f.createURI(dctermsNamespace, "isPartOf");
URI hasPart = f.createURI(dctermsNamespace, "hasPart");
URI modified = f.createURI(dctermsNamespace, "modified");
URI creator = f.createURI(dctermsNamespace, "creator");
URI dcFormat = f.createURI(dctermsNamespace, "format");
URI dcHasFormat = f.createURI(dctermsNamespace, "hasFormat");
// rdfs
URI rdfsLabel = f.createURI(rdfsNamespace, "label");
URI rdfsType = f.createURI(rdfsNamespace, "type");
// regal
URI contentType = f.createURI(regalNamespace, "contentType");
URI hasData = f.createURI(regalNamespace, "hasData");
// FileProperties
URI fpSize = f.createURI(fpNamespace, "size");
BNode theChecksumBlankNode = f.createBNode();
URI fpChecksum = f.createURI(fpNamespace, "checksum");
URI fpChecksumType = f.createURI(fpNamespace, "Checksum");
URI fpChecksumGenerator = f.createURI(fpNamespace, "generator");
URI fpChecksumAlgo = f.createURI(wnNamespace, "Algorithm");
URI md5Uri = f.createURI("http://en.wikipedia.org/wiki/MD5");
URI fpChecksumValue = f.createURI(fpNamespace, "checksumValue");
// Statements
if (mime != null && !mime.isEmpty()) {
Literal dataMime = f.createLiteral(mime);
con.add(data, dcFormat, dataMime);
con.add(aggregation, aggregates, data);
con.add(aggregation, hasData, data);
if (dataMime.toString().compareTo("application/pdf") == 0) {
con.add(aggregation, aggregates, fulltext);
con.add(data, dcHasFormat, fulltext);
}
}
if (fileSize != null && !fileSize.isEmpty()) {
Literal dataSize = f.createLiteral(fileSize);
con.add(data, fpSize, dataSize);
}
if (fileChecksum != null && !fileChecksum.isEmpty()) {
Literal dataChecksum = f.createLiteral(fileChecksum);
con.add(theChecksumBlankNode, rdfsType, fpChecksumType);
con.add(theChecksumBlankNode, fpChecksumGenerator, md5Uri);
con.add(md5Uri, rdfsType, fpChecksumAlgo);
con.add(theChecksumBlankNode, fpChecksumValue, dataChecksum);
con.add(data, fpChecksum, theChecksumBlankNode);
}
if (label != null && !label.isEmpty()) {
Literal labelLiteral = f.createLiteral(label);
con.add(data, rdfsLabel, labelLiteral);
}
String str = getOriginalUri(pid);
if (str != null && !str.isEmpty()) {
URI originalObject = f.createURI(str);
con.add(aggregation, similarTo, originalObject);
}
URI fedoraObject = f.createURI(server + "/fedora/objects/" + pid);
con.add(rem, describes, aggregation);
con.add(rem, modified, lastTimeModified);
con.add(rem, creator, regal);
con.add(aggregation, isDescribedBy, rem);
con.add(aggregation, similarTo, fedoraObject);
con.add(aggregation, contentType, cType);
for (String relPid : parents) {
URI relUrl = f.createURI(relPid);
con.add(aggregation, isAggregatedBy, relUrl);
con.add(aggregation, isPartOf, relUrl);
}
for (String relPid : children) {
URI relUrl = f.createURI(relPid);
con.add(aggregation, aggregates, relUrl);
con.add(aggregation, hasPart, relUrl);
}
} catch (Exception e) {
throw new AddStructuralDataException(e);
}
}
private String getOriginalUri(String pid) {
String pidWithoutNamespace = pid.substring(pid.indexOf(':') + 1);
String originalUri = null;
if (pid.contains("edoweb") || pid.contains("ellinet")) {
if (pid.length() <= 17) {
originalUri = "http://klio.hbz-nrw.de:1801/webclient/MetadataManager?pid="
+ pidWithoutNamespace;
}
}
if (pid.contains("dipp")) {
originalUri = "http://193.30.112.23:9280/fedora/get/" + pid
+ "/QDC";
}
if (pid.contains("ubm")) {
originalUri = "http://ubm.opus.hbz-nrw.de/frontdoor.php?source_opus="
+ pidWithoutNamespace + "&la=de";
}
if (pid.contains("fhdd")) {
originalUri = "http://fhdd.opus.hbz-nrw.de/frontdoor.php?source_opus="
+ pidWithoutNamespace + "&la=de";
}
if (pid.contains("kola")) {
originalUri = "http://kola.opus.hbz-nrw.de/frontdoor.php?source_opus="
+ pidWithoutNamespace + "&la=de";
}
return originalUri;
}
private String getHtml(String rdf, String mime, String pid) {
String result = "";
RepositoryConnection con = null;
try {
java.net.URL fileLocation = Thread.currentThread()
.getContextClassLoader().getResource("html.html");
StringWriter writer = new StringWriter();
IOUtils.copy(fileLocation.openStream(), writer);
String data = writer.toString();
ST st = new ST(data, '$', '$');
st.add("serverRoot", server);
if (mime != null) {
String dataLink = uriPrefix + pid + "/data";
String logoLink = "";
if (mime.compareTo("application/pdf") == 0) {
logoLink = "pdflogo.svg";
} else if (mime.compareTo("application/zip") == 0) {
logoLink = "zip.png";
} else {
logoLink = "data.png";
}
st.add("data", "<tr><td class=\"textlink\"><a href=\""
+ dataLink + "\"><img src=\"/img/" + logoLink
+ "\" width=\"100\" /></a></td></tr>");
} else {
st.add("data", "");
}
SailRepository myRepository = new SailRepository(new MemoryStore());
myRepository.initialize();
con = myRepository.getConnection();
String baseURI = "";
try {
con.add(new StringReader(rdf), baseURI, RDFFormat.N3);
RepositoryResult<Statement> statements = con.getStatements(
null, null, null, false);
while (statements.hasNext()) {
Statement statement = statements.next();
String subject = statement.getSubject().stringValue();
String predicate = statement.getPredicate().stringValue();
String object = statement.getObject().stringValue();
MyTriple triple = new MyTriple(subject, predicate, object,
pid);
if (predicate.compareTo("http://purl.org/dc/terms/hasPart") == 0
|| predicate
.compareTo("http://purl.org/dc/terms/isPartOf") == 0) {
st.add("relations", triple);
} else if (predicate
.compareTo("http:
|| predicate
.compareTo("http:
{
// do nothing!;
} else if (predicate
.compareTo("http:
st.add("links", triple);
} else {
st.add("statements", triple);
}
}
result = st.render();
} catch (Exception e) {
logger.warn(e.getMessage());
}
} catch (RepositoryException e) {
logger.error(e.getMessage());
}
catch (IOException e) {
logger.error(e.getMessage());
}
finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
}
return result;
}
private class MyTriple {
String subject;
String predicate;
String object;
String pid;
public MyTriple(String subject, String predicate, String object,
String pid) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.pid = pid;
}
public String toString() {
String subjectLink = null;
String objectLink = null;
String namespace = pid.substring(0, pid.indexOf(":"));
if (subject.startsWith(pid)) {
subjectLink = uriPrefix + subject;
} else {
subjectLink = subject;
}
if (object.startsWith(namespace)) {
objectLink = uriPrefix + object;
} else if (object.startsWith("http")) {
objectLink = object;
}
if (predicate.compareTo("http://hbz-nrw.de/regal#contentType") == 0) {
objectLink = "/resource?type=" + object;
}
if (objectLink != null) {
return "<tr><td><a href=\"" + subjectLink + "\">" + subject
+ "</a></td><td><a href=\"" + predicate + "\">"
+ predicate + "</a></td><td about=\"" + subject
+ "\"><a property=\"" + predicate + "\" href=\""
+ objectLink + "\">" + object + "</a></td></tr>";
} else {
return "<tr><td><a href=\"" + subjectLink + "\">" + subject
+ "</a></td><td><a href=\"" + predicate + "\">"
+ predicate + "</a></td><td about=\"" + subject + "\">"
+ object + "</td></tr>";
}
}
}
private class CreateRepositoryException extends RuntimeException {
public CreateRepositoryException(Throwable e) {
super(e);
}
}
private class AddDescriptiveDataException extends RuntimeException {
public AddDescriptiveDataException(Throwable e) {
super(e);
}
}
private class AddStructuralDataException extends RuntimeException {
public AddStructuralDataException(Throwable e) {
super(e);
}
}
private class WriteRdfException extends RuntimeException {
public WriteRdfException(Throwable e) {
super(e);
}
}
} |
package es.deusto.weblab.client;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.ScriptElement;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import es.deusto.weblab.client.configuration.ConfigurationManager;
import es.deusto.weblab.client.configuration.IConfigurationLoadedCallback;
import es.deusto.weblab.client.ui.widgets.WlWaitingLabel;
public abstract class WebLabClient implements EntryPoint {
public static final String BASE_LOCATION = "base.location";
public static final String DEFAULT_BASE_LOCATION = "";
public static String baseLocation;
public static boolean IS_MOBILE = false;
public static final int MAX_FACEBOOK_WIDTH = 735;
private static final String MAIN_SLOT = "weblab_slot";
private static final String SCRIPT_CONFIG_FILE = GWT.getModuleBaseURL() + "configuration.js";
public static final String MOBILE_URL_PARAM = "mobile";
private static final String LOCALE_URL_PARAM = "locale";
public static final String LOCALE_COOKIE = "weblabdeusto.locale";
public static final String MOBILE_COOKIE = "weblabdeusto.mobile";
public static final String HOST_ENTITY_DEFAULT_LANGUAGE = "host.entity.default.language";
public static final String DEFAULT_HOST_ENTITY_DEFAULT_LANGUAGE = "en";
public static final String THEME_PROPERTY = "theme";
public static final String DEFAULT_THEME = "deusto";
private static final String GOOGLE_ANALYTICS_TRACKING_CODE = "google.analytics.tracking.code";
// These are the minimum width and height to choose the standard version over the
// mobile one automatically. The choice can nonetheless be forced upon the client
// by explicitly specifying the "mobile" GET variable.
private static final int MIN_NON_MOBILE_WIDTH = 480;
private static final int MIN_NON_MOBILE_HEIGHT = 350;
private static final int MIN_NON_MOBILE_AREA = 350 * 300;
protected static final String INDEX_ADMIN_HTML = "index-admin.html";
public ConfigurationManager configurationManager;
private boolean languageDecisionPending = false;
public void putWidget(Widget widget){
while(RootPanel.get(WebLabClient.MAIN_SLOT).getWidgetCount() > 0)
RootPanel.get(WebLabClient.MAIN_SLOT).remove(0);
RootPanel.get(WebLabClient.MAIN_SLOT).add(widget);
}
public void showError(String message){
final Label errorMessage = new Label(message);
this.putWidget(errorMessage);
}
private boolean localeConfigured(){
return Window.Location.getParameter(WebLabClient.LOCALE_URL_PARAM) != null;
}
/**
* Check whether we must display the mobile or the standard version. If the "mobile" GET var is
* specified, we will comply. If it is not, we will display the standard version if the browser
* resolution of the user is large enough, and the mobile one otherwise.
*
* @return True if we should display the mobile version, false otherwise
*/
boolean isMobile(){
// If it was explicitly specified through the GET var, do what it says and set a cookie.
final String urlSaysIsMobile = Window.Location.getParameter(WebLabClient.MOBILE_URL_PARAM);
if(urlSaysIsMobile != null) {
if(urlSaysIsMobile.toLowerCase().equals("yes") ||
urlSaysIsMobile.toLowerCase().equals("true")) {
Cookies.setCookie(MOBILE_COOKIE, "true");
return true;
} else if(urlSaysIsMobile.toLowerCase().equals("no") ||
urlSaysIsMobile.toLowerCase().equals("false")) {
Cookies.setCookie(MOBILE_COOKIE, "false");
return false;
} else {
// We are receiving an unexpected value for the mobile parameter.
// We will not make assumptions about this parameter, and we will
// delete the mobile cookie.
Cookies.removeCookie(MOBILE_COOKIE);
}
}
// It was not specified. Now, we will first try to find a cookie that tells us what to do.
final String cookieSaysIsMobile = Cookies.getCookie(MOBILE_COOKIE);
if(cookieSaysIsMobile != null)
return cookieSaysIsMobile.equals("true");
// It was not specified, and we did not find a cookie, so we will choose the best option
// depending on the user's browser resolution.
final int width = Window.getClientWidth();
final int height = Window.getClientHeight();
final int area = width * height;
// We check everything > 0 just in case there are issues with frames (such as facebook iframes)
if ((width > 0 && width <= MIN_NON_MOBILE_WIDTH) || (height > 0 && height <= MIN_NON_MOBILE_HEIGHT) || (area > 0 && area <= MIN_NON_MOBILE_AREA))
return true;
return false;
}
private void selectLanguage(){
if(localeConfigured())
return;
final String weblabLocaleCookie = Cookies.getCookie(WebLabClient.LOCALE_COOKIE);
if(weblabLocaleCookie != null){
String currentLocaleName = LocaleInfo.getCurrentLocale().getLocaleName();
if(currentLocaleName.equals("default"))
currentLocaleName = "en";
if(!currentLocaleName.equals(weblabLocaleCookie))
WebLabClient.refresh(weblabLocaleCookie);
return;
}
// Else, check if there is a default language. If there is, show it
this.languageDecisionPending = true;
}
public static native String getAcceptLanguageHeader() /*-{
return $wnd.acceptLanguageHeader;
}-*/;
public static String getNewUrl(String parameterName, String parameterValue){
String newUrl = Window.Location.getPath() + "?";
final Map<String, List<String>> parameters = Window.Location.getParameterMap();
for(final String parameter : parameters.keySet())
if(!parameter.equals(parameterName)){
String value = "";
for(final String v : parameters.get(parameter))
value = v;
newUrl += parameter + "=" + value + "&";
}
newUrl += parameterName + "=" + parameterValue;
return newUrl;
}
public static void refresh(String locale){
String newUrl = Window.Location.getPath() + "?";
final Map<String, List<String>> parameters = Window.Location.getParameterMap();
for(final String parameter : parameters.keySet())
if(!parameter.equals(WebLabClient.LOCALE_URL_PARAM)){
String value = "";
for(final String v : parameters.get(parameter))
value = v;
newUrl += parameter + "=" + value + "&";
}
newUrl += WebLabClient.LOCALE_URL_PARAM + "=" + locale;
Window.Location.replace(newUrl);
}
public abstract void loadApplication();
@Override
public void onModuleLoad() {
HistoryProperties.load();
final WlWaitingLabel loadingLabel = new WlWaitingLabel("Loading WebLab-Deusto");
loadingLabel.start();
this.putWidget(loadingLabel.getWidget());
this.selectLanguage();
final String configFile = WebLabClient.SCRIPT_CONFIG_FILE;
this.configurationManager = new ConfigurationManager(configFile, new IConfigurationLoadedCallback(){
@Override
public void onLoaded() {
WebLabClient.baseLocation = WebLabClient.this.configurationManager.getProperty(BASE_LOCATION, DEFAULT_BASE_LOCATION);
if(WebLabClient.this.languageDecisionPending) {
String currentLocaleName = LocaleInfo.getCurrentLocale().getLocaleName();
if(currentLocaleName.equals("default"))
currentLocaleName = "en";
try{
if(getAcceptLanguageHeader() != null) {
final String firstLanguage = getAcceptLanguageHeader().split(";")[0].split(",")[0].split("-")[0];
if(!currentLocaleName.equals(firstLanguage)) {
WebLabClient.refresh(firstLanguage);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
final String hostDefaultLanguage = WebLabClient.this.configurationManager.getProperty(HOST_ENTITY_DEFAULT_LANGUAGE, DEFAULT_HOST_ENTITY_DEFAULT_LANGUAGE);
if(!hostDefaultLanguage.equals("en") && WebLabClient.this.languageDecisionPending)
refresh(hostDefaultLanguage);
}
final String trackingCode = WebLabClient.this.configurationManager.getProperty(GOOGLE_ANALYTICS_TRACKING_CODE, null);
if(trackingCode != null)
loadGoogleAnalytics(trackingCode);
loadApplication();
}
@Override
public void onFailure(Throwable t) {
WebLabClient.this.showError("Error loading configuration file: " + t.getMessage());
}
});
this.configurationManager.start();
}
public void setMaxWidth(int width){
RootPanel.get(WebLabClient.MAIN_SLOT).setWidth(width + "px");
}
private void loadGoogleAnalytics(String trackingCode) {
final ScriptElement gaqScript = Document.get().createScriptElement(
"var _gaq = _gaq || [];" +
"_gaq.push(['_setAccount', '" + trackingCode + "']);" +
"_gaq.push(['_trackPageview']);"
);
final Element s = Document.get().getElementsByTagName("script").getItem(0);
s.getParentNode().insertBefore(gaqScript, s);
final ScriptElement ga = Document.get().createScriptElement();
ga.setSrc(("https:".equals(Window.Location.getProtocol()) ? "https:
ga.setType("text/javascript");
ga.setAttribute("async", "true");
s.getParentNode().insertBefore(ga, s);
}
} |
package net.sandius.rembulan.core;
import net.sandius.rembulan.util.Check;
import net.sandius.rembulan.util.Cons;
/*
Properties:
1) For any coroutine c,
(c.resuming == null || c.resuming.yieldingTo == c) && (c.yieldingTo == null || c.yieldingTo.resuming == c)
(i.e. coroutines form a doubly-linked list)
2) if c is the currently-running coroutine, then c.resuming == null
3) if c is the main coroutine, then c.yieldingTo == null
Coroutine d can be resumed from c iff
c != d && d.resuming == null && d.yieldingTo == null
This means that
c.resuming = d
d.yieldingTo = c
*/
public abstract class Coroutine {
protected final LuaState state;
// paused call stack: up-to-date only iff coroutine is not running
protected Cons<ResumeInfo> callStack;
protected Coroutine yieldingTo;
protected Coroutine resuming;
public Coroutine(LuaState state) {
Check.notNull(state);
this.state = state;
}
public LuaState getOwnerState() {
return state;
}
@Override
public String toString() {
return "thread: 0x" + Integer.toHexString(hashCode());
}
} |
package org.jboss.da.rest.listings;
import org.jboss.da.listings.api.service.BlackArtifactService;
import org.jboss.da.listings.api.service.WhiteArtifactService;
import org.jboss.da.listings.api.service.ArtifactService.STATUS;
import org.jboss.da.rest.listings.model.ContainsResponse;
import org.jboss.da.rest.listings.model.RestArtifact;
import org.jboss.da.rest.listings.model.SuccessResponse;
import org.jboss.da.rest.model.ErrorMessage;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import java.util.Collections;
import java.util.Optional;
import org.jboss.da.listings.api.model.BlackArtifact;
import org.jboss.da.listings.api.model.WhiteArtifact;
/**
*
* @author Jozef Mrazek <jmrazek@redhat.com>
* @author Jakub Bartecek <jbartece@redhat.com>
*
*/
@Path("/listings")
@Api(value = "/listings", description = "Listings of black/white listed artifacts")
public class Artifacts {
@Inject
private RestConvert convert;
@Inject
private WhiteArtifactService whiteService;
@Inject
private BlackArtifactService blackService;
// Whitelist endpoints
@GET
@Path("/whitelist")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get all artifacts in the whitelist", responseContainer = "List",
response = RestArtifact.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Response successfully generated") })
public Collection<RestArtifact> getAllWhiteArtifacts() {
List<RestArtifact> artifacts = new ArrayList<>();
artifacts.addAll(convert.toRestArtifacts(whiteService.getAll()));
return artifacts;
}
@GET
@Path("/whitelist/gav")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Check if an artifact is in the whitelist",
response = ContainsResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact is in the whitelist"),
@ApiResponse(code = 404, message = "Artifact is not in the whitelist"),
@ApiResponse(code = 400, message = "All parameters are required") })
public Response isWhiteArtifactPresent(@QueryParam("groupid") String groupId,
@QueryParam("artifactid") String artifactId, @QueryParam("version") String version) {
if (groupId == null || artifactId == null || version == null)
return Response.status(Response.Status.BAD_REQUEST)
.entity(new ErrorMessage("All parameters are required")).build();
ContainsResponse response = new ContainsResponse();
List<WhiteArtifact> artifacts = whiteService.getArtifacts(groupId, artifactId, version);
response.setFound(convert.toRestArtifacts(artifacts));
response.setContains(!artifacts.isEmpty());
if (artifacts.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(response).build();
} else {
return Response.ok(response).build();
}
}
@POST
@Path("/whitelist/gav")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add an artifact to the whitelist", response = SuccessResponse.class)
@ApiResponses(
value = {
@ApiResponse(code = 200, message = "Response successfully generated"),
@ApiResponse(
code = 400,
message = "Can't add artifact to whitelist, artifact is not in redhat version"),
@ApiResponse(code = 409,
message = "Can't add artifact to whitelist, artifact is blacklisted") })
public Response addWhiteArtifact(
@ApiParam(value = "JSON object with keys 'groupId', 'artifactId', and 'version'") RestArtifact artifact) {
SuccessResponse response = new SuccessResponse();
try {
STATUS result = whiteService.addArtifact(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
switch (result) {
case ADDED:
response.setSuccess(true);
return Response.ok(response).build();
case IS_BLACKLISTED:
response.setSuccess(false);
return Response
.status(Response.Status.CONFLICT)
.entity(new ErrorMessage(
"Can't add artifact to whitelist, artifact is blacklisted"))
.build();
case NOT_MODIFIED:
response.setSuccess(false);
return Response.ok(response).build();
default:
response.setSuccess(false);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorMessage("Unexpected server error occurred.")).build();
}
} catch (IllegalArgumentException ex) {
return Response
.status(Response.Status.BAD_REQUEST)
.entity(new ErrorMessage(
"Can't add artifact to whitelist, artifact is not in redhat version."))
.build();
}
}
@DELETE
@Path("/whitelist/gav")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Remove an artifact from the whitelist", response = SuccessResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Response successfully generated") })
public SuccessResponse removeWhiteArtifact(
@ApiParam(value = "JSON object with keys 'groupId', 'artifactId', and 'version'") RestArtifact artifact) {
SuccessResponse response = new SuccessResponse();
response.setSuccess(whiteService.removeArtifact(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion()));
return response;
}
// Blacklist endpoints
@GET
@Path("/blacklist")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get all artifacts in the blacklist", responseContainer = "List",
response = RestArtifact.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Response successfully generated") })
public Collection<RestArtifact> getAllBlackArtifacts() {
List<RestArtifact> artifacts = new ArrayList<>();
artifacts.addAll(convert.toRestArtifacts(blackService.getAll()));
return artifacts;
}
@GET
@Path("/blacklist/gav")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Check if an artifact is in the blacklist",
response = ContainsResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact is in the blacklist"),
@ApiResponse(code = 404, message = "Artifact is not in the blacklist"),
@ApiResponse(code = 400, message = "All parameters are required")})
public Response isBlackArtifactPresent(@QueryParam("groupid") String groupId,
@QueryParam("artifactid") String artifactId, @QueryParam("version") String version) {
if (groupId == null || artifactId == null || version == null)
return Response.status(Response.Status.BAD_REQUEST)
.entity(new ErrorMessage("All parameters are required")).build();
ContainsResponse response = new ContainsResponse();
Optional<BlackArtifact> artifact = blackService.getArtifact(groupId, artifactId, version);
List<BlackArtifact> artifacts = artifact
.map(Collections::singletonList)
.orElse(Collections.emptyList());
response.setContains(artifact.isPresent());
response.setFound(convert.toRestArtifacts(artifacts));
if (artifact.isPresent()) {
return Response.ok(response).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(response).build();
}
}
@POST
@Path("/blacklist/gav")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add an artifact to the blacklist", response = SuccessResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Response successfully generated") })
public Response addBlackArtifact(
@ApiParam(value = "JSON object with keys 'groupId', 'artifactId', and 'version'") RestArtifact artifact) {
SuccessResponse response = new SuccessResponse();
STATUS result = blackService.addArtifact(artifact.getGroupId(), artifact.getArtifactId(),
artifact.getVersion());
switch (result) {
case ADDED:
response.setSuccess(true);
return Response.ok(response).build();
case WAS_WHITELISTED:
response.setSuccess(true);
response.setMessage("Artifact was moved from whitelist into blacklist");
return Response.ok(response).build();
case NOT_MODIFIED:
response.setSuccess(false);
return Response.ok(response).build();
default:
response.setSuccess(false);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorMessage("Unexpected server error occurred.")).build();
}
}
@DELETE
@Path("/blacklist/gav")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Remove an artifact from the blacklist", response = SuccessResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Response successfully generated") })
public SuccessResponse removeBlackArtifact(
@ApiParam(value = "JSON object with keys 'groupId', 'artifactId', and 'version'") RestArtifact artifact) {
SuccessResponse response = new SuccessResponse();
response.setSuccess(blackService.removeArtifact(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion()));
return response;
}
} |
package org.zstack.resourceconfig;
import org.zstack.header.identity.rbac.RBACDescription;
import org.zstack.header.vo.ResourceVO;
public class RBACInfo implements RBACDescription {
@Override
public void permissions() {
permissionBuilder()
.name("global-config")
.normalAPIs("org.zstack.resourceconfig.**")
.targetResources(ResourceVO.class)
.build();
}
@Override
public void contributeToRoles() {
roleContributorBuilder()
.roleName("other")
.actionsByPermissionName("global-config")
.build();
}
@Override
public void roles() {
}
@Override
public void globalReadableResources() {
}
} |
package org.jetel.graph;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.Future;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.main.runGraph;
import org.jetel.test.CloverTestCase;
import org.jetel.util.file.FileUtils;
import org.jetel.util.string.StringUtils;
public class ResetTest extends CloverTestCase {
private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/";
private final static String[] EXAMPLE_PATH = {
"../cloveretl.examples/SimpleExamples/",
"../cloveretl.examples/AdvancedExamples/",
"../cloveretl.examples/CTL1FunctionsTutorial/",
"../cloveretl.examples/CTL2FunctionsTutorial/",
"../cloveretl.examples/DataProfiling/",
"../cloveretl.examples/DataSampling/",
"../cloveretl.examples/ExtExamples/",
"../cloveretl.test.scenarios/",
"../cloveretl.examples.commercial/",
"../cloveretl.examples/CompanyTransactionsTutorial/"
};
private final static String[] NEEDS_SCENARIOS_CONNECTION = {
"graphRevenues.grf",
"graphDBExecuteMsSql.grf",
"graphDBExecuteMySql.grf",
"graphDBExecuteOracle.grf",
"graphDBExecutePostgre.grf",
"graphDBExecuteSybase.grf",
"graphInfobrightDataWriterRemote.grf",
"graphLdapReaderWriter.grf"
};
private final static String[] NEEDS_SCENARIOS_LIB = {
"graphDBExecuteOracle.grf",
"graphDBExecuteSybase.grf",
"graphLdapReaderWriter.grf"
};
private final static String GRAPHS_DIR = "graph";
private final static String TRANS_DIR = "trans";
private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"};
private final String basePath;
private final File graphFile;
private final boolean batchMode;
private boolean cleanUp = true;
private static Log logger = LogFactory.getLog(ResetTest.class);
public static Test suite() {
final TestSuite suite = new TestSuite();
for (int i = 0; i < EXAMPLE_PATH.length; i++) {
logger.info("Testing graphs in " + EXAMPLE_PATH[i]);
final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR);
if(!graphsDir.exists()){
throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found");
}
File[] graphFiles =graphsDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".grf")
&& !pathname.getName().startsWith("TPCH")// ok, performance tests - last very long
&& !pathname.getName().contains("Performance")// ok, performance tests - last very long
&& !pathname.getName().equals("graphJoinData.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("conversionNum2num.grf") // ok, should fail
&& !pathname.getName().equals("outPortWriting.grf") // ok, should fail
&& !pathname.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client
&& !pathname.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client
&& !pathname.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client
&& !pathname.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client
&& !pathname.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client
&& !pathname.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server
&& !pathname.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server
&& !pathname.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows
&& !pathname.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server
&& !pathname.getName().equals("graphSequenceChecker.grf") // ok, is to fail
&& !pathname.getName().equals("FixedData.grf") // ok, is to fail
&& !pathname.getName().equals("xpathReaderStates.grf") // ok, is to fail
&& !pathname.getName().equals("graphDataPolicy.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDecimal2integer.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDecimal2long.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDouble2integer.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDouble2long.grf") // ok, is to fail
&& !pathname.getName().equals("conversionLong2integer.grf") // ok, is to fail
&& !pathname.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths
&& !pathname.getName().equals("mountainsInformix.grf") // see issue 2550
&& !pathname.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows
&& !pathname.getName().equals("XLSEncryptedFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSInvalidFile.grf") // ok, is to fail
&& !pathname.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardStrict.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail
&& !pathname.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts
&& !pathname.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts
&& !pathname.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail
&& !pathname.getName().equals("FailingGraph.grf") // ok, is to fail
&& !pathname.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts
&& !pathname.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail
&& !pathname.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail
&& !pathname.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail
&& !pathname.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines
&& !pathname.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved
&& !pathname.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate)
&& !pathname.getName().contains("firebird") // remove after CL-2170 solved
&& !pathname.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved
&& !pathname.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved
&& !pathname.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved
&& !pathname.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved
&& !pathname.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved
&& !pathname.getName().equals("manyRecords.grf") // remove after CL-1825 implemented
&& !pathname.getName().equals("packedDecimal.grf") // remove after CL-1811 solved
&& !pathname.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately
&& !pathname.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf
&& !pathname.getName().equals("testdata_intersection.grf") // remove after CL-1792 solved
&& !pathname.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail
&& !pathname.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved
&& !pathname.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail
&& !pathname.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail
&& !pathname.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail
&& !pathname.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server
&& !pathname.getName().equals("DenormalizerWithoutInputFile.grf"); // probably subgraph not supposed to be executed separately
}
});
Arrays.sort(graphFiles);
for( int j = 0; j < graphFiles.length; j++){
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false));
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false));
}
}
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
initEngine();
}
protected static String getTestName(String basePath, File graphFile, boolean batchMode) {
final StringBuilder ret = new StringBuilder();
final String n = graphFile.getName();
int lastDot = n.lastIndexOf('.');
if (lastDot == -1) {
ret.append(n);
} else {
ret.append(n.substring(0, lastDot));
}
if (batchMode) {
ret.append("-batch");
} else {
ret.append("-nobatch");
}
return ret.toString();
}
protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) {
super(getTestName(basePath, graphFile, batchMode));
this.basePath = basePath;
this.graphFile = graphFile;
this.batchMode = batchMode;
this.cleanUp = cleanup;
}
@Override
protected void runTest() throws Throwable {
final String beseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/');
logger.info("Project dir: " + beseAbsolutePath);
logger.info("Analyzing graph " + graphFile.getPath());
logger.info("Batch mode: " + batchMode);
final GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
runtimeContext.setUseJMX(false);
runtimeContext.setContextURL(FileUtils.getFileURL(basePath));
// absolute path in PROJECT parameter is required for graphs using Derby database
runtimeContext.addAdditionalProperty("PROJECT", beseAbsolutePath);
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) {
final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath();
runtimeContext.addAdditionalProperty("CONN_DIR", connDir);
logger.info("CONN_DIR set to " + connDir);
}
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory
final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath();
runtimeContext.addAdditionalProperty("LIB_DIR", libDir);
logger.info("LIB_DIR set to " + libDir);
}
// for scenarios graphs, add the TRANS dir to the classpath
if (basePath.contains("cloveretl.test.scenarios")) {
runtimeContext.setRuntimeClassPath(new URL[] {FileUtils.getFileURL(FileUtils.appendSlash(beseAbsolutePath) + TRANS_DIR + "/")});
runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath());
}
runtimeContext.setBatchMode(batchMode);
final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext);
try {
graph.setDebugMode(false);
EngineInitializer.initGraph(graph);
for (int i = 0; i < 3; i++) {
final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext);
Result result = Result.N_A;
result = futureResult.get();
switch (result) {
case FINISHED_OK:
// everything O.K.
logger.info("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
break;
default:
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
}
}
} catch (Throwable e) {
throw new IllegalStateException("Error executing grap " + graphFile, e);
} finally {
if (cleanUp) {
cleanupData();
}
logger.info("Transformation graph is freeing.\n");
graph.free();
}
}
private void cleanupData() {
for (String outDir : OUT_DIRS) {
File outDirFile = new File(basePath, outDir);
File[] file = outDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile();
}
});
for (int i = 0; i < file.length; i++) {
final boolean drt = file[i].delete();
if (drt) {
logger.info("Cleanup: deleted file " + file[i].getAbsolutePath());
} else {
logger.info("Cleanup: error delete file " + file[i].getAbsolutePath());
}
}
}
}
} |
package org.wiztools.restclient.ui;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.inject.Inject;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.filechooser.FileFilter;
import org.simplericity.macify.eawt.Application;
import org.simplericity.macify.eawt.ApplicationEvent;
import org.simplericity.macify.eawt.ApplicationListener;
import org.simplericity.macify.eawt.DefaultApplication;
import org.wiztools.restclient.*;
import org.wiztools.restclient.server.TraceServer;
/**
*
* @author schandran
*/
class RESTMain implements RESTUserInterface {
private final Application application = new DefaultApplication();
private RESTView view;
private AboutDialog aboutDialog;
private OptionsDialog optionsDialog;
private PasswordGenDialog passwordGenDialog;
// Requests and responses are generally saved in different dirs
private JFileChooser jfc_request = UIUtil.getNewJFileChooser();
private JFileChooser jfc_response = UIUtil.getNewJFileChooser();
private JFileChooser jfc_generic = UIUtil.getNewJFileChooser();
private JFileChooser jfc_archive = UIUtil.getNewJFileChooser();
private UIPreferenceRepo uiPrefs = ServiceLocator.getInstance(UIPreferenceRepo.class);
private final JFrame frame;
/**
* This constructor is used for plugin initialization
* @param frame
* @param scriptEditor script editor
* @param responseViewer response viewer
*/
public RESTMain(final JFrame frame, ScriptEditor scriptEditor, ScriptEditor responseViewer) {
this.frame = frame;
init(true, scriptEditor, responseViewer); // true means isPlugin==true
}
public RESTMain(final String title){
// Macify:
application.addAboutMenuItem();
application.addApplicationListener(new RCApplicationListener());
application.addPreferencesMenuItem();
// Application logic:
frame = new JFrame(title);
init(false, null, null); // false means isPlugin==false
}
@Override
public RESTView getView(){
return view;
}
@Override
public JFrame getFrame(){
return this.frame;
}
private void createMenu(){
JMenuBar jmb = new JMenuBar();
// File menu
JMenu jm_file = new JMenu("File");
jm_file.setMnemonic(KeyEvent.VK_F);
JMenuItem jmi_open_req = new JMenuItem("Open Request", RCFileView.REQUEST_ICON);
jmi_open_req.setMnemonic(KeyEvent.VK_O);
jmi_open_req.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
jmi_open_req.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jmi_open_reqAction();
}
});
jm_file.add(jmi_open_req);
JMenuItem jmi_open_res = new JMenuItem("Open Response", RCFileView.RESPONSE_ICON);
jmi_open_res.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jmi_open_resAction();
}
});
jm_file.add(jmi_open_res);
JMenuItem jmi_open_archive = new JMenuItem("Open Req-Res Archive", RCFileView.ARCHIVE_ICON);
jmi_open_archive.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jmi_open_archiveAction();
}
});
jm_file.add(jmi_open_archive);
final JMenu jm_open_recent = new JMenu("Open recent");
jm_open_recent.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent me) {
List<File> recentFiles = uiPrefs.getRecentFiles();
jm_open_recent.removeAll();
for(final File f: recentFiles) {
JMenuItem jmi = new JMenuItem(f.getName());
jmi.setToolTipText(f.getAbsolutePath());
jmi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
FileOpenUtil.open(view, f);
}
});
jm_open_recent.add(jmi);
}
}
@Override
public void menuDeselected(MenuEvent me) {
// do nothing
}
@Override
public void menuCanceled(MenuEvent me) {
// do nothing
}
});
jm_file.add(jm_open_recent);
jm_file.addSeparator();
JMenuItem jmi_save_req = new JMenuItem("Save Request", RCFileView.REQUEST_ICON);
jmi_save_req.setMnemonic(KeyEvent.VK_Q);
jmi_save_req.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
jmi_save_req.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
actionSave(FileChooserType.SAVE_REQUEST);
}
});
jm_file.add(jmi_save_req);
JMenuItem jmi_save_res = new JMenuItem("Save Response", RCFileView.RESPONSE_ICON);
jmi_save_res.setMnemonic(KeyEvent.VK_S);
jmi_save_res.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
actionSave(FileChooserType.SAVE_RESPONSE);
}
});
jm_file.add(jmi_save_res);
JMenuItem jmi_save_res_body = new JMenuItem("Save Response Body", RCFileView.FILE_ICON);
// jmi_save_res_body.setMnemonic(' ');
jmi_save_res_body.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
actionSave(FileChooserType.SAVE_RESPONSE_BODY);
}
});
jm_file.add(jmi_save_res_body);
JMenuItem jmi_save_archive = new JMenuItem("Save Req-Res Archive", RCFileView.ARCHIVE_ICON);
jmi_save_archive.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
actionSave(FileChooserType.SAVE_ARCHIVE);
}
});
jm_file.add(jmi_save_archive);
if(!application.isMac()) { // Shown only for non-Mac platform!
jm_file.addSeparator();
JMenuItem jmi_exit = new JMenuItem("Exit", UIUtil.getIconFromClasspath(RCFileView.iconBasePath + "fv_exit.png"));
jmi_exit.setMnemonic(KeyEvent.VK_X);
jmi_exit.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
jmi_exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
shutdownCall();
}
});
jm_file.add(jmi_exit);
}
// Edit menu
JMenu jm_edit = new JMenu("Edit");
jm_edit.setMnemonic(KeyEvent.VK_E);
JMenuItem jmi_clear_res = new JMenuItem("Clear Response");
jmi_clear_res.setMnemonic(KeyEvent.VK_C);
jmi_clear_res.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
view.clearUIResponse();
}
});
jm_edit.add(jmi_clear_res);
JMenuItem jmi_reset_all = new JMenuItem("Reset All");
jmi_reset_all.setMnemonic('a');
jmi_reset_all.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
view.clearUIResponse();
view.clearUIRequest();
}
});
jm_edit.add(jmi_reset_all);
jm_edit.addSeparator();
JMenuItem jmi_reset_to_last = new JMenuItem("Reset to Last Request-Response");
jmi_reset_to_last.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(view.getLastRequest() != null && view.getLastResponse() != null){
view.setUIToLastRequestResponse();
}
else{
JOptionPane.showMessageDialog(frame,
"No Last Request-Response Available",
"No Last Request-Response Available",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
jm_edit.add(jmi_reset_to_last);
// Tools menu
JMenu jm_tools = new JMenu("Tools");
jm_tools.setMnemonic('o');
JMenuItem jmi_session = new JMenuItem("Open Session View");
jmi_session.setMnemonic('s');
jmi_session.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
view.showSessionFrame();
}
});
// Commenting it out for 2.x release. This will be the focus of 3.x release:
// jm_tools.add(jmi_session);
JMenuItem jmi_pwd_gen = new JMenuItem("Password Encoder/Decoder");
jmi_pwd_gen.setMnemonic('p');
jmi_pwd_gen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(passwordGenDialog == null){
passwordGenDialog = new PasswordGenDialog(frame);
}
passwordGenDialog.setVisible(true);
}
});
jm_tools.add(jmi_pwd_gen);
jm_tools.addSeparator();
// Trace Server
JMenuItem jmi_server_start = new JMenuItem("Start Trace Server @ port " + TraceServer.PORT);
jmi_server_start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try{
TraceServer.start();
view.setStatusMessage("Trace Server started.");
}
catch(Exception ex){
view.showError(Util.getStackTrace(ex));
}
}
});
jm_tools.add(jmi_server_start);
JMenuItem jmi_server_stop = new JMenuItem("Stop Trace Server");
jmi_server_stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try{
if(TraceServer.isRunning()){
TraceServer.stop();
view.setStatusMessage("Trace Server stopped.");
}
}
catch(Exception ex){
view.showError(Util.getStackTrace(ex));
}
}
});
jm_tools.add(jmi_server_stop);
JMenuItem jmi_server_fill_url = new JMenuItem("Insert Trace Server URL");
jmi_server_fill_url.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
RequestBean request = (RequestBean) view.getRequestFromUI();
if(request.getUrl() != null){
int ret = JOptionPane.showConfirmDialog(frame,
"URL field not empty. Overwrite?",
"Request URL not empty",
JOptionPane.YES_NO_OPTION);
if(ret == JOptionPane.NO_OPTION){
return;
}
}
try {
request.setUrl(new URL("http://localhost:" + TraceServer.PORT + "/"));
} catch (MalformedURLException ex) {
assert true: ex;
}
view.setUIFromRequest(request);
}
});
jm_tools.add(jmi_server_fill_url);
if(!application.isMac()) { // Add Options menu only for non-Mac platform!
jm_tools.addSeparator();
JMenuItem jmi_options = new JMenuItem("Options");
jmi_options.setMnemonic('o');
jmi_options.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
showOptionsDialog();
}
});
jm_tools.add(jmi_options);
}
// Add menus to menu-bar
jmb.add(jm_file);
jmb.add(jm_edit);
jmb.add(jm_tools);
// Help menu
if(!application.isMac()) { // show for only non-Mac platform!
JMenu jm_help = new JMenu("Help");
jm_help.setMnemonic(KeyEvent.VK_H);
JMenuItem jmi_about = new JMenuItem("About");
jmi_about.setMnemonic('a');
jmi_about.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
showAboutDialog();
}
});
jm_help.add(jmi_about);
// Add Help menu to Menubar:
jmb.add(jm_help);
}
frame.setJMenuBar(jmb);
}
private void init(final boolean isPlugin, ScriptEditor editor, ScriptEditor responseViewer) {
// JFileChooser: Initialize
jfc_request.addChoosableFileFilter(new RCFileFilter(FileType.REQUEST_EXT));
jfc_response.addChoosableFileFilter(new RCFileFilter(FileType.RESPONSE_EXT));
jfc_archive.addChoosableFileFilter(new RCFileFilter(FileType.ARCHIVE_EXT));
// Set the view on the pane
view = new RESTView(this, editor, responseViewer);
UIRegistry.getInstance().view = view;
// Create AboutDialog
aboutDialog = new AboutDialog(frame);
if(!isPlugin){
frame.setContentPane(view);
createMenu();
ImageIcon icon =
UIUtil.getIconFromClasspath("org/wiztools/restclient/WizLogo.png");
frame.setIconImage(icon.getImage());
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event){
shutdownCall();
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
private void showOptionsDialog(){
if(optionsDialog == null){
optionsDialog = new OptionsDialog(frame);
}
optionsDialog.setVisible(true);
}
@Override
public File getOpenFile(final FileChooserType type){
return getOpenFile(type, frame);
}
@Override
public File getOpenFile(final FileChooserType type, final Component parent){
String title = null;
JFileChooser jfc = null;
if(type == FileChooserType.OPEN_REQUEST){
jfc = jfc_request;
title = "Open Request";
}
else if(type == FileChooserType.OPEN_RESPONSE){
jfc = jfc_response;
title = "Open Response";
}
else if(type == FileChooserType.OPEN_ARCHIVE){
jfc = jfc_archive;
title = "Open Req-Res Archive";
}
else if(type == FileChooserType.OPEN_REQUEST_BODY){
jfc = jfc_generic;
title = "Open Request Body";
}
else if(type == FileChooserType.OPEN_TEST_SCRIPT){
jfc = jfc_generic;
title = "Open Test Script";
}
else if(type == FileChooserType.OPEN_GENERIC){
jfc = jfc_generic;
title = "Open";
}
jfc.setDialogTitle(title);
int status = jfc.showOpenDialog(parent);
if(status == JFileChooser.APPROVE_OPTION){
File f = jfc.getSelectedFile();
return f;
}
return null;
}
private void jmi_open_reqAction(){
File f = getOpenFile(FileChooserType.OPEN_REQUEST);
if(f != null){
FileOpenUtil.openRequest(view, f);
uiPrefs.openedFile(f);
}
}
private void jmi_open_resAction(){
File f = getOpenFile(FileChooserType.OPEN_RESPONSE);
if(f != null){
FileOpenUtil.openResponse(view, f);
uiPrefs.openedFile(f);
}
}
private void jmi_open_archiveAction(){
File f = getOpenFile(FileChooserType.OPEN_ARCHIVE);
if(f != null){
FileOpenUtil.openArchive(view, f);
uiPrefs.openedFile(f);
}
}
// This method is invoked from SU.invokeLater
@Override
public File getSaveFile(final FileChooserType type){
JFileChooser jfc = null;
String title = null;
if(type == FileChooserType.SAVE_REQUEST){
jfc = jfc_request;
title = "Save Request";
}
else if(type == FileChooserType.SAVE_RESPONSE){
jfc = jfc_response;
title = "Save Response";
}
else if(type == FileChooserType.SAVE_RESPONSE_BODY){
jfc = jfc_generic;
title = "Save Response Body";
}
else if(type == FileChooserType.SAVE_ARCHIVE){
jfc = jfc_archive;
title = "Save Req-Res Archive";
}
jfc.setDialogTitle(title);
int status = jfc.showSaveDialog(frame);
if(status == JFileChooser.APPROVE_OPTION){
File f = jfc.getSelectedFile();
if(f == null){
return null;
}
String ext = null;
switch(type){
case SAVE_REQUEST:
ext = FileType.REQUEST_EXT;
break;
case SAVE_RESPONSE:
ext = FileType.RESPONSE_EXT;
break;
case SAVE_ARCHIVE:
ext = FileType.ARCHIVE_EXT;
break;
default:
break;
}
if(ext != null){
String path = f.getAbsolutePath();
path = path.toLowerCase();
// Add our extension only if the selected filter is ours
FileFilter ff = jfc.getFileFilter();
RCFileFilter rcFileFilter = null;
if(ff instanceof RCFileFilter){
rcFileFilter = (RCFileFilter)ff;
}
if((rcFileFilter != null) &&
(rcFileFilter.getFileTypeExt().equals(ext)) &&
!path.endsWith(ext)){
f = new File(f.getAbsolutePath() + ext);
jfc.setSelectedFile(f);
view.setStatusMessage("Adding default extension: " + ext);
}
}
if(f.exists()){
int yesNo = JOptionPane.showConfirmDialog(frame,
"File exists. Overwrite?",
"File exists",
JOptionPane.YES_NO_OPTION);
if(yesNo == JOptionPane.YES_OPTION){
return f;
}
else{
JOptionPane.showMessageDialog(frame,
"File not saved!",
"Not saved",
JOptionPane.INFORMATION_MESSAGE);
}
}
else{ // If the file is new one
return f;
}
}
return null;
}
private static final String[] DO_SAVE_UI_REQUEST = new String[]{"Request", "completed Request"};
private static final String[] DO_SAVE_UI_RESPONSE = new String[]{"Response", "received Response"};
private static final String[] DO_SAVE_UI_ARCHIVE = new String[]{"Request/Response", "completed Request-Response"};
private boolean doSaveEvenIfUIChanged(final String[] parameters){
final String message = MessageI18N.getMessage(
"yes-no.cant.save.req-res", parameters);
int optionChoosen = JOptionPane.showConfirmDialog(view,
message,
"UI Parameters Changed!",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if(optionChoosen != JOptionPane.OK_OPTION){
return false;
}
return true;
}
private void actionSave(final FileChooserType type){
if(type == FileChooserType.SAVE_REQUEST){
Request request = view.getLastRequest();
if(request == null){
JOptionPane.showMessageDialog(view,
"No last request available.",
"No Request",
JOptionPane.ERROR_MESSAGE);
return;
}
Request uiRequest = view.getRequestFromUI();
if(!request.equals(uiRequest)){
if(!doSaveEvenIfUIChanged(DO_SAVE_UI_REQUEST)){
return;
}
}
File f = getSaveFile(FileChooserType.SAVE_REQUEST);
if(f != null){
try{
XMLUtil.writeRequestXML(request, f);
}
catch(IOException ex){
view.showError(Util.getStackTrace(ex));
}
catch(XMLException ex){
view.showError(Util.getStackTrace(ex));
}
}
}
else if(type == FileChooserType.SAVE_RESPONSE){
Response response = view.getLastResponse();
if(response == null){
JOptionPane.showMessageDialog(view,
"No last response available.",
"No Response",
JOptionPane.ERROR_MESSAGE);
return;
}
Response uiResponse = view.getResponseFromUI();
if(!response.equals(uiResponse)){
if(!doSaveEvenIfUIChanged(DO_SAVE_UI_RESPONSE)){
return;
}
}
File f = getSaveFile(FileChooserType.SAVE_RESPONSE);
if(f != null){
try{
XMLUtil.writeResponseXML(response, f);
}
catch(IOException ex){
view.showError(Util.getStackTrace(ex));
}
catch(XMLException ex){
view.showError(Util.getStackTrace(ex));
}
}
}
else if(type == FileChooserType.SAVE_RESPONSE_BODY){
Response response = view.getLastResponse();
if(response == null){
JOptionPane.showMessageDialog(view,
"No last response available.",
"No Response",
JOptionPane.ERROR_MESSAGE);
return;
}
File f = getSaveFile(FileChooserType.SAVE_RESPONSE_BODY);
if(f != null){
PrintWriter pw = null;
try{
pw = new PrintWriter(new FileWriter(f));
pw.print(response.getResponseBody());
}
catch(IOException ex){
view.showError(Util.getStackTrace(ex));
}
finally{
if(pw != null){
pw.close();
}
}
}
}
else if(type == FileChooserType.SAVE_ARCHIVE){
Request request = view.getLastRequest();
Response response = view.getLastResponse();
if(request == null || response == null){
JOptionPane.showMessageDialog(view,
"No last request/response available.",
"No Request/Response",
JOptionPane.ERROR_MESSAGE);
return;
}
Request uiRequest = view.getRequestFromUI();
Response uiResponse = view.getResponseFromUI();
if((!request.equals(uiRequest)) || (!response.equals(uiResponse))){
if(!doSaveEvenIfUIChanged(DO_SAVE_UI_ARCHIVE)){
return;
}
}
File f = getSaveFile(FileChooserType.SAVE_ARCHIVE);
if(f != null){
Exception e = null;
try{
Util.createReqResArchive(request, response, f);
}
catch(IOException ex){
e = ex;
}
catch(XMLException ex){
e = ex;
}
if(e != null){
view.showError(Util.getStackTrace(e));
}
}
}
}
private void shutdownCall(){
System.out.println("Exiting...");
System.exit(0);
}
/**
* show about dialog
*/
public void showAboutDialog() {
aboutDialog.setVisible(true);
}
public class RCApplicationListener implements ApplicationListener {
@Override
public void handleAbout(ApplicationEvent ae) {
showAboutDialog();
ae.setHandled(true);
}
@Override
public void handleOpenApplication(ApplicationEvent ae) {
// do nothing!
}
@Override
public void handleOpenFile(ApplicationEvent ae) {
final String fileName = ae.getFilename();
final File f = new File(fileName);
FileOpenUtil.open(view, f);
ae.setHandled(true);
}
@Override
public void handlePreferences(ApplicationEvent ae) {
showOptionsDialog();
ae.setHandled(true);
}
@Override
public void handlePrintFile(ApplicationEvent ae) {
JOptionPane.showMessageDialog(frame, "Sorry, printing not implemented");
}
@Override
public void handleQuit(ApplicationEvent ae) {
shutdownCall();
}
@Override
public void handleReOpenApplication(ApplicationEvent ae) {
frame.setVisible(true);
ae.setHandled(true);
}
}
} |
package org.zalando.riptide;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import org.springframework.http.HttpMethod;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.net.URI;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.springframework.web.util.UriComponentsBuilder.fromUri;
import static org.springframework.web.util.UriComponentsBuilder.fromUriString;
public interface RequestArguments {
URI getBaseUrl();
HttpMethod getMethod();
String getUriTemplate();
ImmutableList<Object> getUriVariables();
URI getUri();
ImmutableMultimap<String, String> getQueryParams();
URI getRequestUri();
ImmutableMultimap<String, String> getHeaders();
Object getBody();
RequestArguments withBaseUrl(@Nullable URI baseUrl);
RequestArguments withMethod(@Nullable HttpMethod method);
RequestArguments withUriTemplate(@Nullable String uriTemplate);
RequestArguments withUriVariables(@Nullable ImmutableList<Object> uriVariables);
RequestArguments withUri(@Nullable URI uri);
RequestArguments withQueryParams(@Nullable ImmutableMultimap<String, String> queryParams);
RequestArguments withRequestUri(@Nullable URI requestUri);
RequestArguments withHeaders(@Nullable ImmutableMultimap<String, String> headers);
RequestArguments withBody(@Nullable Object body);
default RequestArguments withRequestUri() {
@Nullable final URI uri = getUri();
@Nullable final URI unresolvedUri;
if (uri == null) {
final String uriTemplate = getUriTemplate();
if (uriTemplate == null) {
unresolvedUri = null;
} else {
// expand uri template
unresolvedUri = fromUriString(uriTemplate)
.buildAndExpand(getUriVariables().toArray())
.encode()
.toUri();
}
} else {
unresolvedUri = uri;
}
@Nullable final URI baseUrl = getBaseUrl();
@Nonnull final URI resolvedUri;
if (unresolvedUri == null) {
resolvedUri = checkNotNull(baseUrl, "base url required");
} else if (baseUrl == null) {
resolvedUri = unresolvedUri;
} else {
resolvedUri = baseUrl.resolve(unresolvedUri);
}
// encode query params
final MultiValueMap<String, String> queryParams;
{
final UriComponentsBuilder components = UriComponentsBuilder.newInstance();
getQueryParams().entries().forEach(entry ->
components.queryParam(entry.getKey(), entry.getValue()));
queryParams = components.build().encode().getQueryParams();
}
// build request uri
final URI requestUri = fromUri(resolvedUri)
.queryParams(queryParams)
.build(true).normalize().toUri();
return withRequestUri(requestUri);
}
static RequestArguments create() {
return new DefaultRequestArguments(null, null, null, ImmutableList.of(), null, ImmutableMultimap.of(), null,
ImmutableMultimap.of(), null);
}
} |
package org.robolectric;
import android.os.Build;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import org.junit.AssumptionViolatedException;
import org.junit.Ignore;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.robolectric.android.AndroidInterceptors;
import org.robolectric.android.internal.ParallelUniverse;
import org.robolectric.annotation.Config;
import org.robolectric.internal.AndroidConfigurer;
import org.robolectric.internal.BuckManifestFactory;
import org.robolectric.internal.DefaultManifestFactory;
import org.robolectric.internal.ManifestFactory;
import org.robolectric.internal.ManifestIdentifier;
import org.robolectric.internal.MavenManifestFactory;
import org.robolectric.internal.ParallelUniverseInterface;
import org.robolectric.internal.SandboxFactory;
import org.robolectric.internal.SandboxTestRunner;
import org.robolectric.internal.SdkConfig;
import org.robolectric.internal.SdkEnvironment;
import org.robolectric.internal.ShadowProvider;
import org.robolectric.internal.bytecode.ClassHandler;
import org.robolectric.internal.bytecode.InstrumentationConfiguration;
import org.robolectric.internal.bytecode.InstrumentationConfiguration.Builder;
import org.robolectric.internal.bytecode.Interceptor;
import org.robolectric.internal.bytecode.Sandbox;
import org.robolectric.internal.bytecode.SandboxClassLoader;
import org.robolectric.internal.bytecode.ShadowMap;
import org.robolectric.internal.bytecode.ShadowWrangler;
import org.robolectric.manifest.AndroidManifest;
import org.robolectric.pluginapi.SdkPicker;
import org.robolectric.util.PerfStatsCollector;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.inject.Injector;
/**
* Loads and runs a test in a {@link SandboxClassLoader} in order to provide a simulation of the
* Android runtime environment.
*/
@SuppressWarnings("NewApi")
public class RobolectricTestRunner extends SandboxTestRunner {
public static final String CONFIG_PROPERTIES = "robolectric.properties";
private static final Injector INJECTOR;
private final Ctx ctx;
private static final Map<ManifestIdentifier, AndroidManifest> appManifestsCache = new HashMap<>();
private ServiceLoader<ShadowProvider> providers;
private final ResourcesMode resourcesMode = getResourcesMode();
private boolean alwaysIncludeVariantMarkersInName =
Boolean.parseBoolean(
System.getProperty("robolectric.alwaysIncludeVariantMarkersInTestName", "false"));
static {
new SecureRandom(); // this starts up the Poller SunPKCS11-Darwin thread early, outside of any Robolectric classloader
INJECTOR = defaultInjector();
}
protected static Injector defaultInjector() {
return new Injector()
.register(Properties.class, System.getProperties())
.registerDefault(ApkLoader.class, ApkLoader.class)
.registerDefault(SandboxFactory.class, SandboxFactory.class)
.registerDefault(Ctx.class, Ctx.class);
}
public static class Ctx {
final SandboxFactory sandboxFactory;
final ApkLoader apkLoader;
final SdkPicker sdkPicker;
final org.robolectric.pluginapi.ConfigMerger configMerger;
@Inject
public Ctx(SandboxFactory sandboxFactory, ApkLoader apkLoader,
SdkPicker sdkPicker,
org.robolectric.pluginapi.ConfigMerger configMerger) {
this.sandboxFactory = sandboxFactory;
this.apkLoader = apkLoader;
this.sdkPicker = sdkPicker;
this.configMerger = configMerger;
}
}
/**
* Creates a runner to run {@code testClass}. Use the {@link Config} annotation to configure.
*
* @param testClass the test class to be run
* @throws InitializationError if junit says so
*/
public RobolectricTestRunner(final Class<?> testClass) throws InitializationError {
this(testClass, INJECTOR);
}
protected RobolectricTestRunner(final Class<?> testClass, Injector injector)
throws InitializationError {
super(testClass);
ctx = injector.getInstance(Ctx.class);
}
/**
* Create a {@link ClassHandler} appropriate for the given arguments.
*
* Robolectric may chose to cache the returned instance, keyed by <tt>shadowMap</tt> and <tt>sdkConfig</tt>.
*
* Custom TestRunner subclasses may wish to override this method to provide alternate configuration.
*
* @param shadowMap the {@link ShadowMap} in effect for this test
* @param sandbox the {@link SdkConfig} in effect for this test
* @return an appropriate {@link ClassHandler}. This implementation returns a {@link ShadowWrangler}.
* @since 2.3
*/
@Override
@Nonnull
protected ClassHandler createClassHandler(ShadowMap shadowMap, Sandbox sandbox) {
return new ShadowWrangler(shadowMap, ((SdkEnvironment) sandbox).getSdkConfig().getApiLevel(), getInterceptors());
}
@Override
@Nonnull // todo
protected Collection<Interceptor> findInterceptors() {
return AndroidInterceptors.all();
}
/**
* Create an {@link InstrumentationConfiguration} suitable for the provided
* {@link FrameworkMethod}.
*
* Adds configuration for Android using {@link AndroidConfigurer}.
*
* Custom TestRunner subclasses may wish to override this method to provide additional
* configuration.
*
* @param method the test method that's about to run
* @return an {@link InstrumentationConfiguration}
*/
@Override @Nonnull
protected InstrumentationConfiguration createClassLoaderConfig(final FrameworkMethod method) {
Builder builder = new Builder(super.createClassLoaderConfig(method));
AndroidConfigurer.configure(builder, getInterceptors());
AndroidConfigurer.withConfig(builder, ((RobolectricFrameworkMethod) method).config);
return builder.build();
}
@Override
protected void configureSandbox(Sandbox sandbox, FrameworkMethod method) {
SdkEnvironment sdkEnvironment = (SdkEnvironment) sandbox;
RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) method;
boolean isLegacy = roboMethod.isLegacy();
roboMethod.parallelUniverseInterface = getHooksInterface(sdkEnvironment);
roboMethod.parallelUniverseInterface.setSdkConfig(roboMethod.sdkConfig);
roboMethod.parallelUniverseInterface.setResourcesMode(isLegacy);
super.configureSandbox(sandbox, method);
}
/**
* An instance of the returned class will be created for each test invocation.
*
* Custom TestRunner subclasses may wish to override this method to provide alternate configuration.
*
* @return a class which implements {@link TestLifecycle}. This implementation returns a {@link DefaultTestLifecycle}.
*/
@Nonnull
protected Class<? extends TestLifecycle> getTestLifecycleClass() {
return DefaultTestLifecycle.class;
}
enum ResourcesMode {
legacy,
binary,
best,
both;
static final ResourcesMode DEFAULT = best;
private static ResourcesMode getFromProperties() {
String resourcesMode = System.getProperty("robolectric.resourcesMode");
return resourcesMode == null ? DEFAULT : valueOf(resourcesMode);
}
boolean includeLegacy(AndroidManifest appManifest) {
return appManifest.supportsLegacyResourcesMode()
&&
(this == legacy
|| (this == best && !appManifest.supportsBinaryResourcesMode())
|| this == both);
}
boolean includeBinary(AndroidManifest appManifest) {
return appManifest.supportsBinaryResourcesMode()
&& (this == binary || this == best || this == both);
}
}
@Override
protected List<FrameworkMethod> getChildren() {
List<FrameworkMethod> children = new ArrayList<>();
for (FrameworkMethod frameworkMethod : super.getChildren()) {
try {
Config config = getConfig(frameworkMethod.getMethod());
AndroidManifest appManifest = getAppManifest(config);
List<SdkConfig> sdksToRun = ctx.sdkPicker.selectSdks(config, appManifest);
RobolectricFrameworkMethod last = null;
for (SdkConfig sdkConfig : sdksToRun) {
if (resourcesMode.includeLegacy(appManifest)) {
children.add(
last =
new RobolectricFrameworkMethod(
frameworkMethod.getMethod(),
appManifest,
sdkConfig,
config,
ResourcesMode.legacy,
resourcesMode,
alwaysIncludeVariantMarkersInName));
}
if (resourcesMode.includeBinary(appManifest)) {
children.add(
last =
new RobolectricFrameworkMethod(
frameworkMethod.getMethod(),
appManifest,
sdkConfig,
config,
ResourcesMode.binary,
resourcesMode,
alwaysIncludeVariantMarkersInName));
}
}
if (last != null) {
last.dontIncludeVariantMarkersInTestName();
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("failed to configure " +
getTestClass().getName() + "." + frameworkMethod.getMethod().getName() +
": " + e.getMessage(), e);
}
}
return children;
}
@Override protected boolean shouldIgnore(FrameworkMethod method) {
return method.getAnnotation(Ignore.class) != null;
}
@Override
@Nonnull
protected SdkEnvironment getSandbox(FrameworkMethod method) {
RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) method;
SdkConfig sdkConfig = roboMethod.sdkConfig;
InstrumentationConfiguration classLoaderConfig = createClassLoaderConfig(method);
boolean useLegacyResources = roboMethod.isLegacy();
if (useLegacyResources && sdkConfig.getApiLevel() > Build.VERSION_CODES.P) {
throw new AssumptionViolatedException("Robolectric doesn't support legacy mode after P");
}
if (sdkConfig.isKnown() && !sdkConfig.isSupported()) {
try {
return ctx.sandboxFactory.getSdkEnvironment(
classLoaderConfig, sdkConfig, useLegacyResources);
} catch (Throwable e) {
throw new AssumptionViolatedException("Failed to create a Robolectric sandbox", e);
}
} else {
return ctx.sandboxFactory.getSdkEnvironment(
classLoaderConfig, sdkConfig, useLegacyResources);
}
}
@Override
protected void beforeTest(Sandbox sandbox, FrameworkMethod method, Method bootstrappedMethod) throws Throwable {
SdkEnvironment sdkEnvironment = (SdkEnvironment) sandbox;
RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) method;
PerfStatsCollector perfStatsCollector = PerfStatsCollector.getInstance();
SdkConfig sdkConfig = roboMethod.sdkConfig;
perfStatsCollector.putMetadata(
AndroidMetadata.class,
new AndroidMetadata(
ImmutableMap.of("ro.build.version.sdk", "" + sdkConfig.getApiLevel()),
roboMethod.resourcesMode.name()));
System.out.println(
"[Robolectric] " + roboMethod.getDeclaringClass().getName() + "."
+ roboMethod.getMethod().getName() + ": sdk=" + sdkConfig.getApiLevel()
+ "; resources=" + roboMethod.resourcesMode);
if (roboMethod.resourcesMode == ResourcesMode.legacy) {
System.out.println(
"[Robolectric] NOTICE: legacy resources mode is deprecated; see http://robolectric.org/migrating/#migrating-to-40");
}
roboMethod.parallelUniverseInterface = getHooksInterface(sdkEnvironment);
Class<TestLifecycle> cl = sdkEnvironment.bootstrappedClass(getTestLifecycleClass());
roboMethod.testLifecycle = ReflectionHelpers.newInstance(cl);
providers = ServiceLoader.load(ShadowProvider.class, sdkEnvironment.getRobolectricClassLoader());
roboMethod.parallelUniverseInterface.setSdkConfig(sdkConfig);
AndroidManifest appManifest = roboMethod.getAppManifest();
roboMethod.parallelUniverseInterface.setUpApplicationState(
ctx.apkLoader,
bootstrappedMethod,
roboMethod.config, appManifest,
sdkEnvironment
);
roboMethod.testLifecycle.beforeTest(bootstrappedMethod);
}
@Override
protected void afterTest(FrameworkMethod method, Method bootstrappedMethod) {
RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) method;
try {
roboMethod.parallelUniverseInterface.tearDownApplication();
} finally {
internalAfterTest(method, bootstrappedMethod);
}
}
private void resetStaticState() {
if (providers != null) {
for (ShadowProvider provider : providers) {
provider.reset();
}
}
}
@Override
protected void finallyAfterTest(FrameworkMethod method) {
// If the test was interrupted, it will interfere with new AbstractInterruptibleChannels in
if (Thread.interrupted()) {
System.out.println("WARNING: Test thread was interrupted! " + method.toString());
}
try {
// reset static state afterward too, so statics don't defeat GC?
PerfStatsCollector.getInstance()
.measure("reset Android state (after test)", this::resetStaticState);
} finally {
RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) method;
roboMethod.testLifecycle = null;
roboMethod.parallelUniverseInterface = null;
}
}
@Override protected SandboxTestRunner.HelperTestRunner getHelperTestRunner(Class bootstrappedTestClass) {
try {
return new HelperTestRunner(bootstrappedTestClass);
} catch (InitializationError initializationError) {
throw new RuntimeException(initializationError);
}
}
/**
* Detects which build system is in use and returns the appropriate ManifestFactory implementation.
*
* Custom TestRunner subclasses may wish to override this method to provide alternate configuration.
*
* @param config Specification of the SDK version, manifest file, package name, etc.
*/
protected ManifestFactory getManifestFactory(Config config) {
Properties buildSystemApiProperties = getBuildSystemApiProperties();
if (buildSystemApiProperties != null) {
return new DefaultManifestFactory(buildSystemApiProperties);
}
if (BuckManifestFactory.isBuck()) {
return new BuckManifestFactory();
} else {
return new MavenManifestFactory();
}
}
protected Properties getBuildSystemApiProperties() {
InputStream resourceAsStream = getClass().getResourceAsStream("/com/android/tools/test_config.properties");
if (resourceAsStream == null) {
return null;
}
try {
Properties properties = new Properties();
properties.load(resourceAsStream);
return properties;
} catch (IOException e) {
return null;
} finally {
try {
resourceAsStream.close();
} catch (IOException e) {
// ignore
}
}
}
private AndroidManifest getAppManifest(Config config) {
ManifestFactory manifestFactory = getManifestFactory(config);
ManifestIdentifier identifier = manifestFactory.identify(config);
return cachedCreateAppManifest(identifier);
}
private AndroidManifest cachedCreateAppManifest(ManifestIdentifier identifier) {
synchronized (appManifestsCache) {
AndroidManifest appManifest;
appManifest = appManifestsCache.get(identifier);
if (appManifest == null) {
appManifest = createAndroidManifest(identifier);
appManifestsCache.put(identifier, appManifest);
}
return appManifest;
}
}
/**
* Internal use only.
* @deprecated Do not use.
*/
@Deprecated
@VisibleForTesting
public static AndroidManifest createAndroidManifest(ManifestIdentifier manifestIdentifier) {
List<ManifestIdentifier> libraries = manifestIdentifier.getLibraries();
List<AndroidManifest> libraryManifests = new ArrayList<>();
for (ManifestIdentifier library : libraries) {
libraryManifests.add(createAndroidManifest(library));
}
return new AndroidManifest(manifestIdentifier.getManifestFile(), manifestIdentifier.getResDir(),
manifestIdentifier.getAssetDir(), libraryManifests, manifestIdentifier.getPackageName(),
manifestIdentifier.getApkFile());
}
/**
* Compute the effective Robolectric configuration for a given test method.
*
* Configuration information is collected from package-level <tt>robolectric.properties</tt> files
* and {@link Config} annotations on test classes, superclasses, and methods.
*
* Custom TestRunner subclasses may wish to override this method to provide alternate configuration.
*
* @param method the test method
* @return the effective Robolectric configuration for the given test method
* @since 2.0
*/
public Config getConfig(Method method) {
return ctx.configMerger.getConfig(getTestClass().getJavaClass(), method, buildGlobalConfig());
}
/**
* Provides the base Robolectric configuration {@link Config} used for all tests.
*
* Configuration provided for specific packages, test classes, and test method
* configurations will override values provided here.
*
* Custom TestRunner subclasses may wish to override this method to provide
* alternate configuration. Consider using a {@link Config.Builder}.
*
* The default implementation has appropriate values for most use cases.
*
* @return global {@link Config} object
* @since 3.1.3
*/
protected Config buildGlobalConfig() {
return new Config.Builder().build();
}
@Override @Nonnull
protected Class<?>[] getExtraShadows(FrameworkMethod frameworkMethod) {
Config config = ((RobolectricFrameworkMethod) frameworkMethod).config;
return config.shadows();
}
ParallelUniverseInterface getHooksInterface(SdkEnvironment sdkEnvironment) {
ClassLoader robolectricClassLoader = sdkEnvironment.getRobolectricClassLoader();
try {
Class<?> clazz = robolectricClassLoader.loadClass(ParallelUniverse.class.getName());
Class<? extends ParallelUniverseInterface> typedClazz = clazz.asSubclass(ParallelUniverseInterface.class);
Constructor<? extends ParallelUniverseInterface> constructor = typedClazz.getConstructor();
return constructor.newInstance();
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
protected void internalAfterTest(FrameworkMethod frameworkMethod, Method method) {
RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) frameworkMethod;
roboMethod.testLifecycle.afterTest(method);
}
@Override
protected void afterClass() {
}
@Override
public Object createTest() throws Exception {
throw new UnsupportedOperationException("this should always be invoked on the HelperTestRunner!");
}
@VisibleForTesting
ResourcesMode getResourcesMode() {
return ResourcesMode.getFromProperties();
}
public static class HelperTestRunner extends SandboxTestRunner.HelperTestRunner {
public HelperTestRunner(Class bootstrappedTestClass) throws InitializationError {
super(bootstrappedTestClass);
}
@Override protected Object createTest() throws Exception {
Object test = super.createTest();
RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) this.frameworkMethod;
roboMethod.testLifecycle.prepareTest(test);
return test;
}
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
final Statement invoker = super.methodInvoker(method, test);
final RobolectricFrameworkMethod roboMethod = (RobolectricFrameworkMethod) this.frameworkMethod;
return new Statement() {
@Override
public void evaluate() throws Throwable {
Thread orig = roboMethod.parallelUniverseInterface.getMainThread();
roboMethod.parallelUniverseInterface.setMainThread(Thread.currentThread());
try {
invoker.evaluate();
} finally {
roboMethod.parallelUniverseInterface.setMainThread(orig);
}
}
};
}
}
static class RobolectricFrameworkMethod extends FrameworkMethod {
private final @Nonnull AndroidManifest appManifest;
final @Nonnull SdkConfig sdkConfig;
final @Nonnull Config config;
final ResourcesMode resourcesMode;
private final ResourcesMode defaultResourcesMode;
private final boolean alwaysIncludeVariantMarkersInName;
private boolean includeVariantMarkersInTestName = true;
TestLifecycle testLifecycle;
ParallelUniverseInterface parallelUniverseInterface;
RobolectricFrameworkMethod(
@Nonnull Method method,
@Nonnull AndroidManifest appManifest,
@Nonnull SdkConfig sdkConfig,
@Nonnull Config config,
ResourcesMode resourcesMode,
ResourcesMode defaultResourcesMode,
boolean alwaysIncludeVariantMarkersInName) {
super(method);
this.appManifest = appManifest;
this.sdkConfig = sdkConfig;
this.config = config;
this.resourcesMode = resourcesMode;
this.defaultResourcesMode = defaultResourcesMode;
this.alwaysIncludeVariantMarkersInName = alwaysIncludeVariantMarkersInName;
}
@Override
public String getName() {
// IDE focused test runs rely on preservation of the test name; we'll use the
// latest supported SDK for focused test runs
StringBuilder buf = new StringBuilder(super.getName());
if (includeVariantMarkersInTestName || alwaysIncludeVariantMarkersInName) {
buf.append("[").append(sdkConfig.getApiLevel()).append("]");
if (defaultResourcesMode == ResourcesMode.both) {
buf.append("[").append(resourcesMode.name()).append("]");
}
}
return buf.toString();
}
void dontIncludeVariantMarkersInTestName() {
includeVariantMarkersInTestName = false;
}
@Nonnull
AndroidManifest getAppManifest() {
return appManifest;
}
public boolean isLegacy() {
return resourcesMode == ResourcesMode.legacy;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
RobolectricFrameworkMethod that = (RobolectricFrameworkMethod) o;
return sdkConfig.equals(that.sdkConfig) && resourcesMode == that.resourcesMode;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + sdkConfig.hashCode();
result = 31 * result + resourcesMode.ordinal();
return result;
}
@Override
public String toString() {
return getName();
}
}
} |
package org.netsec.iottestbed.nonembedded;
import java.net.*;
import java.util.concurrent.Executors;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.EndpointManager;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.netsec.iottestbed.nonembedded.resources.NetsecResource;
import org.netsec.iottestbed.nonembedded.resources.actuators.Actuator;
import org.netsec.iottestbed.nonembedded.resources.sensors.Sensor;
class AdvertisingRunnable implements Runnable {
private CoapClient _advertisingClient = new CoapClient();
private URI _broadcastURI;
private String _adString;
AdvertisingRunnable(String adString){
//String uriString = "coap://[ff02::1]:6666/devices";
String uriString = "coap://localhost:6666/devices";
try {
_broadcastURI = new URI(uriString);
} catch (URISyntaxException e) {
System.err.println("Invalid URI: " + e.getMessage());
System.exit(-1);
}
_adString = adString;
_advertisingClient = new CoapClient(_broadcastURI);
}
public void run() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println(_adString);
_advertisingClient.put(_adString, 0);
}
}
}
class Server extends CoapServer {
private static final int COAP_PORT = NetworkConfig.getStandard().getInt(NetworkConfig.Keys.COAP_PORT);
private String _adString = "";
private Server() {
addEndpoints();
}
private void advertise() {
(new Thread(new AdvertisingRunnable(_adString))).start();
}
private void addEndpoints() {
// IPv4 and IPv6 addresses and localhost
InetAddress multicastAddr = null;
try {
multicastAddr = InetAddress.getByName("FF05::FD");
} catch (UnknownHostException e) {
e.printStackTrace();
}
InetSocketAddress multicastBindToAddress = new InetSocketAddress(multicastAddr, COAP_PORT);
CoapEndpoint multicast = new CoapEndpoint(multicastBindToAddress);
super.addEndpoint(multicast);
for (InetAddress addr : EndpointManager.getEndpointManager().getNetworkInterfaces()) {
if (addr instanceof Inet6Address || addr instanceof Inet4Address || addr.isLoopbackAddress()) {
InetSocketAddress bindToAddress = new InetSocketAddress(addr, COAP_PORT);
addEndpoint(new CoapEndpoint(bindToAddress));
}
}
}
private void add(NetsecResource resource) {
super.add(resource);
for (String path: resource.getSubPaths()) {
_adString += path + ",";
}
}
public void start() {
super.start();
advertise();
}
public static void main(String[] args) throws Exception {
Server server = new Server();
server.setExecutor(Executors.newScheduledThreadPool(4));
server.add(new Sensor());
server.add(new Actuator());
server.start();
}
} |
package exm.stc.ic.opt.valuenumber;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import exm.stc.common.Logging;
import exm.stc.common.exceptions.STCRuntimeError;
import exm.stc.common.lang.Arg;
import exm.stc.common.lang.Var;
import exm.stc.common.lang.Var.Alloc;
import exm.stc.common.util.HierarchicalSet;
import exm.stc.common.util.TernaryLogic.Ternary;
import exm.stc.ic.opt.InitVariables.InitState;
import exm.stc.ic.opt.valuenumber.ClosedVarTracker.AliasFinder;
import exm.stc.ic.opt.valuenumber.ClosedVarTracker.ClosedEntry;
import exm.stc.ic.opt.valuenumber.ComputedValue.ArgCV;
import exm.stc.ic.opt.valuenumber.ComputedValue.ArgOrCV;
import exm.stc.ic.opt.valuenumber.ComputedValue.CongruenceType;
import exm.stc.ic.opt.valuenumber.ValLoc.Closed;
import exm.stc.ic.opt.valuenumber.ValLoc.IsAssign;
import exm.stc.ic.tree.ICTree.GlobalConstants;
import exm.stc.ic.tree.ICTree.RenameMode;
import exm.stc.ic.tree.Opcode;
/**
* Track which variables/values are congruent with each other
* In particular, track which is the "canonical" version to use.
* Looking up a variable in the map will give you back the canonical
* congruent variable.
*
* We have two notions of congruence: by-value (reading results in same thing),
* and by-alias (reading & writing results in same effect).
*
* This module uses a notion of "Congruence Set", which contains
* all values known to be congruent to each other, to allow
* accurate tracking of congruence relationship. We retain
* enough info to answer these kinds of questions:
*
* - Given a ComputedValue or Arg, what congruence set is it in?
* (by value/by alias)?
* - Given a (by alias or by value) congruence set, what is
* the canonical Arg?
* - Given a Var in a REFERENCE/VALUE context, what should we
* replace it with, if anything?
*
* The notion of by-value congruence can't totally disregard whether a
* variable is mapped: we can only have one mapped variable in each
* congruence set, and it must be the canonical member
*
* TODO: get arithmetic logic to rerun upon change
* TODO: inconsistent sets in child after canonicalization
* -> When we're doing the first walk over the tree, this def.
* shouldn't happen
* -> When we're doing the replacement walk, it isn't necessarily a problem:
* maybe just need to re-lookup canonical to make sure it wasn't
* recanonicalized.
*/
public class Congruences implements AliasFinder {
private final Logger logger;
private final GlobalConstants consts;
@SuppressWarnings("unused")
private final Congruences parent;
private final ClosedVarTracker track;
private final CongruentSets byValue;
private final CongruentSets byAlias;
private final HierarchicalSet<List<Arg>> maybeAssigned;
private final boolean reorderingAllowed;
private Congruences(Logger logger,
GlobalConstants consts,
Congruences parent,
ClosedVarTracker track,
CongruentSets byValue,
CongruentSets byAlias,
HierarchicalSet<List<Arg>> maybeAssigned,
boolean reorderingAllowed) {
this.logger = logger;
this.consts = consts;
this.parent = parent;
this.track = track;
this.byValue = byValue;
this.byAlias = byAlias;
this.maybeAssigned = maybeAssigned;
this.reorderingAllowed = reorderingAllowed;
}
public Congruences(Logger logger, GlobalConstants consts,
boolean reorderingAllowed) {
this(logger, consts, null,
ClosedVarTracker.makeRoot(logger, reorderingAllowed),
CongruentSets.makeRoot(CongruenceType.VALUE),
CongruentSets.makeRoot(CongruenceType.ALIAS),
new HierarchicalSet<List<Arg>>(),
reorderingAllowed);
}
public Congruences enterContBlock(boolean varsFromParent,
int parentStmtIndex) {
Congruences child = new Congruences(logger, consts, this,
track.enterContinuation(parentStmtIndex),
byValue.makeChild(varsFromParent),
byAlias.makeChild(varsFromParent),
maybeAssigned.makeChild(), reorderingAllowed);
/*
* TODO: how to handle difference between information that is shared
* between inner/outer scopes. E.g.
* - Congruences are valid inside and outside of wait
* - Except considering obstructions to variable passing:
* ->> consider handling this in replacement walk, by
* iterating over alternatives
* - Closed info is sensitive to execution order: need to create new
* one per state
*/
return child;
}
public void update(GlobalConstants consts, String errContext,
ValLoc resVal, int stmtIndex) throws OptUnsafeError {
if (logger.isTraceEnabled()) {
logger.trace("update: " + resVal + " " + resVal.congType());
}
if (resVal.congType() == CongruenceType.ALIAS) {
// Update aliases only if congType matches
update(consts, errContext, resVal.location(), resVal.value(),
resVal.isAssign(), byAlias, true, stmtIndex);
} else {
assert(resVal.congType() == CongruenceType.VALUE);
}
/*
* After alias updates, mark arg as closed, so that closedness
* is propagated to all in set. Do this before updating value
* congruence so that we can pick a closed variable to represent
* the value if possible.
*/
markClosed(resVal.location(), stmtIndex, resVal.locClosed());
// Both alias and value links result in updates to value
update(consts, errContext, resVal.location(), resVal.value(),
resVal.isAssign(), byValue, true, stmtIndex);
// Check assignment after all other updates, so that any
// contradictions get propagated correctly
markAssigned(errContext, consts, resVal);
}
/**
* Update a congruentSet with the information that value is stored
* in location
* @param consts Global constants to add canonical vals if needed
* @param errContext
* @param location
* @param value
* @param isAssign YES if value represents a single-assignment location
* and location is the thing stored to that location
* @param congruent
* @param addConsequential
* @throws OptUnsafeError
*/
private void update(GlobalConstants consts, String errContext,
Arg location, ArgCV value, IsAssign isAssign,
CongruentSets congruent, boolean addConsequential, int stmtIndex)
throws OptUnsafeError {
// LocCV may already be in congruent set
Arg canonLoc = congruent.findCanonical(location);
// Canonicalize value based on existing congruences
ArgOrCV canonVal = congruent.canonicalize(consts, value);
// Check if value is already associated with a location
Arg canonLocFromVal = congruent.findCanonicalInternal(canonVal);
if (canonLocFromVal == null) {
// Handle case where value not congruent to anything yet.
// Just add val to arg's set
congruent.addToSet(consts, canonVal, canonLoc);
} else {
// Need to merge together two existing sets
mergeSets(errContext, canonVal, consts, congruent,
canonLocFromVal, canonLoc, isAssign, stmtIndex);
}
if (addConsequential) {
addInverses(consts, errContext, canonLoc, canonVal, stmtIndex);
addInferred(consts, errContext, congruent, stmtIndex, canonLoc, canonVal);
}
}
private CongruentSets getCongruentSet(CongruenceType congType) {
if (congType == CongruenceType.VALUE) {
return byValue;
} else {
assert(congType == CongruenceType.ALIAS);
return byAlias;
}
}
/**
* Add any inverse operations that can be directly inferred from
* a value that was just added
* @param errContext
* @param canonLoc
* @param canonVal
* @throws OptUnsafeError
*/
private void addInverses(GlobalConstants consts, String errContext,
Arg canonLoc, ArgOrCV canonVal, int stmtIndex)
throws OptUnsafeError {
if (canonVal.isCV() && canonVal.cv().inputs.size() == 1) {
ComputedValue<Arg> cv = canonVal.cv();
Arg invOutput = cv.getInput(0);
// Only add value congruences to be safe.
// It might be possible to handle ALIAS congruences, e.g. for
// STORE_REF/LOAD_REF pair here later on (TODO)
if (cv.op().isAssign()) {
ArgCV invVal = ComputedValue.retrieveCompVal(canonLoc.getVar());
updateInv(consts, errContext, invOutput, invVal, stmtIndex);
} else if (cv.op().isRetrieve()) {
Opcode invOp = Opcode.assignOpcode(invOutput.getVar());
assert(invOp != null);
ArgCV invVal = new ArgCV(invOp, canonLoc.asList());
updateInv(consts, errContext, invOutput, invVal, stmtIndex);
}
} else if (canonVal.isArg() && canonVal.arg().isVar() &&
canonVal.arg().getVar().storage() == Alloc.GLOBAL_CONST) {
// Add value for retrieval of global
Var globalConst = canonVal.arg().getVar();
Arg constVal = consts.lookupByVar(globalConst);
assert(constVal != null);
ArgCV invVal = ComputedValue.retrieveCompVal(globalConst);
updateInv(consts, errContext, constVal, invVal, stmtIndex);
}
}
private void addInferred(GlobalConstants consts, String errContext,
CongruentSets congruent, int stmtIndex, Arg canonLoc, ArgOrCV canonVal)
throws OptUnsafeError {
if (canonVal.isCV()) {
for (ArgCV extra: Algebra.tryAlgebra(this, canonVal.cv())) {
update(consts, errContext, canonLoc, extra, IsAssign.NO,
congruent, false, stmtIndex);
}
}
}
private void updateInv(GlobalConstants consts, String errContext,
Arg invOutput, ArgCV invVal, int stmtIndex)
throws OptUnsafeError {
CongruentSets valCong = getCongruentSet(CongruenceType.VALUE);
update(consts, errContext, invOutput, invVal, IsAssign.NO,
valCong, false, stmtIndex);
}
/**
* Merge two congruence sets that are newly connected via value
* @param errContext
* @param resVal
* @param congruent
* @param newLoc representative of set with location just maybeAssigned
* @param oldLoc representative of existing set
* @throws OptUnsafeError
*/
private void mergeSets(String errContext, ArgOrCV value,
GlobalConstants consts, CongruentSets congruent,
Arg oldLoc, Arg newLoc, IsAssign newIsAssign, int stmtIndex) throws OptUnsafeError {
if (newLoc.equals(oldLoc)) {
// Already merged
return;
}
checkNoContradiction(errContext, congruent.congType,
value, newLoc, oldLoc);
// Must merge. Select which is the preferred value
// (for replacement purposes, etc.)
Arg winner = preferred(congruent, oldLoc, newLoc, newIsAssign, stmtIndex);
Arg loser = (winner == oldLoc ? newLoc : oldLoc);
if (logger.isTraceEnabled()) {
logger.trace("old: " + oldLoc + " vs. new: " + newLoc +
" winner: " + winner);
}
changeCanonical(consts, congruent, loser, winner);
}
/**
* Helper function to update CongruentSets plus any other info
* @param congruent
* @param locCV
* @param canonicalFromVal
*/
private void changeCanonical(GlobalConstants consts,
CongruentSets congruent, Arg oldVal, Arg newVal) {
assert(!oldVal.equals(newVal));
if (congruent.congType == CongruenceType.VALUE) {
// Two mapped variables with same value aren't interchangeable: abort!
if (oldVal.isMapped() != Ternary.FALSE) {
return;
}
}
congruent.changeCanonical(consts, oldVal, newVal);
}
/**
* Check if vals contradict each other.
* @param errContext
* @param congType
* @param value
* @param val1
* @param val2
* @throw {@link OptUnsafeError} if problem found
*/
private void checkNoContradiction(String errContext,
CongruenceType congType, ArgOrCV value, Arg val1, Arg val2)
throws OptUnsafeError {
boolean contradiction = false;
if (congType == CongruenceType.VALUE) {
if (val1.isConstant() && val2.isConstant() && !val1.equals(val2)) {
contradiction = true;
}
} else {
assert(congType == CongruenceType.ALIAS);
assert(val1.isVar() && val2.isVar());
if (val1.getVar().storage() != Alloc.ALIAS &&
val2.getVar().storage() != Alloc.ALIAS &&
!val1.getVar().equals(val2.getVar())) {
contradiction = true;
}
}
if (contradiction) {
Logging.uniqueWarn("Invalid code detected during optimization. "
+ "Conflicting values for " + value + ": " + val1 +
" != " + val2 + " in " + errContext + ".\n"
+ "This may have been caused by a double-write to a variable. "
+ "Please look at any previous warnings emitted by compiler. "
+ "Otherwise this could indicate a stc bug");
throw new OptUnsafeError();
}
}
/**
* Check which arg is preferred as the replacement.
*
* Note that this ordering is important for correctness. If we replace
* a closed var with a non-closed var, we may produce incorrect results.
* @param track
* @param congType
* @param oldArg current one
* @param newArg oldOne
* @return the preferred of the two args
*/
private Arg preferred(CongruentSets congruent,
Arg oldArg, Arg newArg, IsAssign newIsAssign, int stmtIndex) {
if (congruent.congType == CongruenceType.VALUE) {
// Constants trump all
if (isConst(oldArg)) {
return oldArg;
} else if (isConst(newArg)) {
return newArg;
}
/*
* If newArg was stored directly to the location, doesn't make
* sense to substitute. In some cases this could result in a
* bad substitution creating a circular dependency. We handle
* the situation where double-assignment occurs separately: a
* double-assignment tends to be an error and we disable optimization
* more aggressively in those cases.
*/
if (newIsAssign == IsAssign.TO_VALUE) {
return newArg;
}
} else {
assert(congruent.congType == CongruenceType.ALIAS);
assert(oldArg.isVar() && newArg.isVar());
// Shouldn't have alias equivalence on values
// Prefer non-alias (i.e. direct handle)
if (oldArg.getVar().storage() != Alloc.ALIAS) {
return oldArg;
} else if (newArg.getVar().storage() != Alloc.ALIAS){
return newArg;
}
}
// Check if accessible (based on passability).
// Assume new one is accessible
if (!congruent.isAccessible(oldArg.getVar())) {
return newArg;
}
// Prefer closed
if (congruent.congType == CongruenceType.VALUE) {
// Check if this gives us a reason to prefer newArg
if (isRecClosed(newArg.getVar(), stmtIndex) &&
!isRecClosed(oldArg.getVar(), stmtIndex)) {
return newArg;
} else if (isClosed(newArg.getVar(), stmtIndex)
&& !isClosed(oldArg.getVar(), stmtIndex)) {
return newArg;
}
}
// otherwise keep old arg
return oldArg;
}
/**
* Check if argument is a value or future constant
* @param arg
* @return
*/
static boolean isConst(Arg arg) {
return arg.isConstant() ||
(arg.isVar() && arg.getVar().storage() == Alloc.GLOBAL_CONST);
}
private Var getCanonicalAlias(Arg varArg) {
assert(varArg.isVar()) : varArg;
Arg canonical = byAlias.findCanonical(varArg);
assert(canonical.isVar()) : "Should only have a variable as" +
" canonical member in ALIAS congruence relationship";
return canonical.getVar();
}
/**
*
* @param canonLoc CV representing a single assignment location
* @param assign
* @throws OptUnsafeError
*/
private void markAssigned(String errContext, GlobalConstants consts,
ValLoc vl) throws OptUnsafeError {
List<Arg> assigned;
if (vl.isAssign() == IsAssign.NO) {
return;
} else if (vl.isAssign() == IsAssign.TO_LOCATION) {
Arg location = vl.location();
assert(location.isVar()) : "Can't assign constant: " + location;
assigned = Collections.singletonList(location);
} else {
assert(vl.isAssign() == IsAssign.TO_VALUE);
assigned = canonicalizeAssignValue(consts, vl.value());
}
if (maybeAssigned.contains(assigned)) {
// Potential double assignment: avoid doing any optimizations on
// the contents of this location.
logger.debug("Potential double assignment to " + assigned);
Logging.uniqueWarn("Invalid code detected during optimization. "
+ "Double assignment to " + printableAssignValue(assigned) + " in " + errContext + ".\n"
+ "This may have been caused by a double-write to a variable. "
+ "Please look at any previous warnings emitted by compiler. "
+ "Otherwise this could indicate a stc bug");
throw new OptUnsafeError();
}
if (logger.isTraceEnabled()) {
logger.trace("First assignment to " + assigned);
}
maybeAssigned.add(assigned);
// TODO: will need to unify stored state
// TODO: will need to merge maybeAssigned info upon congruence merges.
// E.g. if A[x], A[y] are stored and we find out that x == y
}
/**
* User friendly string for location.
* @param assigned
* @return
*/
private String printableAssignValue(List<Arg> assigned) {
assert(assigned.size() > 0);
StringBuilder sb = new StringBuilder();
sb.append(assigned.get(0).toString());
for (Arg arg: assigned.subList(1, assigned.size())) {
sb.append("[" + arg + "]");
}
return sb.toString();
}
private List<Arg> canonicalizeAssignValue(GlobalConstants consts,
ArgCV val) {
// Canonicalize location as appropriate
// (e.g. root var by alias and subscripts by value)
// TODO: will need to recanonicalize?
if (val.isArrayMember() || val.isArrayMemberRef()) {
Arg arr = byAlias.findCanonical(val.getInput(0));
Arg ix = byValue.findCanonical(val.getInput(1));
return Arrays.asList(arr, ix);
} else if (val.op == Opcode.GET_FILENAME_VAL) {
return Arrays.asList(Arg.createStringLit("filename"),
byAlias.findCanonical(val.getInput(0)));
} else {
throw new STCRuntimeError("Don't know how to canonicalize " +
val + " for assignment value tracking");
}
}
public void markClosed(Var var, int stmtIndex, boolean recursive) {
markClosed(var, false, stmtIndex, recursive);
}
public void markClosedBlockStart(Var var, boolean recursive) {
markClosed(var, true, -1, recursive);
}
private void markClosed(Var var, boolean blockStart, int stmtIndex, boolean recursive) {
if (!trackClosed(var)) {
// Don't bother tracking this info: not actually closed
return;
}
Var canonical = getCanonicalAlias(var.asArg());
if (blockStart) {
track.closeBlockStart(canonical, recursive);
} else {
track.close(canonical, stmtIndex, recursive);
}
}
/**
* Update data structures to reflect that location is closed
* @param track
* @param closed
* @param resVal
*/
private void markClosed(Arg location, int stmtIndex, Closed closed) {
if (closed != Closed.MAYBE_NOT && location.isVar()) {
// Mark the canonical version of the variable closed
if (closed == Closed.YES_NOT_RECURSIVE) {
markClosed(location.getVar(), stmtIndex, false);
} else {
assert(closed == Closed.YES_RECURSIVE);
markClosed(location.getVar(), stmtIndex, true);
}
}
}
public boolean isClosed(Var var, int stmtIndex) {
return isClosed(var.asArg(), stmtIndex);
}
public boolean isClosed(Arg varArg, int stmtIndex) {
return isClosed(varArg, stmtIndex, false);
}
public boolean isRecClosed(Var var, int stmtIndex) {
return isRecClosed(var.asArg(), stmtIndex);
}
public boolean isRecClosed(Arg varArg, int stmtIndex) {
return isClosed(varArg, stmtIndex, true);
}
/**
* Check if variable is closed before a given statement starts executing
* @param varArg
* @param stmtIndex
* @param recursive
* @return
*/
private boolean isClosed(Arg varArg, int stmtIndex, boolean recursive) {
// Find canonical var for alias, and check if that is closed.
if (varArg.isConstant() || !trackClosed(varArg.getVar())) {
// No write refcount - always closed
logger.trace(varArg + " has no refcount");
return true;
}
Var canonicalAlias = getCanonicalAlias(varArg);
ClosedEntry ce;
ce = track.getClosedEntry(canonicalAlias, recursive, stmtIndex, this);
if (logger.isTraceEnabled()) {
logger.trace("Closed " + varArg + "(" + canonicalAlias + "): " + ce);
}
if (ce != null) {
// Mark as closed to avoid having to trace back again like this.
track.close(canonicalAlias, ce);
if (ce.matches(recursive, stmtIndex)) {
logger.trace(varArg + "/" + canonicalAlias + " closed @ "
+ ce.stmtIndex);
return true;
}
}
return false;
}
/**
* Whether we should track closed status for this var
* @param var
* @return
*/
private boolean trackClosed(Var var) {
return var.storage() != Alloc.LOCAL &&
var.storage() != Alloc.GLOBAL_CONST;
}
public Set<Var> getClosed(int stmtIndex) {
return new ClosedSet(stmtIndex, false);
}
public Set<Var> getRecursivelyClosed(int stmtIndex) {
return new ClosedSet(stmtIndex, true);
}
/**
* Return set of vars that were closed in this scope but
* not in parent scopes
* @param recursiveOnly
* @return
*/
public Set<Var> getScopeClosed(boolean recursiveOnly) {
// Get variables that can be inferred to be closed
Set<Var> nonAlias = track.getScopeClosed(recursiveOnly);
// In parent scope, some alias sets that might be merged. Add in
// a representative that was merged into the closed set. We know
// that each var returned by getScopeClosed was at some point in this
// block. By backtrakcing through merges that happened in this block,
// we can find the canonical representatives of all set in the parent
// block.
// As optimization, only create new set on demand
Set<Var> expanded = null;
for (Var closed: nonAlias) {
for (Arg merged: byAlias.mergedCanonicalsThisScope(closed.asArg())) {
assert(merged.isVar());
if (expanded == null) {
// Copy to new set
expanded = new HashSet<Var>();
expanded.addAll(nonAlias);
}
expanded.add(merged.getVar());
}
}
if (expanded != null) {
return expanded;
} else {
return nonAlias;
}
}
/**
* @param mode
* @param init
* @return replacements in effect for given rename mode
*/
public Map<Var, Arg> replacements(RenameMode mode, InitState init) {
if (mode == RenameMode.VALUE) {
return byValue.getReplacementMap(init);
} else {
assert(mode == RenameMode.REFERENCE);
return byAlias.getReplacementMap(init);
}
}
public void printTraceInfo(Logger logger, GlobalConstants consts) {
logger.trace("State dump for " + System.identityHashCode(this));
byAlias.printTraceInfo(logger, consts);
byValue.printTraceInfo(logger, consts);
track.printTraceInfo(logger);
}
/**
* Do any internal validations
*/
public void validate(GlobalConstants consts) {
byAlias.validate(consts);
byValue.validate(consts);
}
/**
* See if the result of a value retrieval is already in scope
* Returns nothing if contradiction found!
* @param v
* @return
*/
public Arg findRetrieveResult(Var v) {
return byValue.findRetrieveResult(v.asArg());
}
public Arg findValue(Var output) {
return byValue.findCanonical(output.asArg());
}
/**
* @return canonical location for given value, null if not stored anywhere
*/
public Arg findCanonical(ArgCV val, CongruenceType congType) {
return getCongruentSet(congType).findCanonical(consts, val);
}
public boolean isAvailable(ArgCV val, CongruenceType congType) {
return findCanonical(val, congType) != null;
}
public List<ArgOrCV> findCongruent(Arg arg, CongruenceType congType) {
return getCongruentSet(congType).findCongruentValues(arg);
}
public List<Var> getAliasesOf(Var var) {
List<Var> result = new ArrayList<Var>();
Arg canonical = byAlias.findCanonical(var.asArg());
if (canonical.isVar()) {
result.add(canonical.getVar());
}
for (Arg alias: byAlias.allMergedCanonicals(canonical)) {
if (alias.isVar()) {
result.add(alias.getVar());
}
}
return result;
}
public void addUnifiedValues(GlobalConstants consts, String errContext,
int stmtIndex, UnifiedValues unified)
throws OptUnsafeError {
// TODO: need to refine this merge to compensate for sets being
// named differently in child
for (Var closed: unified.closed) {
markClosed(closed, stmtIndex, false);
}
for (Var closed: unified.recursivelyClosed) {
markClosed(closed, stmtIndex, true);
}
for (ValLoc loc: unified.availableVals) {
update(consts, errContext, loc, stmtIndex);
}
}
/**
* Return iterator over values that are defined only in the
* current scope (ignore outer scopes)
* @param congType
* @return
*/
public Iterable<ArgOrCV> availableThisScope(CongruenceType congType) {
return getCongruentSet(congType).availableThisScope();
}
/**
* Convert from ArgOrCV into ArgCV implementation
* @param val
* @param congType
* @return
*/
public ArgCV convertToArgs(ArgOrCV val, CongruenceType congType) {
if (val.isArg()) {
if (congType == CongruenceType.VALUE) {
return ComputedValue.makeCopy(val.arg());
} else {
assert(congType == CongruenceType.ALIAS);
return ComputedValue.makeAlias(val.arg());
}
} else {
assert(val.isCV());
return val.cv();
}
}
/**
* Add in closedness dependency: if to is closed, implies
* from is closed
* @param to
* @param fromVars
* TODO: this information can be propagated up the IR tree, since if
* A -> B in a wait statement, this implies that in any parent
* blocks, that if B is set, then A is set (assuming no
* contradictions)
*/
public void setDependencies(Var to, List<Var> fromVars) {
Var toCanon = getCanonicalAlias(to.asArg());
for (Var fromVar: fromVars) {
Var fromCanon = getCanonicalAlias(fromVar.asArg());
track.setDependency(toCanon, fromCanon);
}
}
/**
* Implement set interface for checking if var is closed
*/
private class ClosedSet extends AbstractSet<Var> {
ClosedSet(int stmtIndex, boolean recursive) {
this.stmtIndex = stmtIndex;
this.recursive = recursive;
}
private final int stmtIndex;
private final boolean recursive;
@Override
public boolean contains(Object o) {
assert(o instanceof Var);
Var v = (Var)o;
if (recursive) {
return isRecClosed(v, stmtIndex);
} else {
return isClosed(v, stmtIndex);
}
}
@Override
public Iterator<Var> iterator() {
throw new STCRuntimeError("iterator() not supported");
}
@Override
public int size() {
throw new STCRuntimeError("size() not supported");
}
}
static class OptUnsafeError extends Exception {
private static final long serialVersionUID = 1L;
/**
* Don't have message: should log problem before throwing exception
*/
OptUnsafeError() {
super();
}
}
} |
package de.saumya.mojo.rspec;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.FileUtils;
import de.saumya.mojo.ruby.script.Script;
import de.saumya.mojo.ruby.script.ScriptException;
import de.saumya.mojo.tests.AbstractTestMojo;
import de.saumya.mojo.tests.JRubyRun.Mode;
import de.saumya.mojo.tests.JRubyRun.Result;
import de.saumya.mojo.tests.TestScriptFactory;
/**
* executes the jruby command.
*
* @goal test
* @phase test
* @requiresDependencyResolution test
*/
public class RSpecMojo extends AbstractTestMojo {
/**
* arguments for the rspec command. <br/>
* Command line -Drspec.args=...
*
* @parameter expression="${rspec.args}"
*/
private final String rspecArgs = null;
/**
* The directory containing the RSpec source files<br/>
* Command line -Drspec.dir=...
*
* @parameter expression="${rspec.dir}" default-value="spec"
*/
protected String specSourceDirectory;
/**
* skip rspecs <br/>
* Command line -DskipSpecs=...
*
* @parameter expression="${skipSpecs}" default-value="false"
*/
protected boolean skipSpecs;
/**
* The name of the RSpec report.
*
* @parameter default-value="rspec-report.html"
*/
private String reportName;
private File outputfile;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.skip || this.skipTests || this.skipSpecs) {
getLog().info("Skipping RSpec tests");
return;
}
else {
outputfile = new File(this.project.getBuild().getDirectory()
.replace("${project.basedir}/", ""), reportName);
if (outputfile.exists()){
outputfile.delete();
}
super.execute();
}
}
protected Result runIt(de.saumya.mojo.ruby.script.ScriptFactory factory, Mode mode, String version, TestScriptFactory scriptFactory)
throws IOException, ScriptException, MojoExecutionException {
scriptFactory.setOutputDir(outputfile.getParentFile());
scriptFactory.setReportPath(outputfile);
if(specSourceDirectory.startsWith(launchDirectory().getAbsolutePath())){
scriptFactory.setSourceDir(new File(specSourceDirectory));
}
else{
scriptFactory.setSourceDir(new File(launchDirectory(), specSourceDirectory));
}
final Script script = factory.newScript(scriptFactory.getCoreScript());
if (this.rspecArgs != null) {
script.addArgs(this.rspecArgs);
}
if (this.args != null) {
script.addArgs(this.args);
}
try {
script.executeIn(launchDirectory());
} catch (Exception e) {
getLog().debug("exception in running specs", e);
}
String reportPath = outputfile.getAbsolutePath();
final File reportFile;
if (mode != Mode.DEFAULT) {
reportFile = new File(reportPath.replace(".html", "-" + version
+ mode.name() + ".html"));
}
else if (this.jrubyVersion.equals(version)) {
reportFile = new File(reportPath);
}
else {
reportFile = new File(reportPath.replace(".html", "-" + version
+ ".html"));
}
new File(reportPath).renameTo(reportFile);
Result result = new Result();
Reader in = null;
try {
in = new FileReader(reportFile);
final BufferedReader reader = new BufferedReader(in);
String line = null;
while ((line = reader.readLine()) != null) {
// singular case needs to be treated as well
if (line.contains("failure") && line.contains("example")) {
result.message = line.replaceFirst("\";</.*>", "")
.replaceFirst("<.*\"", "");
break;
}
}
}
catch (final IOException e) {
throw new MojoExecutionException("Unable to read test report file: "
+ reportFile);
}
finally {
if (in != null) {
try {
in.close();
}
catch (final IOException e) {
throw new MojoExecutionException(e.getMessage());
}
}
}
if (result.message == null) {
if(reportFile.length() == 0){
result.success = true;
}
else { // this means the report file partial and thus an error occured
result.message = "An unknown error occurred";
result.success = false;
}
}
else {
String filename = "TEST-rspec"
+ (mode.flag == null ? "" : "-" + version
+ mode.flag) + ".xml";
File xmlReport = new File(this.testReportDirectory, filename);
new File(this.testReportDirectory, "TEST-rspec.xml").renameTo(xmlReport);
if (this.summaryReport != null) {
FileUtils.copyFile(xmlReport, this.summaryReport);
}
result.success = result.message.contains("0 failures");
}
return result;
}
@Override
protected TestScriptFactory newTestScriptFactory(Mode mode) {
return new RSpecMavenTestScriptFactory();
}
} |
package com.polidea.rxandroidble;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.polidea.rxandroidble.internal.RxBleLog;
import java.util.Set;
import java.util.UUID;
import rx.Observable;
public abstract class RxBleClient {
/**
* Returns instance of RxBleClient using application context. It is required by the client to maintain single instance of RxBleClient.
*
* @param context Any Android context
* @return BLE client instance.
*/
public static RxBleClient create(@NonNull Context context) {
return DaggerClientComponent
.builder()
.clientModule(new ClientComponent.ClientModule(context))
.build()
.rxBleClient();
}
/**
* A convenience method.
* Sets the log level that will be printed out in the console. Default is LogLevel.NONE which logs nothing.
*
* @param logLevel the minimum log level to log
*/
public static void setLogLevel(@RxBleLog.LogLevel int logLevel) {
RxBleLog.setLogLevel(logLevel);
}
/**
* Obtain instance of RxBleDevice for provided MAC address. This may be the same instance that was provided during scan operation but
* this in not guaranteed.
*
* @param macAddress Bluetooth LE device MAC address.
* @return Handle for Bluetooth LE operations.
* @throws UnsupportedOperationException if called on system without Bluetooth capabilities
*/
public abstract RxBleDevice getBleDevice(@NonNull String macAddress);
/**
* A function returning a set of currently bonded devices
*
* If Bluetooth state is not STATE_ON, this API will return an empty set. After turning on Bluetooth, wait for ACTION_STATE_CHANGED
* with STATE_ON to get the updated value.
*
* @return set of currently bonded devices
* @throws UnsupportedOperationException if called on system without Bluetooth capabilities
*/
public abstract Set<RxBleDevice> getBondedDevices();
/**
* Returns an infinite observable emitting BLE scan results.
* Scan is automatically started and stopped based on the Observable lifecycle.
* Scan is started on subscribe and stopped on unsubscribe. You can safely subscribe multiple observers to this observable.
* When defining filterServiceUUIDs have in mind that the {@link RxBleScanResult} will be emitted only if _all_ UUIDs will be present
* in the advertisement.
* <p>
* The library automatically handles Bluetooth adapter state changes but you are supposed to prompt
* the user to enable it if it's disabled.
*
* @param filterServiceUUIDs Filtering settings. Scan results are only filtered by exported services.
* All specified UUIDs must be present in the advertisement data to match the filter.
* @throws com.polidea.rxandroidble.exceptions.BleScanException emits in case of error starting the scan
*/
public abstract Observable<RxBleScanResult> scanBleDevices(@Nullable UUID... filterServiceUUIDs);
} |
package com.scrumkin.ejb;
import com.scrumkin.api.UserStoryManager;
import com.scrumkin.api.exceptions.*;
import com.scrumkin.jpa.*;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
@Stateless
public class UserStoryManagerEJB implements UserStoryManager {
public static List<PriorityEntity> validPriorities;
@PersistenceContext(unitName = "scrumkin_PU")
private EntityManager em;
public UserStoryManagerEJB() {
}
@PostConstruct
public void init() {
validPriorities = getValidPriorities();
}
@Override
public List<PriorityEntity> getValidPriorities() {
if (validPriorities != null)
return validPriorities;
TypedQuery<PriorityEntity> query = em.createNamedQuery("PriorityEntity.findAll", PriorityEntity.class);
List<PriorityEntity> priorities = query.getResultList();
return priorities;
}
@Override
public void addTestToStory(AcceptenceTestEntity acceptenceTestEntity) {
em.persist(acceptenceTestEntity);
}
@Override
public void setStoryTime(int id, double time) throws UserStoryEstimatedTimeMustBePositive {
if (time < 0) {
throw new UserStoryEstimatedTimeMustBePositive();
}
UserStoryEntity userStoryEntity = getUserStory(id);
userStoryEntity.setEstimatedTime(BigDecimal.valueOf(time));
em.persist(userStoryEntity);
}
@Override
public void updateTest(int id, String test, Boolean accepted) {
AcceptenceTestEntity acceptenceTestEntity = em.find(AcceptenceTestEntity.class, id);
acceptenceTestEntity.setAccepted(accepted);
acceptenceTestEntity.setTest(test);
em.persist(acceptenceTestEntity);
}
@Override
public void updateTestCompletion(int id, Boolean accepted) {
AcceptenceTestEntity acceptenceTestEntity = em.find(AcceptenceTestEntity.class, id);
acceptenceTestEntity.setAccepted(accepted);
em.persist(acceptenceTestEntity);
}
@Override
public void deleteStory(int id) {
UserStoryEntity userStoryEntity = em.find(UserStoryEntity.class, id);
if (userStoryEntity != null) {
em.remove(userStoryEntity);
}
}
@Override
public void updateStory(int id, String title, String story, PriorityEntity priority,
Integer businessValue, Collection<AcceptenceTestEntity> acceptanceTests) throws
UserStoryInvalidPriorityException, UserStoryTitleNotUniqueException,
UserStoryBusinessValueZeroOrNegative, UserStoryDoesNotExist {
UserStoryEntity userStory = em.find(UserStoryEntity.class, id);
if (userStory == null) {
throw new UserStoryDoesNotExist();
}
if (title != null) {
if (!isUniqueTitle(title)) {
throw new UserStoryTitleNotUniqueException("User story title [" + title + "] is not unique.");
}
userStory.setTitle(title);
}
if (story != null) {
userStory.setStory(story);
}
if (priority != null) {
userStory.setPriority(priority);
}
if (businessValue != null) {
if (businessValue <= 0) {
throw new UserStoryBusinessValueZeroOrNegative();
}
}
if (acceptanceTests != null) {
userStory.setAcceptenceTests(acceptanceTests);
}
em.persist(userStory);
}
@Override
public AcceptenceTestEntity getAcceptanceTest(int id) {
return em.find(AcceptenceTestEntity.class, id);
}
@Override
public void addStoryComment(int id, String comment) {
StoryCommentEntity storyCommentEntity = new StoryCommentEntity();
storyCommentEntity.setStory(getUserStory(id));
storyCommentEntity.setComment(comment);
storyCommentEntity.setDate(new Timestamp(System.currentTimeMillis()));
em.persist(storyCommentEntity);
}
@Override
public List<StoryCommentEntity> getStoryComments(int id) {
// TypedQuery<StoryCommentEntity> query = em.createNamedQuery("StoryCommentEntity.getAllStoryComments",
// StoryCommentEntity.class);
// query.setParameter("story_id", id);
// return query.getResultList();
return new LinkedList<>(em.find(UserStoryEntity.class, id).getComments());
}
@Override
public int addUserStoryToBacklog(ProjectEntity project, String title, String story, PriorityEntity priority,
int businessValue, Collection<AcceptenceTestEntity> acceptanceTests) throws
ProjectInvalidException,
UserStoryInvalidPriorityException, UserStoryTitleNotUniqueException, UserStoryBusinessValueZeroOrNegative {
if (!validPriorities.contains(priority)) {
throw new UserStoryInvalidPriorityException("Priority name [" + priority.getName() + "] is not valid.");
}
// TypedQuery<Boolean> projectExistsQuery = em.createNamedQuery("ProjectEntity.exists", Boolean.class);
// projectExistsQuery.setParameter("project", project);
// boolean projectExists = projectExistsQuery.getSingleResult();
// if (projectExists) {
// throw new ProjectInvalidException("Project named [" + project.getName() + "] does not exist.");
// TypedQuery<Boolean> isUniqueTitleQuery = em.createNamedQuery("UserStoryEntity.isUniqueTitle", Boolean.class);
// isUniqueTitleQuery.setParameter("title", title);
// boolean isUniqueTitle = isUniqueTitleQuery.getSingleResult();
if (!isUniqueTitle(title)) {
throw new UserStoryTitleNotUniqueException("User story title [" + title + "] is not unique.");
}
if (businessValue <= 0) {
throw new UserStoryBusinessValueZeroOrNegative();
}
UserStoryEntity userStory = new UserStoryEntity();
userStory.setProject(project);
userStory.setTitle(title);
userStory.setStory(story);
userStory.setPriority(priority);
userStory.setBussinessValue(businessValue);
userStory.setAcceptenceTests(acceptanceTests);
em.persist(userStory);
em.persist(project);
return userStory.getId();
}
@Override
public boolean isUserStoryRealized(UserStoryEntity userStory) {
Collection<AcceptenceTestEntity> acceptanceTests = userStory.getAcceptenceTests();
if (acceptanceTests.size() == 0) {
return false;
}
for (AcceptenceTestEntity acceptanceTest : acceptanceTests) {
if (acceptanceTest.getAccepted() == null || !acceptanceTest.getAccepted()) {
return false;
}
}
return true;
}
@Override
public void assignUserStoriesToSprint(SprintEntity sprint, List<UserStoryEntity> userStories)
throws UserStoryEstimatedTimeNotSetException, UserStoryRealizedException,
UserStoryInThisSprintException, UserStoryInAnotherSprintException {
List<String> userStoriesNoTime = new ArrayList<String>();
List<String> userStoriesRealized = new ArrayList<String>();
List<String> userStoriesInThisSprint = new ArrayList<String>();
List<String> userStoriesInAnotherSprint = new ArrayList<String>();
for (UserStoryEntity use : userStories) {
String userStoryTitle = use.getTitle();
if (use.getEstimatedTime() == null) {
userStoriesNoTime.add(userStoryTitle);
}
boolean userStoryRealized = isUserStoryRealized(use);
if (userStoryRealized) {
userStoriesRealized.add(userStoryTitle);
}
if (use.getSprint() != null) {
if (use.getSprint().equals(sprint))
userStoriesInThisSprint.add(userStoryTitle);
else
userStoriesInAnotherSprint.add(userStoryTitle);
}
}
if (userStoriesNoTime.size() > 0) {
throw new UserStoryEstimatedTimeNotSetException("User story/ies " + userStoriesNoTime.toString()
+ " doesn't/don't specify estimated time.");
}
if (userStoriesRealized.size() > 0) {
throw new UserStoryRealizedException("User storie/s " + userStoriesRealized.toString()
+ " is/were already realized.");
}
if (userStoriesInThisSprint.size() > 0) {
throw new UserStoryInThisSprintException("User storie/s " + userStoriesInThisSprint.toString()
+ " is/were already assigned to this sprint.");
}
if (userStoriesInAnotherSprint.size() > 0) {
throw new UserStoryInAnotherSprintException("User storie/s " + userStoriesInAnotherSprint.toString()
+ " is/were already assigned to other sprint/s.");
}
List<UserStoryEntity> currentStories = (List<UserStoryEntity>) sprint.getUserStories();
if (currentStories != null) {
userStories.addAll(currentStories);
}
// sprint.setUserStories(userStories);
// em.persist(sprint);
for (UserStoryEntity userStory : userStories) {
userStory.setSprint(sprint);
em.persist(userStory);
}
}
@Override
public UserStoryEntity getUserStory(int id) {
UserStoryEntity userStory = em.find(UserStoryEntity.class, id);
return userStory;
}
private boolean isUniqueTitle(String title) {
TypedQuery<UserStoryEntity> titleQuery = em.createQuery("SELECT s FROM UserStoryEntity s WHERE s" +
".title=:title", UserStoryEntity.class);
titleQuery.setParameter("title", title);
return titleQuery.getResultList().size() == 0;
}
} |
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.model;
import com.kyloth.serleena.common.GeoPoint;
import com.kyloth.serleena.common.LocationTelemetryEvent;
import com.kyloth.serleena.common.TelemetryEvent;
import com.kyloth.serleena.common.TelemetryEventType;
/**
* Interfaccia realizzata da oggetti che rappresentano un
* Tracciamento
*
* @author Tobia Tesan <tobia.tesan@gmail.com>
* @version 1.0
* @since 1.0
*/
public interface ITelemetry {
/**
* Restituisce gli eventi che costituiscono il Tracciamento.
*
* @return Un Iterable che contiene tutti gli eventi del Tracciamento.
* @version 1.0
*/
public Iterable<TelemetryEvent> getEvents();
public Iterable<TelemetryEvent> getEvents(int from, int to)
throws NoSuchTelemetryEventException, IllegalArgumentException;
/**
* Restituisce gli eventi che costituiscono il Tracciamento, filtrati in
* base a uno specifico tipo di evento.
*
* @return Insieme enumerabile che contiene tutti e soli gli eventi del
* Tracciamento di tipo specificato.
* @param type Tipo di eventi da restituire.
* @return Insieme enumerabile di eventi di Tracciamento.
*/
public Iterable<TelemetryEvent> getEvents(TelemetryEventType type)
throws NoSuchTelemetryEventException;
public LocationTelemetryEvent getEventAtLocation(GeoPoint loc,
int tolerance)
throws NoSuchTelemetryEventException, IllegalArgumentException;
/**
* Restituisce la durata totale del Tracciamento.
*
* @return Durata temporale in secondi del Tracciamento.
* @version 1.0
*/
public int getDuration();
} |
package bisq.common.util;
import org.bitcoinj.core.Utils;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.common.base.Splitter;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import java.text.DecimalFormat;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.awt.Desktop.Action;
import static java.awt.Desktop.getDesktop;
import static java.awt.Desktop.isDesktopSupported;
@Slf4j
public class Utilities {
public static String objectToJson(Object object) {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new AnnotationExclusionStrategy())
/*.excludeFieldsWithModifiers(Modifier.TRANSIENT)*/
/* .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)*/
.setPrettyPrinting()
.create();
return gson.toJson(object);
}
public static ExecutorService getSingleThreadExecutor(String name) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.build();
return Executors.newSingleThreadExecutor(threadFactory);
}
public static ListeningExecutorService getSingleThreadListeningExecutor(String name) {
return MoreExecutors.listeningDecorator(getSingleThreadExecutor(name));
}
public static ListeningExecutorService getListeningExecutorService(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
return MoreExecutors.listeningDecorator(getThreadPoolExecutor(name, corePoolSize, maximumPoolSize, keepAliveTimeInSec));
}
public static ThreadPoolExecutor getThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.build();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeInSec,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory);
executor.allowCoreThreadTimeOut(true);
executor.setRejectedExecutionHandler((r, e) -> log.debug("RejectedExecutionHandler called"));
return executor;
}
@SuppressWarnings("SameParameterValue")
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.setPriority(Thread.MIN_PRIORITY)
.build();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
executor.setKeepAliveTime(keepAliveTimeInSec, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
executor.setMaximumPoolSize(maximumPoolSize);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
executor.setRejectedExecutionHandler((r, e) -> log.debug("RejectedExecutionHandler called"));
return executor;
}
/**
* @return true if <code>defaults read -g AppleInterfaceStyle</code> has an exit status of <code>0</code> (i.e. _not_ returning "key not found").
*/
public static boolean isMacMenuBarDarkMode() {
try {
// check for exit status only. Once there are more modes than "dark" and "default", we might need to analyze string contents..
Process process = Runtime.getRuntime().exec(new String[]{"defaults", "read", "-g", "AppleInterfaceStyle"});
process.waitFor(100, TimeUnit.MILLISECONDS);
return process.exitValue() == 0;
} catch (IOException | InterruptedException | IllegalThreadStateException ex) {
return false;
}
}
public static boolean isUnix() {
return isOSX() || isLinux() || getOSName().contains("freebsd");
}
public static boolean isWindows() {
return getOSName().contains("win");
}
/**
* @return True, if Bisq is running on a virtualized OS within Qubes, false otherwise
*/
public static boolean isQubesOS() {
// For Linux qubes, "os.version" looks like "4.19.132-1.pvops.qubes.x86_64"
// The presence of the "qubes" substring indicates this Linux is running as a qube
// This is the case for all 3 virtualization modes (PV, PVH, HVM)
// In addition, this works for both simple AppVMs, as well as for StandaloneVMs
// TODO This might not work for detecting Qubes virtualization for other OSes
// like Windows
return getOSVersion().contains("qubes");
}
public static boolean isOSX() {
return getOSName().contains("mac") || getOSName().contains("darwin");
}
public static boolean isLinux() {
return getOSName().contains("linux");
}
public static boolean isDebianLinux() {
return isLinux() && new File("/etc/debian_version").isFile();
}
public static boolean isRedHatLinux() {
return isLinux() && new File("/etc/redhat-release").isFile();
}
private static String getOSName() {
return System.getProperty("os.name").toLowerCase(Locale.US);
}
public static String getOSVersion() {
return System.getProperty("os.version").toLowerCase(Locale.US);
}
/**
* Returns the well-known "user data directory" for the current operating system.
*/
public static File getUserDataDir() {
if (Utilities.isWindows())
return new File(System.getenv("APPDATA"));
if (Utilities.isOSX())
return Paths.get(System.getProperty("user.home"), "Library", "Application Support").toFile();
// *nix
return Paths.get(System.getProperty("user.home"), ".local", "share").toFile();
}
public static int getMinorVersion() throws InvalidVersionException {
String version = getOSVersion();
String[] tokens = version.split("\\.");
try {
checkArgument(tokens.length > 1);
return Integer.parseInt(tokens[1]);
} catch (IllegalArgumentException e) {
printSysInfo();
throw new InvalidVersionException("Version is not in expected format. Version=" + version);
}
}
public static int getMajorVersion() throws InvalidVersionException {
String version = getOSVersion();
String[] tokens = version.split("\\.");
try {
checkArgument(tokens.length > 0);
return Integer.parseInt(tokens[0]);
} catch (IllegalArgumentException e) {
printSysInfo();
throw new InvalidVersionException("Version is not in expected format. Version=" + version);
}
}
public static String getOSArchitecture() {
String osArch = System.getProperty("os.arch");
if (isWindows()) {
// See: Like always windows needs extra treatment
String arch = System.getenv("PROCESSOR_ARCHITECTURE");
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
return arch.endsWith("64")
|| wow64Arch != null && wow64Arch.endsWith("64")
? "64" : "32";
} else if (osArch.contains("arm")) {
// armv8 is 64 bit, armv7l is 32 bit
return osArch.contains("64") || osArch.contains("v8") ? "64" : "32";
} else if (isLinux()) {
return osArch.startsWith("i") ? "32" : "64";
} else {
return osArch.contains("64") ? "64" : osArch;
}
}
public static void printSysInfo() {
log.info("System info: os.name={}; os.version={}; os.arch={}; sun.arch.data.model={}; JRE={}; JVM={}",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"),
getJVMArchitecture(),
(System.getProperty("java.runtime.version", "-") + " (" + System.getProperty("java.vendor", "-") + ")"),
(System.getProperty("java.vm.version", "-") + " (" + System.getProperty("java.vm.name", "-") + ")")
);
}
public static String getJVMArchitecture() {
return System.getProperty("sun.arch.data.model");
}
public static boolean isCorrectOSArchitecture() {
boolean result = getOSArchitecture().endsWith(getJVMArchitecture());
if (!result) {
log.warn("System.getProperty(\"os.arch\") " + System.getProperty("os.arch"));
log.warn("System.getenv(\"ProgramFiles(x86)\") " + System.getenv("ProgramFiles(x86)"));
log.warn("System.getenv(\"PROCESSOR_ARCHITECTURE\")" + System.getenv("PROCESSOR_ARCHITECTURE"));
log.warn("System.getenv(\"PROCESSOR_ARCHITEW6432\") " + System.getenv("PROCESSOR_ARCHITEW6432"));
log.warn("System.getProperty(\"sun.arch.data.model\") " + System.getProperty("sun.arch.data.model"));
}
return result;
}
public static void openURI(URI uri) throws IOException {
if (!isLinux()
&& isDesktopSupported()
&& getDesktop().isSupported(Action.BROWSE)) {
getDesktop().browse(uri);
} else {
// Maybe Application.HostServices works in those cases?
// HostServices hostServices = getHostServices();
// hostServices.showDocument(uri.toString());
// On Linux Desktop is poorly implemented.
if (!DesktopUtil.browse(uri))
throw new IOException("Failed to open URI: " + uri.toString());
}
}
public static void openFile(File file) throws IOException {
if (!isLinux()
&& isDesktopSupported()
&& getDesktop().isSupported(Action.OPEN)) {
getDesktop().open(file);
} else {
// Maybe Application.HostServices works in those cases?
// HostServices hostServices = getHostServices();
// hostServices.showDocument(uri.toString());
// On Linux Desktop is poorly implemented.
if (!DesktopUtil.open(file))
throw new IOException("Failed to open file: " + file.toString());
}
}
public static String getDownloadOfHomeDir() {
File file = new File(getSystemHomeDirectory() + "/Downloads");
if (file.exists())
return file.getAbsolutePath();
else
return getSystemHomeDirectory();
}
public static void copyToClipboard(String content) {
try {
if (content != null && content.length() > 0) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(content);
clipboard.setContent(clipboardContent);
}
} catch (Throwable e) {
log.error("copyToClipboard failed " + e.getMessage());
e.printStackTrace();
}
}
public static void setThreadName(String name) {
Thread.currentThread().setName(name + "-" + new Random().nextInt(10000));
}
public static boolean isDirectory(String path) {
return new File(path).isDirectory();
}
public static String getSystemHomeDirectory() {
return Utilities.isWindows() ? System.getenv("USERPROFILE") : System.getProperty("user.home");
}
public static String encodeToHex(@Nullable byte[] bytes, boolean allowNullable) {
if (allowNullable)
return bytes != null ? Utils.HEX.encode(bytes) : "null";
else
return Utils.HEX.encode(checkNotNull(bytes, "bytes must not be null at encodeToHex"));
}
public static String bytesAsHexString(@Nullable byte[] bytes) {
return encodeToHex(bytes, true);
}
public static String encodeToHex(@Nullable byte[] bytes) {
return encodeToHex(bytes, false);
}
public static byte[] decodeFromHex(String encoded) {
return Utils.HEX.decode(encoded);
}
public static boolean isAltOrCtrlPressed(KeyCode keyCode, KeyEvent keyEvent) {
return isAltPressed(keyCode, keyEvent) || isCtrlPressed(keyCode, keyEvent);
}
public static boolean isCtrlPressed(KeyCode keyCode, KeyEvent keyEvent) {
return new KeyCodeCombination(keyCode, KeyCombination.SHORTCUT_DOWN).match(keyEvent) ||
new KeyCodeCombination(keyCode, KeyCombination.CONTROL_DOWN).match(keyEvent);
}
public static boolean isAltPressed(KeyCode keyCode, KeyEvent keyEvent) {
return new KeyCodeCombination(keyCode, KeyCombination.ALT_DOWN).match(keyEvent);
}
public static boolean isCtrlShiftPressed(KeyCode keyCode, KeyEvent keyEvent) {
return new KeyCodeCombination(keyCode, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN).match(keyEvent);
}
public static byte[] concatenateByteArrays(byte[] array1, byte[] array2) {
return ArrayUtils.addAll(array1, array2);
}
public static Date getUTCDate(int year, int month, int dayOfMonth) {
GregorianCalendar calendar = new GregorianCalendar(year, month, dayOfMonth);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
return calendar.getTime();
}
/**
* @param stringList String of comma separated tokens.
* @param allowWhitespace If white space inside the list tokens is allowed. If not the token will be ignored.
* @return Set of tokens
*/
public static Set<String> commaSeparatedListToSet(String stringList, boolean allowWhitespace) {
if (stringList != null) {
return Splitter.on(",")
.splitToList(allowWhitespace ? stringList : StringUtils.deleteWhitespace(stringList))
.stream()
.filter(e -> !e.isEmpty())
.collect(Collectors.toSet());
} else {
return new HashSet<>();
}
}
public static String getPathOfCodeSource() throws URISyntaxException {
return new File(Utilities.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath();
}
private static class AnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(JsonExclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
public static String toTruncatedString(Object message) {
return toTruncatedString(message, 200, true);
}
public static String toTruncatedString(Object message, int maxLength) {
return toTruncatedString(message, maxLength, true);
}
public static String toTruncatedString(Object message, int maxLength, boolean removeLineBreaks) {
if (message == null)
return "null";
String result = StringUtils.abbreviate(message.toString(), maxLength);
if (removeLineBreaks)
return result.replace("\n", "");
return result;
}
public static String getRandomPrefix(int minLength, int maxLength) {
int length = minLength + new Random().nextInt(maxLength - minLength + 1);
String result;
switch (new Random().nextInt(3)) {
case 0:
result = RandomStringUtils.randomAlphabetic(length);
break;
case 1:
result = RandomStringUtils.randomNumeric(length);
break;
case 2:
default:
result = RandomStringUtils.randomAlphanumeric(length);
}
switch (new Random().nextInt(3)) {
case 0:
result = result.toUpperCase();
break;
case 1:
result = result.toLowerCase();
break;
case 2:
default:
}
return result;
}
public static String getShortId(String id) {
return getShortId(id, "-");
}
@SuppressWarnings("SameParameterValue")
public static String getShortId(String id, String sep) {
String[] chunks = id.split(sep);
if (chunks.length > 0)
return chunks[0];
else
return id.substring(0, Math.min(8, id.length()));
}
public static byte[] integerToByteArray(int intValue, int numBytes) {
byte[] bytes = new byte[numBytes];
for (int i = numBytes - 1; i >= 0; i
bytes[i] = ((byte) (intValue & 0xFF));
intValue >>>= 8;
}
return bytes;
}
public static int byteArrayToInteger(byte[] bytes) {
int result = 0;
for (byte aByte : bytes) {
result = result << 8 | aByte & 0xff;
}
return result;
}
// Helper to filter unique elements by key
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
public static String readableFileSize(long size) {
if (size <= 0) return "0";
String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("
}
} |
package io.spine.server.integration;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.protobuf.Message;
import io.spine.core.BoundedContextName;
import io.spine.protobuf.AnyPacker;
import io.spine.server.BoundedContext;
import io.spine.server.ContextAware;
import io.spine.server.ServerEnvironment;
import io.spine.server.bus.BusBuilder;
import io.spine.server.bus.DeadMessageHandler;
import io.spine.server.bus.EnvelopeValidator;
import io.spine.server.bus.MulticastBus;
import io.spine.server.event.AbstractEventSubscriber;
import io.spine.server.transport.Publisher;
import io.spine.server.transport.PublisherHub;
import io.spine.server.transport.Subscriber;
import io.spine.server.transport.SubscriberHub;
import io.spine.server.transport.TransportFactory;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import java.util.Set;
import static com.google.common.base.Preconditions.checkState;
import static io.spine.server.integration.IntegrationChannels.toId;
import static io.spine.util.Exceptions.newIllegalArgumentException;
import static java.lang.String.format;
/**
* Dispatches {@linkplain ExternalMessage external messages} from and to the Bounded Context
* in which this bus operates.
*
* <p>This bus is available as a part of single {@code BoundedContext}.
* In a multi-component environment messages may travel across components from one Bounded Context
* to another.
*
* <p>{@code IntegrationBus} is always based upon some {@linkplain TransportFactory transport}
* that delivers the messages from and to it. For several Bounded Contexts to communicate,
* their integration buses have to share the transport. Typically that would be a single
* messaging broker.
*
* <p>The messages from external components received by the {@code IntegrationBus} instance
* via the transport are propagated into the bounded context. They are dispatched
* to the subscribers and reactors marked with {@code external = true} on per-message-type basis.
*
* {@code IntegrationBus} is also responsible for publishing the messages
* born within the current `BoundedContext` to external collaborators. To do that properly,
* the bus listens to a special document message called {@linkplain RequestForExternalMessages}
* that describes the needs of other parties.
*
* <p><b>Sample Usage.</b> The Bounded Context named Projects has an external event handler method
* in the projection as follows:
*
* <p>Bounded context "Projects" has the external event handler method in the projection as follows:
* <pre>
* public class ProjectListView extends Projection ... {
*
* {@literal @}Subscribe(external = true)
* public void on(UserDeleted event) {
* // Remove the projects that belong to this user.
* // ...
* }
*
* // ...
* }
* </pre>
*
* <p>Upon a registration of the corresponding repository, the integration bus of
* "Projects" context sends out a {@code RequestForExternalMessages} saying that an {@code Event}
* of {@code UserDeleted} type is needed from other parties.
*
* <p>Let's say the second Bounded Context is "Users". Its integration bus will receive
* the {@code RequestForExternalMessages} request sent out by "Projects". To handle it properly,
* it will create a bridge between "Users"'s event bus (which may eventually be transmitting
* a {@code UserDeleted} event) and an external transport.
*
* <p>Once {@code UserDeleted} is published locally in "Users" context, it will be received
* by this bridge (as well as other local dispatchers) and published to the external transport.
*
* <p>The integration bus of "Projects" context will receive the {@code UserDeleted}
* external message. The event will be dispatched to the external event handler of
* {@code ProjectListView} projection.
*/
@SuppressWarnings("OverlyCoupledClass")
public class IntegrationBus
extends MulticastBus<ExternalMessage,
ExternalMessageEnvelope,
ExternalMessageClass,
ExternalMessageDispatcher<?>>
implements ContextAware {
/**
* An identification of the channel serving to exchange {@linkplain RequestForExternalMessages
* configuration messages} with other parties, such as instances of {@code IntegrationBus}
* from other {@code BoundedContext}s.
*/
private static final ChannelId CONFIG_EXCHANGE_CHANNEL_ID =
toId(RequestForExternalMessages.class);
private final SubscriberHub subscriberHub;
private final PublisherHub publisherHub;
private @MonotonicNonNull Iterable<BusAdapter<?, ?>> localBusAdapters;
private @MonotonicNonNull BoundedContextName boundedContextName;
private @MonotonicNonNull ConfigurationChangeObserver configurationChangeObserver;
private @MonotonicNonNull ConfigurationBroadcast configurationBroadcast;
private IntegrationBus(Builder builder) {
super(builder);
TransportFactory transportFactory = ServerEnvironment.instance().transportFactory();
this.subscriberHub = new SubscriberHub(transportFactory);
this.publisherHub = new PublisherHub(transportFactory);
}
@Override
public void registerWith(BoundedContext context) {
checkNotRegistered();
this.boundedContextName = context.name();
this.localBusAdapters = createAdapters(context);
this.configurationChangeObserver = observeConfigurationChanges();
Publisher configurationPublisher = publisherHub.get(CONFIG_EXCHANGE_CHANNEL_ID);
this.configurationBroadcast =
new ConfigurationBroadcast(boundedContextName, configurationPublisher);
subscriberHub.get(CONFIG_EXCHANGE_CHANNEL_ID)
.addObserver(configurationChangeObserver);
}
@Override
public boolean isRegistered() {
return boundedContextName != null;
}
/**
* Creates an observer to react upon {@linkplain RequestForExternalMessages external request}
* message arrival.
*/
private ConfigurationChangeObserver observeConfigurationChanges() {
return new ConfigurationChangeObserver(this, boundedContextName, this::adapterFor);
}
private
ImmutableSet<BusAdapter<?, ?>> createAdapters(BoundedContext context) {
return ImmutableSet.of(
EventBusAdapter.builderWith(context.eventBus(), context.name())
.setPublisherHub(publisherHub)
.build()
);
}
@Override
protected DeadMessageHandler<ExternalMessageEnvelope> deadMessageHandler() {
return DeadExternalMessageHandler.INSTANCE;
}
@Override
protected EnvelopeValidator<ExternalMessageEnvelope> validator() {
return ExternalMessageValidator.INSTANCE;
}
@Override
protected ExternalMessageEnvelope toEnvelope(ExternalMessage message) {
BusAdapter<?, ?> adapter = adapterFor(message);
ExternalMessageEnvelope result = adapter.toExternalEnvelope(message);
return result;
}
private static IllegalArgumentException messageUnsupported(Class<? extends Message> msgClass) {
throw newIllegalArgumentException("The message of %s type isn't supported", msgClass);
}
@Override
protected void dispatch(ExternalMessageEnvelope envelope) {
ExternalMessageEnvelope markedEnvelope = markExternal(envelope);
int dispatchersCalled = callDispatchers(markedEnvelope);
checkState(dispatchersCalled != 0,
format("External message %s has no local dispatchers.",
markedEnvelope.message()));
}
private ExternalMessageEnvelope markExternal(ExternalMessageEnvelope envelope) {
ExternalMessage externalMessage = envelope.outerObject();
BusAdapter<?, ?> adapter = adapterFor(externalMessage);
return adapter.markExternal(externalMessage);
}
private BusAdapter<?, ?> adapterFor(ExternalMessage message) {
Message unpackedOriginal = AnyPacker.unpack(message.getOriginalMessage());
return adapterFor(unpackedOriginal.getClass());
}
@Override
protected void store(Iterable<ExternalMessage> messages) {
// We don't store the incoming messages yet.
}
/**
* Registers a local dispatcher which is subscribed to {@code external} messages.
*
* @param dispatcher the dispatcher to register
*/
@Override
public void register(ExternalMessageDispatcher<?> dispatcher) {
super.register(dispatcher);
Iterable<ExternalMessageClass> receivedTypes = dispatcher.messageClasses();
for (ExternalMessageClass cls : receivedTypes) {
ChannelId channelId = toId(cls);
Subscriber subscriber = subscriberHub.get(channelId);
ExternalMessageObserver observer = observerFor(cls);
subscriber.addObserver(observer);
notifyOfSubscriptions();
}
}
/**
* Unregisters a local dispatcher which should no longer be subscribed
* to {@code external} messages.
*
* @param dispatcher the dispatcher to unregister
*/
@Override
public void unregister(ExternalMessageDispatcher<?> dispatcher) {
super.unregister(dispatcher);
Iterable<ExternalMessageClass> transformed = dispatcher.messageClasses();
for (ExternalMessageClass cls : transformed) {
ChannelId channelId = toId(cls);
Subscriber subscriber = subscriberHub.get(channelId);
ExternalMessageObserver observer = observerFor(cls);
subscriber.removeObserver(observer);
}
subscriberHub.closeStaleChannels();
}
private ExternalMessageObserver observerFor(ExternalMessageClass externalClass) {
ExternalMessageObserver observer =
new ExternalMessageObserver(boundedContextName, externalClass.value(), this);
return observer;
}
private void notifyOfSubscriptions() {
notifyOfNeeds(subscriberHub.ids());
}
/**
* Notifies other parts of the application that this integration bus instance now requests
* for a different set of message types.
*
* <p>Sends out an instance of {@linkplain RequestForExternalMessages
* request for external messages} for that purpose.
*
* @param currentlyRequested
* the set of message types that are now requested by this instance of
* integration bus
*/
private void notifyOfNeeds(Set<ChannelId> currentlyRequested) {
configurationBroadcast.onNeedsUpdated(currentlyRequested);
}
/**
* Notifies the other contexts about the current needs on this bus.
*
* <p>Sends a {@link RequestForExternalMessages} message with the details about which messages
* are required by this bus.
*/
void notifyOfCurrentNeeds() {
configurationBroadcast.send();
}
/**
* Registers the passed event subscriber as an external event dispatcher
* by taking only external subscriptions into account.
*
* @param eventSubscriber the subscriber to register.
*/
public void register(AbstractEventSubscriber eventSubscriber) {
ExternalEventSubscriber wrapped = new ExternalEventSubscriber(eventSubscriber);
register(wrapped);
}
/**
* Unregisters the passed event subscriber as an external event dispatcher
* by taking only external subscriptions into account.
*
* @param eventSubscriber the subscriber to register.
*/
public void unregister(AbstractEventSubscriber eventSubscriber) {
ExternalEventSubscriber wrapped = new ExternalEventSubscriber(eventSubscriber);
unregister(wrapped);
}
/**
* Removes all subscriptions and closes all the underlying transport channels.
*/
@Override
public void close() throws Exception {
super.close();
configurationChangeObserver.close();
// Declare that this instance has no needs.
notifyOfNeeds(ImmutableSet.of());
subscriberHub.close();
publisherHub.close();
}
@Override
public String toString() {
return "Integration Bus of BoundedContext Name = " + boundedContextName.getValue();
}
private BusAdapter<?, ?> adapterFor(Class<? extends Message> messageClass) {
for (BusAdapter<?, ?> localAdapter : localBusAdapters) {
if (localAdapter.accepts(messageClass)) {
return localAdapter;
}
}
throw messageUnsupported(messageClass);
}
/** Creates a new builder for this bus. */
public static Builder newBuilder() {
return new Builder();
}
/**
* A {@code Builder} for {@code IntegrationBus} instances.
*/
@CanIgnoreReturnValue
public static class Builder extends BusBuilder<Builder,
ExternalMessage,
ExternalMessageEnvelope,
ExternalMessageClass,
ExternalMessageDispatcher<?>> {
@Override
protected DomesticDispatcherRegistry newRegistry() {
return new DomesticDispatcherRegistry();
}
@Override
@CheckReturnValue
public IntegrationBus build() {
return new IntegrationBus(this);
}
@Override
protected Builder self() {
return this;
}
}
} |
package org.simpleflatmapper.util;
import java.io.IOException;
import java.io.Reader;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
//IFJAVA8_START
import java.util.concurrent.ForkJoinPool;
//IFJAVA8_END
import java.util.concurrent.locks.LockSupport;
public class ParallelReader extends Reader {
//IFJAVA8_START
private static final Executor DEFAULT_EXECUTOR_J8 = ForkJoinPool.getCommonPoolParallelism() > 1 ? ForkJoinPool.commonPool() : new Executor() {
public void execute(Runnable command) {
(new Thread(command)).start();
}
};
//IFJAVA8_END
private static Executor DEFAULT_EXECUTOR_J6 = null;
private static final Object lock = new Object();
public static Executor getDefaultExecutor() {
//IFJAVA8_START
if (true) {
return DEFAULT_EXECUTOR_J8;
}
//IFJAVA8_END
synchronized (lock) {
if (DEFAULT_EXECUTOR_J6 == null) {
DEFAULT_EXECUTOR_J6 = newDefaultExecutor();
}
}
return DEFAULT_EXECUTOR_J6;
}
private static Executor newDefaultExecutor() {
int p = Runtime.getRuntime().availableProcessors();
if (p <= 1) {
return new Executor() {
public void execute(Runnable command) {
(new Thread(command)).start();
}
};
} else {
return Executors.newScheduledThreadPool(Math.min(p, 0x7fff));
}
}
private static final WaitingStrategy DEFAULT_WAITING_STRATEGY = new WaitingStrategy() {
@Override
public int idle(int i) {
LockSupport.parkNanos(1l);
return i;
}
};
private static final int DEFAULT_READ_BUFFER_SIZE = 8192;
private static final int DEFAULT_RING_BUFFER_SIZE = 1024 * 64; // 64 k
private final RingBufferReader reader;
/**
* Create a new ParallelReader that will fetch the data from that reader in a another thread.
* By default it will use the ForkJoinPool common pool from java8 or a ExecutorService with a pool size set to the number of available cores.
* If the number of cores is 1 it will create a new Thread everytime.
* The default WaitingStrategy just call LockSupport.parkNanos(1l);
* @param reader the reader
*/
public ParallelReader(Reader reader) {
this(reader, getDefaultExecutor(), DEFAULT_RING_BUFFER_SIZE);
}
public ParallelReader(Reader reader, Executor executorService) {
this(reader, executorService, DEFAULT_RING_BUFFER_SIZE);
}
public ParallelReader(Reader reader, Executor executorService, int bufferSize) {
this(reader, executorService, bufferSize, DEFAULT_READ_BUFFER_SIZE);
}
public ParallelReader(Reader reader, Executor executorService, int bufferSize, int readBufferSize) {
this(reader, executorService, bufferSize, readBufferSize, DEFAULT_WAITING_STRATEGY);
}
/**
* Create a new ParallelReader.
* @param reader the reader
* @param executorService the executor to fetch from
* @param bufferSize the size of the ring buffer
* @param readBufferSize the size of the buffer to fetch data
* @param waitingStrategy the waiting strategy when the ring buffer is full
*/
public ParallelReader(Reader reader, Executor executorService, int bufferSize, int readBufferSize, WaitingStrategy waitingStrategy) {
this.reader = new RingBufferReader(reader, executorService, bufferSize, readBufferSize, waitingStrategy);
}
@Override
public int read() throws IOException {
return reader.read();
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
return reader.read(cbuf, off, len);
}
@Override
public void close() throws IOException {
reader.close();
}
public interface WaitingStrategy {
int idle(int i);
}
}
class Pad0 {
long p1,p2,p3,p4,p5,p6,p7;
}
class Tail extends Pad0 {
volatile long tail = 0;
}
class Pad1 extends Tail { long p1,p2,p3,p4,p5,p6,p7; }
class Buffer extends Pad1 { char[] buffer; }
class Pad2 extends Buffer { long p1,p2,p3,p4,p5,p6,p7; }
class Head extends Pad2 {
volatile long head = 0;
}
final class RingBufferReader extends Head {
public static final int L1_CACHE_LINE_SIZE = 64;
private final Reader reader;
private final DataProducer dataProducer;
private final long bufferMask;
private final int capacity;
private final int tailPadding;
private long tailCache;
private long headCache;
private final ParallelReader.WaitingStrategy waitingStrategy;
public RingBufferReader(Reader reader, Executor executorService, int ringBufferSize, int readSize, ParallelReader.WaitingStrategy waitingStrategy) {
capacity = 1 << 32 - Integer.numberOfLeadingZeros(ringBufferSize - 1);
tailPadding = capacity <= 1024 ? 0 : L1_CACHE_LINE_SIZE;
this.reader = reader;
buffer = new char[capacity + L1_CACHE_LINE_SIZE * 2]; // cache line padding on both
bufferMask = capacity - 1;
this.waitingStrategy = waitingStrategy;
dataProducer = new DataProducer(Math.max(Math.min(ringBufferSize / 8, readSize), 1));
executorService.execute(dataProducer);
}
public int read(char[] cbuf, int off, int len) throws IOException {
final long currentHead = head;
int i = 0;
do {
if (currentHead < tailCache) {
int l = read(cbuf, off, len, currentHead, tailCache);
head = currentHead + l;
return l;
}
tailCache = tail;
if (currentHead >= tailCache) {
if (!dataProducer.run) {
if (dataProducer.exception != null) {
throw dataProducer.exception;
}
tailCache = tail;
if (currentHead >= tailCache) {
return -1;
}
}
i = waitingStrategy.idle(i);
}
} while(true);
}
public int read() throws IOException {
final long currentHead = head;
int i = 0;
do {
if (currentHead < tailCache) {
int headIndex = (int) (currentHead & bufferMask);
char c = buffer[headIndex + L1_CACHE_LINE_SIZE];
head = currentHead + 1;
return c;
}
tailCache = tail;
if (currentHead >= tailCache) {
if (!dataProducer.run) {
if (dataProducer.exception != null) {
throw dataProducer.exception;
}
tailCache = tail;
if (currentHead >= tailCache) {
return -1;
}
}
i = waitingStrategy.idle(i);
}
} while(true);
}
private int read(char[] cbuf, int off, int len, long currentHead, long currentTail) {
int headIndex = (int) (currentHead & bufferMask);
int usedLength = (int) (currentTail - currentHead);
int block1Length = Math.min(len, Math.min(usedLength, (capacity - headIndex)));
int block2Length = Math.min(len, usedLength) - block1Length;
System.arraycopy(buffer, headIndex + L1_CACHE_LINE_SIZE, cbuf, off, block1Length);
System.arraycopy(buffer, L1_CACHE_LINE_SIZE, cbuf, off+ block1Length, block2Length);
return block1Length + block2Length;
}
public void close() throws IOException {
dataProducer.stop();
reader.close();
}
private final class DataProducer implements Runnable {
private volatile boolean run = true;
private volatile IOException exception;
private int readSize;
public DataProducer(int readSize) {
this.readSize = readSize;
}
@Override
public void run() {
long currentTail = tail;
int i = 0;
while(run) {
final long wrapPoint = currentTail - capacity + tailPadding + readSize;
if (headCache <= wrapPoint) {
headCache = head;
if (headCache <= wrapPoint) {
i = waitingStrategy.idle(i);
continue;
}
}
i = 0;
try {
int used = (int)(currentTail - headCache);
int writable = capacity - used - tailPadding;
int tailIndex = (int) (currentTail & bufferMask);
int endBlock1 = Math.min(tailIndex + writable, capacity );
int block1Length = endBlock1 - tailIndex;
int l = Math.min(block1Length, readSize);
int r = reader.read(buffer, tailIndex + L1_CACHE_LINE_SIZE, l);
if (r != -1) {
currentTail += r;
tail = currentTail;
} else {
run = false;
}
} catch (IOException e) {
exception = e;
run = false;
}
}
}
public void stop() {
run = false;
}
}
} |
package hudson;
import hudson.model.Hudson;
import hudson.slaves.SlaveComputer;
import hudson.remoting.Channel;
import hudson.remoting.Channel.Listener;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Listens to incoming TCP connections from JNLP slave agents.
*
* <h2>Security</h2>
* <p>
* Once connected, remote slave agents can send in commands to be
* executed on the master, so in a way this is like an rsh service.
* Therefore, it is important that we reject connections from
* unauthorized remote slaves.
*
* <p>
* The approach here is to have {@link Hudson#getSecretKey() a secret key} on the master.
* This key is sent to the slave inside the <tt>.jnlp</tt> file
* (this file itself is protected by HTTP form-based authentication that
* we use everywhere else in Hudson), and the slave sends this
* token back when it connects to the master.
* Unauthorized slaves can't access the protected <tt>.jnlp</tt> file,
* so it can't impersonate a valid slave.
*
* <p>
* We don't want to force the JNLP slave agents to be restarted
* whenever the server restarts, so right now this secret master key
* is generated once and used forever, which makes this whole scheme
* less secure.
*
* @author Kohsuke Kawaguchi
*/
public final class TcpSlaveAgentListener extends Thread {
private final ServerSocket serverSocket;
private volatile boolean shuttingDown;
public final int configuredPort;
/**
* @param port
* Use 0 to choose a random port.
*/
public TcpSlaveAgentListener(int port) throws IOException {
super("TCP slave agent listener port="+port);
serverSocket = new ServerSocket(port);
this.configuredPort = port;
LOGGER.info("JNLP slave agent listener started on TCP port "+getPort());
start();
}
/**
* Gets the TCP port number in which we are listening.
*/
public int getPort() {
return serverSocket.getLocalPort();
}
private String getSecretKey() {
return Hudson.getInstance().getSecretKey();
}
public void run() {
try {
// the loop eventually terminates when the socket is closed.
while (true) {
Socket s = serverSocket.accept();
new ConnectionHandler(s).start();
}
} catch (IOException e) {
if(!shuttingDown) {
LOGGER.log(Level.SEVERE,"Failed to accept JNLP slave agent connections",e);
}
}
}
/**
* Initiates the shuts down of the listener.
*/
public void shutdown() {
shuttingDown = true;
try {
serverSocket.close();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to close down TCP port",e);
}
}
private final class ConnectionHandler extends Thread {
private final Socket s;
/**
* Unique number to identify this connection. Used in the log.
*/
private final int id;
public ConnectionHandler(Socket s) {
this.s = s;
synchronized(getClass()) {
id = iotaGen++;
}
}
public void run() {
try {
LOGGER.info("Accepted connection #"+id+" from "+s.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(s.getInputStream());
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
String s = in.readUTF();
if(s.startsWith("Protocol:")) {
String protocol = s.substring(9);
if(protocol.equals("JNLP-connect")) {
runJnlpConnect(in, out);
} else {
error(out, "Unknown protocol:" + s);
}
} else {
error(out, "Unrecognized protocol: "+s);
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e);
try {
s.close();
} catch (IOException _) {
// try to clean up the socket
}
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Connection #"+id+" failed",e);
try {
s.close();
} catch (IOException _) {
// try to clean up the socket
}
}
}
/**
* Handles JNLP slave agent connection request.
*/
private void runJnlpConnect(DataInputStream in, PrintWriter out) throws IOException, InterruptedException {
if(!getSecretKey().equals(in.readUTF())) {
error(out, "Unauthorized access");
return;
}
String nodeName = in.readUTF();
SlaveComputer computer = (SlaveComputer) Hudson.getInstance().getComputer(nodeName);
if(computer==null) {
error(out, "No such slave: "+nodeName);
return;
}
if(computer.getChannel()!=null) {
error(out, nodeName+" is already connected to this master. Rejecting this connection.");
return;
}
out.println("Welcome");
final OutputStream log = computer.openLogFile();
new PrintWriter(log).println("JNLP agent connected from "+ this.s.getInetAddress());
computer.setChannel(new BufferedInputStream(this.s.getInputStream()), new BufferedOutputStream(this.s.getOutputStream()), log,
new Listener() {
public void onClosed(Channel channel, IOException cause) {
try {
log.close();
} catch (IOException e) {
e.printStackTrace();
}
if(cause!=null)
LOGGER.log(Level.WARNING, "Connection #"+id+" terminated",cause);
try {
ConnectionHandler.this.s.close();
} catch (IOException e) {
// ignore
}
}
});
}
private void error(PrintWriter out, String msg) throws IOException {
out.println(msg);
LOGGER.log(Level.WARNING,"Connection #"+id+" is aborted: "+msg);
s.close();
}
}
private static int iotaGen=1;
private static final Logger LOGGER = Logger.getLogger(TcpSlaveAgentListener.class.getName());
} |
package hudson;
import hudson.slaves.OfflineCause;
import jenkins.AgentProtocol;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Listens to incoming TCP connections from JNLP slave agents and CLI.
*
* <p>
* Aside from the HTTP endpoint, Jenkins runs {@link TcpSlaveAgentListener} that listens on a TCP socket.
* Historically this was used for inbound connection from slave agents (hence the name), but over time
* it was extended and made generic, so that multiple protocols of different purposes can co-exist on the
* same socket.
*
* <p>
* This class accepts the socket, then after a short handshaking, it dispatches to appropriate
* {@link AgentProtocol}s.
*
* @author Kohsuke Kawaguchi
* @see AgentProtocol
*/
public final class TcpSlaveAgentListener extends Thread {
private final ServerSocketChannel serverSocket;
private volatile boolean shuttingDown;
public final int configuredPort;
/**
* @param port
* Use 0 to choose a random port.
*/
public TcpSlaveAgentListener(int port) throws IOException {
super("TCP slave agent listener port="+port);
try {
serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(port));
} catch (BindException e) {
throw (BindException)new BindException("Failed to listen on port "+port+" because it's already in use.").initCause(e);
}
this.configuredPort = port;
LOGGER.log(Level.FINE, "JNLP slave agent listener started on TCP port {0}", getPort());
start();
}
/**
* Gets the TCP port number in which we are listening.
*/
public int getPort() {
return serverSocket.socket().getLocalPort();
}
@Override
public void run() {
try {
// the loop eventually terminates when the socket is closed.
while (true) {
Socket s = serverSocket.accept().socket();
// this prevents a connection from silently terminated by the router in between or the other peer
// and that goes without unnoticed. However, the time out is often very long (for example 2 hours
// by default in Linux) that this alone is enough to prevent that.
s.setKeepAlive(true);
// we take care of buffering on our own
s.setTcpNoDelay(true);
new ConnectionHandler(s).start();
}
} catch (IOException e) {
if(!shuttingDown) {
LOGGER.log(Level.SEVERE,"Failed to accept JNLP slave agent connections",e);
}
}
}
/**
* Initiates the shuts down of the listener.
*/
public void shutdown() {
shuttingDown = true;
try {
serverSocket.close();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to close down TCP port",e);
}
}
private final class ConnectionHandler extends Thread {
private final Socket s;
/**
* Unique number to identify this connection. Used in the log.
*/
private final int id;
public ConnectionHandler(Socket s) {
this.s = s;
synchronized(getClass()) {
id = iotaGen++;
}
setName("TCP slave agent connection handler #"+id+" with "+s.getRemoteSocketAddress());
}
@Override
public void run() {
try {
LOGGER.info("Accepted connection #"+id+" from "+s.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(s.getInputStream());
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")),
true); // DEPRECATED: newer protocol shouldn't use PrintWriter but should use DataOutputStream
String s = in.readUTF();
if(s.startsWith("Protocol:")) {
String protocol = s.substring(9);
AgentProtocol p = AgentProtocol.of(protocol);
if (p!=null)
p.handle(this.s);
else
error(out, "Unknown protocol:" + s);
} else {
error(out, "Unrecognized protocol: "+s);
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e);
try {
s.close();
} catch (IOException _) {
// try to clean up the socket
}
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Connection #"+id+" failed",e);
try {
s.close();
} catch (IOException _) {
// try to clean up the socket
}
}
}
private void error(PrintWriter out, String msg) throws IOException {
out.println(msg);
LOGGER.log(Level.WARNING,"Connection #"+id+" is aborted: "+msg);
s.close();
}
}
/**
* Connection terminated because we are reconnected from the current peer.
*/
public static class ConnectionFromCurrentPeer extends OfflineCause {
public String toString() {
return "The current peer is reconnecting";
}
}
private static int iotaGen=1;
private static final Logger LOGGER = Logger.getLogger(TcpSlaveAgentListener.class.getName());
/**
* Host name that we advertise the CLI client to connect to.
* This is primarily for those who have reverse proxies in place such that the HTTP host name
* and the CLI TCP/IP connection host names are different.
*
* TODO: think about how to expose this (including whether this needs to be exposed at all.)
*/
public static String CLI_HOST_NAME = System.getProperty(TcpSlaveAgentListener.class.getName()+".hostName");
} |
package org.spout.renderer.software;
import java.nio.ByteBuffer;
import com.flowpowered.math.vector.Vector4f;
import org.spout.renderer.api.GLImplementation;
import org.spout.renderer.api.data.VertexAttribute.DataType;
import org.spout.renderer.api.util.CausticUtil;
public final class SoftwareUtil {
private static final float BYTE_RANGE = Byte.MAX_VALUE - Byte.MIN_VALUE;
private static final float SHORT_RANGE = Short.MAX_VALUE - Short.MIN_VALUE;
private static final float INT_RANGE = (float) Integer.MAX_VALUE - Integer.MIN_VALUE;
private static final int BYTE_MASK = 0xFF;
private static final int SHORT_MASK = 0xFFFF;
public static final GLImplementation SOFT_IMPL = new GLImplementation(null, SoftwareContext.class.getName());
private SoftwareUtil() {
}
static ByteBuffer create(ByteBuffer buffer, int newCapacity, float threshold) {
final int oldCapacity = buffer != null ? buffer.capacity() : 0;
if (buffer == null || newCapacity > oldCapacity || newCapacity <= oldCapacity * threshold) {
return CausticUtil.createByteBuffer(newCapacity);
} else {
buffer.clear();
return buffer;
}
}
static ByteBuffer set(ByteBuffer buffer, ByteBuffer newData, float threshold) {
final int newCapacity = newData.remaining();
buffer = create(buffer, newCapacity, threshold);
buffer.put(newData);
buffer.flip();
return buffer;
}
static ByteBuffer setAsFloat(ByteBuffer buffer, ByteBuffer newData, DataType type, float threshold, boolean normalize) {
final int elementCount = newData.remaining() / type.getByteSize();
final int newCapacity = elementCount << DataType.FLOAT.getMultiplyShift();
buffer = create(buffer, newCapacity, threshold);
for (int i = 0; i < elementCount; i++) {
buffer.putFloat(toFloat(type, read(newData, type), normalize));
}
buffer.flip();
return buffer;
}
static int read(ByteBuffer data, DataType type) {
switch (type) {
case BYTE:
return data.get();
case SHORT:
return data.getShort();
case INT:
case FLOAT:
return data.getInt();
default:
throw new IllegalArgumentException("Unsupported data type: " + type);
}
}
static int read(ByteBuffer data, DataType type, int i) {
i <<= type.getMultiplyShift();
switch (type) {
case BYTE:
return data.get(i);
case SHORT:
return data.getShort(i);
case INT:
case FLOAT:
return data.getInt(i);
default:
throw new IllegalArgumentException("Unsupported data type: " + type);
}
}
static void write(ByteBuffer data, DataType type, int value) {
switch (type) {
case BYTE:
data.put((byte) (value & BYTE_MASK));
break;
case SHORT:
data.putShort((short) (value & SHORT_MASK));
break;
case INT:
case FLOAT:
data.putInt(value);
break;
default:
throw new IllegalArgumentException("Unsupported data type: " + type);
}
}
static void write(ByteBuffer data, DataType type, int value, int i) {
i <<= type.getMultiplyShift();
switch (type) {
case BYTE:
data.put(i, (byte) (value & BYTE_MASK));
break;
case SHORT:
data.putShort(i, (short) (value & SHORT_MASK));
break;
case INT:
case FLOAT:
data.putInt(i, value);
break;
default:
throw new IllegalArgumentException("Unsupported data type: " + type);
}
}
static void advance(ByteBuffer data, DataType type) {
advance(data, type, 1);
}
static void advance(ByteBuffer data, DataType type, int n) {
data.position(data.position() + n << type.getMultiplyShift());
}
static void copy(ByteBuffer source, DataType sourceType, ByteBuffer destination, DataType destinationType) {
write(destination, destinationType, read(source, sourceType));
}
static void copy(ByteBuffer source, DataType sourceType, int is, ByteBuffer destination, DataType destinationType, int id) {
write(destination, destinationType, read(source, sourceType, id), is);
}
static float toFloat(DataType type, int value, boolean normalize) {
final float f;
switch (type) {
case BYTE:
f = (byte) (value & BYTE_MASK);
return normalize ? (f - Byte.MIN_VALUE) / BYTE_RANGE : f;
case SHORT:
f = (short) (value & SHORT_MASK);
return normalize ? (f - Short.MIN_VALUE) / SHORT_RANGE : f;
case INT:
f = value;
return normalize ? (f - Integer.MIN_VALUE) / INT_RANGE : f;
case FLOAT:
f = Float.intBitsToFloat(value);
return f;
default:
throw new IllegalArgumentException("Unsupported data type: " + type);
}
}
static int pack(Vector4f v) {
return pack(v.getX(), v.getY(), v.getZ(), v.getW());
}
static int pack(float r, float g, float b, float a) {
return ((int) (a * 255) & 0xFF) << 24 | ((int) (r * 255) & 0xFF) << 16 | ((int) (g * 255) & 0xFF) << 8 | (int) (b * 255) & 0xFF;
}
static short denormalizeToShort(float f) {
return (short) (f * SHORT_RANGE + Short.MIN_VALUE);
}
} |
package roart.config;
import java.util.HashMap;
import java.util.Map;
import roart.calculate.CalcMACDNode;
public class ConfigConstants {
public static final String PROPFILE = "stockstat.prop";
public static final String CONFIGFILE = "stockstat.xml";
public static final String SPARK = "spark";
public static final String HIBERNATE = "hibernate";
public static final String SPARKMASTER = "sparkmaster";
public static final String[] dbvalues = { HIBERNATE, SPARK };
public static final String TENSORFLOW = "tensorflow";
public static final String DATABASESPARK = "database.spark[@enable]";
public static final String DATABASESPARKSPARKMASTER = "database.spark.sparkmaster";
public static final String DATABASEHIBERNATE = "database.hibernate[@enable]";
public static final String MACHINELEARNING = "machinelearning[@enable]";
public static final String MACHINELEARNINGSPARKML = "machinelearning.sparkml[@enable]";
public static final String MACHINELEARNINGSPARMMLSPARKMASTER = "machinelearning.sparkml.sparkmaster";
public static final String MACHINELEARNINGSPARKMLMCP = "machinelearning.sparkml.mcp[@enable]";
public static final String MACHINELEARNINGSPARKMLLR = "machinelearning.sparkml.lr[@enable]";
public static final String MACHINELEARNINGTENSORFLOW = "machinelearning.tensorflow[@enable]";
public static final String MACHINELEARNINGTENSORFLOWDNN = "machinelearning.tensorflow.dnn[@enable]";
public static final String MACHINELEARNINGTENSORFLOWL = "machinelearning.tensorflow.l[@enable]";
public static final String INDICATORS = "indicators[@enable]";
public static final String INDICATORSMOVE = "indicators.move[@enable]";
public static final String INDICATORSMACD = "indicators.macd[@enable]";
public static final String INDICATORSMACDMACDHISTOGRAMDELTA = "indicators.macd.macdhistogramdelta[@enable]";
public static final String INDICATORSMACDMACHHISTOGRAMDELTADAYS = "indicators.macd.macdhistogramdeltadays";
public static final String INDICATORSMACDMACDMOMENTUMDELTA = "indicators.macd.macdmomentumdelta[@enable]";
public static final String INDICATORSMACDACDMOMENTUMDELTADAYS = "indicators.macd.macdmomentumdeltadays";
public static final String INDICATORSMACDRECOMMENDWEIGHTS = "indicators.macd.recommend[@enable]";
public static final String INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAM = "indicators.macd.recommend.weightbuyhistogram";
public static final String INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAMDELTA = "indicators.macd.recommend.weightbuyhistogramdelta";
public static final String INDICATORSMACDRECOMMENDWEIGHTSBUYMOMENTUM = "indicators.macd.recommend.weightbuymomemtum";
public static final String INDICATORSMACDRECOMMENDWEIGHTSBUGMOMENTUMDELTA = "indicators.macd.recommend.weightbuymomemtumdelta";
public static final String INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAM = "indicators.macd.recommend.weightsellhistogram";
public static final String INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAMDELTA = "indicators.macd.recommend.weightsellhistogramdelta";
public static final String INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUM = "indicators.macd.recommend.weightsellmomemtum";
public static final String INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUMDELTA = "indicators.macd.recommend.weightsellmomemtumdelta";
public static final String INDICATORSMACDMACHINELEARNING = "indicators.macd.machinelearning[@enable]";
public static final String INDICATORSMACDMACHINELEARNINGMOMENTUMML = "indicators.macd.machinelearning.momemtumml[@enable]";
public static final String INDICATORSMACDMACHINELEARNINGHISTOGRAMML = "indicators.macd.machinelearning.histogramml[@enable]";
public static final String INDICATORSMACDDAYSBEFOREZERO ="indicators.macd.daysbeforezero";
public static final String INDICATORSMACDDAYSAFTERZERO = "indicators.macd.daysafterzero";
public static final String INDICATORSRSI = "indicators.rsi[@enable]";
public static final String INDICATORSRSIDELTA = "indicators.rsi.rsidelta[@enable]";
public static final String INDICATORSRSIDELTADAYS = "indicators.rsi.rsideltadays";
public static final String INDICATORSSTOCHRSI = "indicators.stochrsi[@enable]";
public static final String INDICATORSSTOCHRSIDELTA = "indicators.stochrsi.stochrsidelta[@enable]";
public static final String INDICATORSSTOCHRSIDELTADAYS = "indicators.stochrsi.stochrsideltadays";
public static final String INDICATORSRSIRECOMMENDWEIGHTS = "indicators.rsi.recommend[@enable]";
public static final String INDICATORSRSIRECOMMENDWEIGHTSBUY = "indicators.rsi.recommend.weightbuy";
public static final String INDICATORSRSIRECOMMENDWEIGHTSBUYDELTA = "indicators.rsi.recommend.weightbuydelta";
public static final String INDICATORSRSIRECOMMENDWEIGHTSSELL = "indicators.rsi.recommend.weightsell";
public static final String INDICATORSRSIRECOMMENDWEIGHTSSELLDELTA = "indicators.rsi.recommend.weightselldelta";
public static final String INDICATORSCCI = "indicators.cci[@enable]";
public static final String INDICATORSCCIDELTA ="indicators.cci.ccidelta[@enable]";
public static final String INDICATORSCCIDELTADAYS = "indicators.cci.ccideltadays";
public static final String INDICATORSATR ="indicators.atr[@enable]";
public static final String INDICATORSATRDELTA = "indicators.atr.atrdelta[@enable]";
public static final String INDICATORSATRDELTADAYS = "indicators.atr.atrdeltadays";
public static final String INDICATORSSTOCH = "indicators.stoch[@enable]";
public static final String INDICATORSSTOCHSTOCHDELTA ="indicators.stoch.stochdelta[@enable]";
public static final String INDICATORSSTOCHSTOCHDELTADAYS = "indicators.stoch.stochdeltadays";
public static final String PREDICTORS = "predictors[@enable]";
public static final String PREDICTORSLSTM = "predictors.lstm[@enable]";
public static final String PREDICTORSLSTMWINDOWSIZE = "predictors.lstm.windowsize";
public static final String PREDICTORSLSTMHORIZON = "predictors.lstm.horizon";
public static final String PREDICTORSLSTMEPOCHS = "predictors.lstm.epochs";
public static final String MISC = "misc";
public static final String MISCPERCENTIZEPRICEINDEX = "misc.percentizepriceindex[@enable]";
public static final String MISCMLSTATS = "misc.mlstats[@enable]";
public static final String MISCOTHERSTATS = "misc.otherstats[@enable]";
public static final String MISCMYDAYS = "misc.mydays";
public static final String MISCMYTOPBOTTOM = "misc.mytopbottom";
public static final String MISCMYTBLEDAYS = "misc.mytabledays";
public static final String MISCMYTABLEMOVEINTERVALDAYS = "misc.mytablemoveintervaldays";
public static final String MISCMYTABLEINTERVALDAYS = "misc.mytableintervaldays";
public static final String MISCMYEQUALIZE = "misc.myequalize[@enable]";
public static final String MISCMYGRAPHEQUALIZE = "misc.mygraphequalize[@enable]";
public static final String MISCMYGRAPHEQUALIZEUNIFY = "misc.mygraphequalizeunify[@enable]";
public static final String TESTRECOMMENDFUTUREDAYS = "test.recommend.futuredays";
public static final String TESTRECOMMENDINTERVALDAYS = "test.recommend.intervaldays";
@Deprecated
public static final String TESTRECOMMENDINTERVALTIMES = "test.recommend.intervaltimes";
public static final String TESTRECOMMENDITERATIONS = "test.recommend.iterations";
public static final String TESTRECOMMENDPERIOD = "test.recommend.period";
public static final String TESTRECOMMENDGENERATIONS = "test.recommend.generations";
public static final String TESTRECOMMENDCHILDREN = "test.recommend.children";
public static final String TESTRECOMMENDSELECT = "test.recommend.select";
public static final String TESTRECOMMENDELITE= "test.recommend.elite";
public static final String TESTRECOMMENDMUTATE = "test.recommend.mutate";
public static final String TESTRECOMMENDCROSSOVER = "test.recommend.crossover";
public static final String AGGREGATORS = "aggregators[@enable]";
public static final String AGGREGATORSMACDRSIRECOMMENDER = "aggregators.macdrsirecommender[@enable]";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAM = "aggregators.macdrsirecommender.weightbuyhistogram";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTA = "aggregators.macdrsirecommender.weightbuyhistogramdelta";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUM = "aggregators.macdrsirecommender.weightbuymomemtum";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTA = "aggregators.macdrsirecommender.weightbuymomemtumdelta";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMRSI = "aggregators.macdrsirecommender.weightbuyrsi";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTA = "aggregators.macdrsirecommender.weightbuyrsidelta";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAM = "aggregators.macdrsirecommender.weightsellhistogram";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTA = "aggregators.macdrsirecommender.weightsellhistogramdelta";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUM = "aggregators.macdrsirecommender.weightsellmomemtum";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTA = "aggregators.macdrsirecommender.weightsellmomemtumdelta";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSI = "aggregators.macdrsirecommender.weightsellrsi";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTA = "aggregators.macdrsirecommender.weightsellrsidelta";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMNODE = "aggregators.macdrsirecommender.weightbuyhistogramnode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTANODE = "aggregators.macdrsirecommender.weightbuyhistogramdeltanode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMNODE = "aggregators.macdrsirecommender.weightbuymomemtumnode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTANODE = "aggregators.macdrsirecommender.weightbuymomemtumdeltanode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSINODE = "aggregators.macdrsirecommender.weightbuyrsinode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTANODE = "aggregators.macdrsirecommender.weightbuyrsideltanode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMNODE = "aggregators.macdrsirecommender.weightsellhistogramnode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTANODE = "aggregators.macdrsirecommender.weightsellhistogramdeltanode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMNODE = "aggregators.macdrsirecommender.weightsellmomemtumnode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTANODE = "aggregators.macdrsirecommender.weightsellmomemtumdeltanode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSINODE = "aggregators.macdrsirecommender.weightsellrsinode";
public static final String AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTANODE = "aggregators.macdrsirecommender.weightsellrsideltanode";
public static Map<String, Class> map = new HashMap();
public static void makeTypeMap() {
if (!map.isEmpty()) {
return;
}
map.put(ConfigConstants.DATABASESPARK, Boolean.class);
map.put(ConfigConstants.DATABASESPARKSPARKMASTER, String.class);
map.put(ConfigConstants.DATABASEHIBERNATE, Boolean.class);
map.put(ConfigConstants.MACHINELEARNING, Boolean.class);
map.put(ConfigConstants.MACHINELEARNINGSPARKML, Boolean.class);
map.put(ConfigConstants.MACHINELEARNINGSPARMMLSPARKMASTER, String.class);
map.put(ConfigConstants.MACHINELEARNINGSPARKMLMCP, Boolean.class);
map.put(ConfigConstants.MACHINELEARNINGSPARKMLLR, Boolean.class);
map.put(ConfigConstants.MACHINELEARNINGTENSORFLOW, Boolean.class);
map.put(ConfigConstants.MACHINELEARNINGTENSORFLOWDNN, Boolean.class);
map.put(ConfigConstants.MACHINELEARNINGTENSORFLOWL, Boolean.class);
map.put(ConfigConstants.INDICATORS, Boolean.class);
map.put(ConfigConstants.INDICATORSMOVE, Boolean.class);
map.put(ConfigConstants.INDICATORSMACD, Boolean.class);
map.put(ConfigConstants.INDICATORSMACDMACDHISTOGRAMDELTA, Boolean.class);
map.put(ConfigConstants.INDICATORSMACDMACHHISTOGRAMDELTADAYS, Integer.class);
map.put(ConfigConstants. INDICATORSMACDMACDMOMENTUMDELTA, Boolean.class);
map.put(ConfigConstants.INDICATORSMACDACDMOMENTUMDELTADAYS, Integer.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTS, Boolean.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAM, Integer.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAMDELTA, Integer.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYMOMENTUM, Integer.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUGMOMENTUMDELTA, Integer.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAM, Integer.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAMDELTA, Integer.class);
map.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUM, Integer.class);
map.put(ConfigConstants.INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUMDELTA, Integer.class);
map.put(ConfigConstants.INDICATORSMACDMACHINELEARNING, Boolean.class);
map.put(ConfigConstants.INDICATORSMACDMACHINELEARNINGMOMENTUMML, Boolean.class);
map.put(ConfigConstants.INDICATORSMACDMACHINELEARNINGHISTOGRAMML, Boolean.class);
map.put(ConfigConstants. INDICATORSMACDDAYSBEFOREZERO , Integer.class);
map.put(ConfigConstants. INDICATORSMACDDAYSAFTERZERO, Integer.class);
map.put(ConfigConstants. INDICATORSRSI, Boolean.class);
map.put(ConfigConstants. INDICATORSRSIDELTA, Boolean.class);
map.put(ConfigConstants. INDICATORSRSIDELTADAYS, Integer.class);
map.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTS, Boolean.class);
map.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSBUY, Integer.class);
map.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSBUYDELTA, Integer.class);
map.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSSELL, Integer.class);
map.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSSELLDELTA, Integer.class);
map.put(ConfigConstants. INDICATORSSTOCHRSI, Boolean.class);
map.put(ConfigConstants. INDICATORSSTOCHRSIDELTA, Boolean.class);
map.put(ConfigConstants. INDICATORSSTOCHRSIDELTADAYS, Integer.class);
map.put(ConfigConstants. INDICATORSCCI, Boolean.class);
map.put(ConfigConstants. INDICATORSCCIDELTA , Boolean.class);
map.put(ConfigConstants.INDICATORSCCIDELTADAYS, Integer.class);
map.put(ConfigConstants.INDICATORSATR , Boolean.class);
map.put(ConfigConstants.INDICATORSATRDELTA, Boolean.class);
map.put(ConfigConstants.INDICATORSATRDELTADAYS, Integer.class);
map.put(ConfigConstants.INDICATORSSTOCH, Boolean.class);
map.put(ConfigConstants.INDICATORSSTOCHSTOCHDELTA , Boolean.class);
map.put(ConfigConstants.INDICATORSSTOCHSTOCHDELTADAYS, Integer.class);
map.put(ConfigConstants.PREDICTORS, Boolean.class);
map.put(ConfigConstants.PREDICTORSLSTM, Boolean.class);
map.put(ConfigConstants.PREDICTORSLSTMEPOCHS, Integer.class);
map.put(ConfigConstants.PREDICTORSLSTMHORIZON, Integer.class);
map.put(ConfigConstants.PREDICTORSLSTMWINDOWSIZE, Integer.class);
map.put(ConfigConstants.MISC, Boolean.class);
map.put(ConfigConstants.MISCPERCENTIZEPRICEINDEX, Boolean.class);
map.put(ConfigConstants.MISCMLSTATS, Boolean.class);
map.put(ConfigConstants.MISCOTHERSTATS, Boolean.class);
map.put(ConfigConstants.MISCMYDAYS, Integer.class);
map.put(ConfigConstants.MISCMYTOPBOTTOM, Integer.class);
map.put(ConfigConstants.MISCMYTBLEDAYS, Integer.class);
map.put(ConfigConstants.MISCMYTABLEMOVEINTERVALDAYS, Integer.class);
map.put(ConfigConstants.MISCMYTABLEINTERVALDAYS, Integer.class);
map.put(ConfigConstants.MISCMYEQUALIZE, Boolean.class);
map.put(ConfigConstants.MISCMYGRAPHEQUALIZE, Boolean.class);
map.put(ConfigConstants.MISCMYGRAPHEQUALIZEUNIFY, Boolean.class);
map.put(ConfigConstants.TESTRECOMMENDFUTUREDAYS, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDINTERVALDAYS, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDINTERVALTIMES, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDITERATIONS, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDPERIOD, String.class);
map.put(ConfigConstants.TESTRECOMMENDGENERATIONS, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDCHILDREN, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDCROSSOVER, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDELITE, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDMUTATE, Integer.class);
map.put(ConfigConstants.TESTRECOMMENDSELECT, Integer.class);
map.put(ConfigConstants.AGGREGATORS, Boolean.class);
map.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDER, Boolean.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAM , Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTA , Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUM , Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTA , Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMRSI, Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTA , Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAM , Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTA, Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUM , Integer.class);
map.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTA, Integer.class);
map.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSI, Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTA, Integer.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMNODE , String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTANODE , String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMNODE , String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTANODE , String.class);
map.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSINODE, String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTANODE , String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMNODE , String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTANODE , String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMNODE , String.class);
map.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTANODE, String.class);
map.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSINODE, String.class);
map.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTANODE, String.class);
}
public static Map<String, Object> deflt = new HashMap();
public static void makeDefaultMap() {
if (!deflt.isEmpty()) {
return;
}
deflt.put(ConfigConstants.DATABASESPARK, Boolean.TRUE);
deflt.put(ConfigConstants.DATABASESPARKSPARKMASTER, "spark://127.0.0.1:7077");
deflt.put(ConfigConstants.DATABASEHIBERNATE, Boolean.TRUE);
deflt.put(ConfigConstants.MACHINELEARNING, Boolean.TRUE);
deflt.put(ConfigConstants.MACHINELEARNINGSPARKML, Boolean.TRUE);
deflt.put(ConfigConstants.MACHINELEARNINGSPARMMLSPARKMASTER, "spark://127.0.0.1:7077");
deflt.put(ConfigConstants.MACHINELEARNINGSPARKMLMCP, Boolean.TRUE);
deflt.put(ConfigConstants.MACHINELEARNINGSPARKMLLR, Boolean.TRUE);
deflt.put(ConfigConstants.MACHINELEARNINGTENSORFLOW, Boolean.TRUE);
deflt.put(ConfigConstants.MACHINELEARNINGTENSORFLOWDNN, Boolean.TRUE);
deflt.put(ConfigConstants.MACHINELEARNINGTENSORFLOWL, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORS, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSMOVE, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSMACD, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSMACDMACDHISTOGRAMDELTA, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSMACDMACHHISTOGRAMDELTADAYS, 3);
deflt.put(ConfigConstants. INDICATORSMACDMACDMOMENTUMDELTA, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSMACDACDMOMENTUMDELTADAYS, 3);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTS, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAM, 40);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAMDELTA, 20);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYMOMENTUM, 20);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUGMOMENTUMDELTA, 20);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAM, 40);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAMDELTA, 20);
deflt.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUM, 20);
deflt.put(ConfigConstants.INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUMDELTA, 20);
deflt.put(ConfigConstants.INDICATORSMACDMACHINELEARNING, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSMACDMACHINELEARNINGMOMENTUMML, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSMACDMACHINELEARNINGHISTOGRAMML, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSMACDDAYSBEFOREZERO , 25);
deflt.put(ConfigConstants. INDICATORSMACDDAYSAFTERZERO, 10);
deflt.put(ConfigConstants. INDICATORSRSI, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSRSIDELTA, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSRSIDELTADAYS, 3);
deflt.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTS, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSBUY, 50);
deflt.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSBUYDELTA, 50);
deflt.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSSELL, 50);
deflt.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSSELLDELTA, 50);
deflt.put(ConfigConstants. INDICATORSSTOCHRSI, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSSTOCHRSIDELTA, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSSTOCHRSIDELTADAYS, 3);
deflt.put(ConfigConstants. INDICATORSCCI, Boolean.TRUE);
deflt.put(ConfigConstants. INDICATORSCCIDELTA , Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSCCIDELTADAYS, 3);
deflt.put(ConfigConstants.INDICATORSATR , Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSATRDELTA, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSATRDELTADAYS, 3);
deflt.put(ConfigConstants.INDICATORSSTOCH, Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSSTOCHSTOCHDELTA , Boolean.TRUE);
deflt.put(ConfigConstants.INDICATORSSTOCHSTOCHDELTADAYS, 3);
deflt.put(ConfigConstants.PREDICTORS, Boolean.TRUE);
deflt.put(ConfigConstants.PREDICTORSLSTM, Boolean.TRUE);
deflt.put(ConfigConstants.PREDICTORSLSTMEPOCHS, 5);
deflt.put(ConfigConstants.PREDICTORSLSTMHORIZON, 5);
deflt.put(ConfigConstants.PREDICTORSLSTMWINDOWSIZE, 3);
deflt.put(ConfigConstants.MISC, Boolean.TRUE);
deflt.put(ConfigConstants.MISCPERCENTIZEPRICEINDEX, Boolean.TRUE);
deflt.put(ConfigConstants.MISCMLSTATS, Boolean.TRUE);
deflt.put(ConfigConstants.MISCOTHERSTATS, Boolean.TRUE);
deflt.put(ConfigConstants.MISCMYDAYS, Integer.class);
deflt.put(ConfigConstants.MISCMYTOPBOTTOM, 10);
deflt.put(ConfigConstants.MISCMYTBLEDAYS, 180);
deflt.put(ConfigConstants.MISCMYTABLEMOVEINTERVALDAYS, 5);
deflt.put(ConfigConstants.MISCMYTABLEINTERVALDAYS, 1);
deflt.put(ConfigConstants.MISCMYEQUALIZE, Boolean.TRUE);
deflt.put(ConfigConstants.MISCMYGRAPHEQUALIZE, Boolean.TRUE);
deflt.put(ConfigConstants.MISCMYGRAPHEQUALIZEUNIFY, Boolean.TRUE);
deflt.put(ConfigConstants.TESTRECOMMENDFUTUREDAYS, 10);
deflt.put(ConfigConstants.TESTRECOMMENDINTERVALDAYS, 5);
deflt.put(ConfigConstants.TESTRECOMMENDINTERVALTIMES, 10);
deflt.put(ConfigConstants.TESTRECOMMENDITERATIONS, 100);
deflt.put(ConfigConstants.TESTRECOMMENDPERIOD, "Price");
deflt.put(ConfigConstants.TESTRECOMMENDGENERATIONS, 2);
deflt.put(ConfigConstants.TESTRECOMMENDCHILDREN, 4);
deflt.put(ConfigConstants.TESTRECOMMENDELITE, 1);
deflt.put(ConfigConstants.TESTRECOMMENDMUTATE, 1);
deflt.put(ConfigConstants.TESTRECOMMENDCROSSOVER, 1);
deflt.put(ConfigConstants.TESTRECOMMENDSELECT, 16);
deflt.put(ConfigConstants.AGGREGATORS, Boolean.TRUE);
deflt.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDER, Boolean.TRUE);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAM , 40);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTA , 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUM , 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTA , 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMRSI, 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTA , 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAM , 40);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTA, 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUM , 20);
deflt.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTA, 20);
deflt.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSI, 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTA, 20);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMNODE , json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTANODE , json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMNODE , json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTANODE , json);
deflt.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSINODE, json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTANODE , json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMNODE , json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTANODE, json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMNODE , json);
deflt.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTANODE, json);
deflt.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSINODE, json);
deflt.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTANODE, json);
}
private final static String json = "{\"_class\": \"roart.calculate.CalcMACDNode\", \"className\":null,\"minMutateThresholdRange\":-5.0,\"maxMutateThresholdRange\":5.0,\"threshold\":-2.476814906438654,\"useminmaxthreshold\":true,\"usethreshold\":false,\"divideminmaxthreshold\":true,\"weight\":31.0,\"changeSignWhole\":false,\"doBuy\":false}";
public static Map<String, String> text = new HashMap();
public static void makeTextMap() {
if (!text.isEmpty()) {
return;
}
text.put(ConfigConstants.DATABASESPARK, "Enable Spark Database backend");
text.put(ConfigConstants.DATABASESPARKSPARKMASTER, "Database Spark Master");
text.put(ConfigConstants.DATABASEHIBERNATE, "Enable Hibernate Database backend");
text.put(ConfigConstants.MACHINELEARNING, "Enable machine learning");
text.put(ConfigConstants.MACHINELEARNINGSPARKML, "Enable Spark ML");
text.put(ConfigConstants.MACHINELEARNINGSPARMMLSPARKMASTER, "Machine Learning Spark Master");
text.put(ConfigConstants.MACHINELEARNINGSPARKMLMCP, "Enable Spark ML MCP");
text.put(ConfigConstants.MACHINELEARNINGSPARKMLLR, "Enable Spark ML LR");
text.put(ConfigConstants.MACHINELEARNINGTENSORFLOW, "Enable Tensorflow");
text.put(ConfigConstants.MACHINELEARNINGTENSORFLOWDNN, "Enable Tensorflow DNN");
text.put(ConfigConstants.MACHINELEARNINGTENSORFLOWL, "Enable Tensorflow L");
text.put(ConfigConstants.INDICATORS, "Enable indicators");
text.put(ConfigConstants.INDICATORSMOVE, "Enable move indicator");
text.put(ConfigConstants.INDICATORSMACD, "Enable MACD indicator");
text.put(ConfigConstants.INDICATORSMACDMACDHISTOGRAMDELTA, "Enable MACD histogram delta");
text.put(ConfigConstants.INDICATORSMACDMACHHISTOGRAMDELTADAYS, "MACD histogram delta days");
text.put(ConfigConstants. INDICATORSMACDMACDMOMENTUMDELTA, "Enable MACD momentum delta");
text.put(ConfigConstants.INDICATORSMACDACDMOMENTUMDELTADAYS, "MACD momentum delta days");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTS, "Enable MACD buy/sell recommendation");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAM, "Buy weight histogram");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYHISTOGRAMDELTA, "Buy weight histogram delta");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUYMOMENTUM, "Buy weight momentum");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSBUGMOMENTUMDELTA, "Buy weight momentum delta");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAM, "Sell weight histogram");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLHISTOGRAMDELTA, "Sell weight histogram delta");
text.put(ConfigConstants. INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUM, "Sell weight momentum");
text.put(ConfigConstants.INDICATORSMACDRECOMMENDWEIGHTSSELLMOMENTUMDELTA, "Sell weight momentum delta");
text.put(ConfigConstants.INDICATORSMACDMACHINELEARNING, "Enable indicator MACD machine learning");
text.put(ConfigConstants.INDICATORSMACDMACHINELEARNINGMOMENTUMML, "Enable indicator MACD momentum machine learning");
text.put(ConfigConstants.INDICATORSMACDMACHINELEARNINGHISTOGRAMML, "Enable indicator MACD histogram machine learning");
text.put(ConfigConstants. INDICATORSMACDDAYSBEFOREZERO , "Days before zero");
text.put(ConfigConstants. INDICATORSMACDDAYSAFTERZERO, "Days after zero");
text.put(ConfigConstants. INDICATORSRSI, "Enable indicator RSI");
text.put(ConfigConstants. INDICATORSRSIDELTA, "Enable indicator RSI delta");
text.put(ConfigConstants. INDICATORSRSIDELTADAYS, "RSI delta days");
text.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTS, "Enable buy/sell indicator RSI");
text.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSBUY, "RSI buy weight");
text.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSBUYDELTA, "RSI delta buy weight");
text.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSSELL, "RSI sell weight");
text.put(ConfigConstants. INDICATORSRSIRECOMMENDWEIGHTSSELLDELTA, "RSI delta sell weight");
text.put(ConfigConstants. INDICATORSSTOCHRSI, "Enable indicator STOCH RSI");
text.put(ConfigConstants. INDICATORSSTOCHRSIDELTA, "Enable indicator STOCH RSI delta");
text.put(ConfigConstants. INDICATORSSTOCHRSIDELTADAYS, "STOCH RSI delta days");
text.put(ConfigConstants. INDICATORSCCI, "Enable indicator CCI");
text.put(ConfigConstants. INDICATORSCCIDELTA , "Enable indicator CCI delta");
text.put(ConfigConstants.INDICATORSCCIDELTADAYS, "CCI delta days");
text.put(ConfigConstants.INDICATORSATR , "Enable indicator ATR");
text.put(ConfigConstants.INDICATORSATRDELTA, "Enable indicator ATR delta");
text.put(ConfigConstants.INDICATORSATRDELTADAYS, "ATR delta days");
text.put(ConfigConstants.INDICATORSSTOCH, "Enable indicator STOCH");
text.put(ConfigConstants.INDICATORSSTOCHSTOCHDELTA , "Enable indicator STOCH delta");
text.put(ConfigConstants.INDICATORSSTOCHSTOCHDELTADAYS, "STOCH delta days");
text.put(ConfigConstants.PREDICTORS, "Enable predictors");
text.put(ConfigConstants.PREDICTORSLSTM, "Enable LSTM predictor");
text.put(ConfigConstants.PREDICTORSLSTMEPOCHS, "LSTM epochs");
text.put(ConfigConstants.PREDICTORSLSTMHORIZON, "LSTM horizon");
text.put(ConfigConstants.PREDICTORSLSTMWINDOWSIZE, "LSTM windowsize");
text.put(ConfigConstants.MISC, "Misc");
text.put(ConfigConstants.MISCPERCENTIZEPRICEINDEX, "Enable turning price/index into percent based on first date");
text.put(ConfigConstants.MISCMLSTATS, "Enable ML stats for time usage");
text.put(ConfigConstants.MISCOTHERSTATS, "Enable other stat pages");
text.put(ConfigConstants.MISCMYDAYS, "Number of days to display");
text.put(ConfigConstants.MISCMYTOPBOTTOM, "Number of items to display");
text.put(ConfigConstants.MISCMYTBLEDAYS, "Table days");
text.put(ConfigConstants.MISCMYTABLEMOVEINTERVALDAYS, "Interval days for table move");
text.put(ConfigConstants.MISCMYTABLEINTERVALDAYS, "Table interval days");
text.put(ConfigConstants.MISCMYEQUALIZE, "Enable equalizing");
text.put(ConfigConstants.MISCMYGRAPHEQUALIZE, "Enable graph equalizing");
text.put(ConfigConstants.MISCMYGRAPHEQUALIZEUNIFY, "Enable unified graph equalizing");
text.put(ConfigConstants.TESTRECOMMENDFUTUREDAYS, "Test recommender future days");
text.put(ConfigConstants.TESTRECOMMENDINTERVALDAYS, "Test recommender interval days");
text.put(ConfigConstants.TESTRECOMMENDINTERVALTIMES, "Deprecated Test recommender interval times");
text.put(ConfigConstants.TESTRECOMMENDITERATIONS, "Test recommender iterations");
text.put(ConfigConstants.TESTRECOMMENDPERIOD, "Test recommender period");
text.put(ConfigConstants.TESTRECOMMENDGENERATIONS, "Test recommender generations");
text.put(ConfigConstants.TESTRECOMMENDCHILDREN, "Test recommender children");
text.put(ConfigConstants.TESTRECOMMENDCROSSOVER, "Test recommender crossover");
text.put(ConfigConstants.TESTRECOMMENDELITE, "Test recommender elite");
text.put(ConfigConstants.TESTRECOMMENDSELECT, "Test recommender select");
text.put(ConfigConstants.TESTRECOMMENDMUTATE, "Test recommender mutate");
text.put(ConfigConstants.AGGREGATORS, "Enable aggregators");
text.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDER, "Enable aggregated MACD RSI recommender");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAM , "Buy weight histogram");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTA , "Buy weight histogram delta");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUM , "Buy weight momentum");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTA ,"Buy weight momentum delta");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMRSI, "Buy weight RSI");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTA , "Buy weight RSI delta");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAM ,"Sell weight histogram");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTA, "Sell weight histogram delta");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUM ,"Sell weight momentum");
text.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTA,"Sell weight momentum delta");
text.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSI, "Sell weight RSI");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTA, "Sell weight RSI delta");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMNODE , "Buy weight histogram node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYHISTOGRAMDELTANODE , "Buy weight histogram delta node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMNODE , "Buy weight momentum node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYMOMENTUMDELTANODE ,"Buy weight momentum delta node");
text.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSINODE, "Buy weight RSI node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSBUYRSIDELTANODE , "Buy weight RSI delta node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMNODE ,"Sell weight histogram node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLHISTOGRAMDELTANODE, "Sell weight histogram delta node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMNODE ,"Sell weight momentum node");
text.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLMOMENTUMDELTANODE,"Sell weight momentum delta node");
text.put(ConfigConstants.AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSINODE, "Sell weight RSI node");
text.put(ConfigConstants. AGGREGATORSMACDRSIRECOMMENDWEIGHTSSELLRSIDELTANODE, "Sell weight RSI delta node");
}
} |
package com.intellij.debugger.actions;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.engine.requests.RequestManagerImpl;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.breakpoints.BreakpointManager;
import com.intellij.debugger.ui.breakpoints.LineBreakpoint;
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
public class ToggleLineBreakpointAction extends AnAction {
public void actionPerformed(AnActionEvent e) {
DataContext dataContext = e.getDataContext();
Project project = (Project)dataContext.getData(DataConstants.PROJECT);
if (project == null) return;
PlaceInDocument place = getPlace(e);
if(place == null) return;
DebuggerManagerEx debugManager = DebuggerManagerEx.getInstanceEx(project);
if (debugManager == null) return;
BreakpointManager manager = debugManager.getBreakpointManager();
Breakpoint breakpoint = manager.findLineBreakpoint(place.getDocument(), place.getOffset());
if(breakpoint == null) {
int line = place.getDocument().getLineNumber(place.getOffset());
LineBreakpoint lineBreakpoint = manager.addLineBreakpoint(place.getDocument(), line);
if(lineBreakpoint != null) {
RequestManagerImpl.createRequests(lineBreakpoint);
}
} else {
manager.removeBreakpoint(breakpoint);
}
}
public static PlaceInDocument getPlace(AnActionEvent event) {
DataContext dataContext = event.getDataContext();
Project project = (Project)dataContext.getData(DataConstants.PROJECT);
if(project == null) return null;
Editor editor = (Editor)dataContext.getData(DataConstants.EDITOR);
if(editor == null) {
editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
}
if (editor != null) {
final Document document = editor.getDocument();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (file != null) {
FileTypeManager fileTypeManager = FileTypeManager.getInstance();
FileType fileType = fileTypeManager.getFileTypeByFile(file.getVirtualFile());
if (StdFileTypes.JAVA == fileType || StdFileTypes.JSP == fileType || StdFileTypes.JSPX == fileType) {
final Editor editor1 = editor;
return new PlaceInDocument() {
public Document getDocument() {
return document;
}
public int getOffset() {
return editor1.getCaretModel().getOffset();
}
};
}
}
}
return null;
}
public void update(AnActionEvent event){
boolean toEnable = false;
PlaceInDocument place = getPlace(event);
if (place != null) {
Project project = (Project)event.getDataContext().getData(DataConstants.PROJECT);
final Document document = place.getDocument();
final int offset = place.getOffset();
final BreakpointWithHighlighter breakpointAtLine = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager().findBreakpoint(document, offset);
if (breakpointAtLine != null && LineBreakpoint.CATEGORY.equals(breakpointAtLine.getCategory())) {
toEnable = true;
}
else {
toEnable = LineBreakpoint.canAddLineBreakpoint(project, document, document.getLineNumber(offset));
}
}
Presentation presentation = event.getPresentation();
if (ActionPlaces.EDITOR_POPUP.equals(event.getPlace()) ||
ActionPlaces.PROJECT_VIEW_POPUP.equals(event.getPlace()) ||
ActionPlaces.STRUCTURE_VIEW_POPUP.equals(event.getPlace())) {
presentation.setVisible(toEnable);
}
else {
presentation.setEnabled(toEnable);
}
}
} |
package com.intellij.ide.structureView.impl;
import com.intellij.ide.structureView.impl.java.AccessLevelProvider;
import com.intellij.ide.util.treeView.AlphaComparator;
import com.intellij.ide.util.treeView.SourceComparator;
import com.intellij.openapi.diagnostic.Logger;
import java.util.Comparator;
public class VisibilityComparator implements Comparator {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.structureView.impl.VisibilityComparator");
private static final int GROUP_ACCESS_SUBLEVEL = 1;
public static Comparator THEN_SOURCE = new VisibilityComparator(SourceComparator.INSTANCE);
public static Comparator THEN_ALPHA = new VisibilityComparator(AlphaComparator.INSTANCE);
public static Comparator IMSTANCE = new VisibilityComparator(null);
private Comparator myNextComparator;
public static final int UNKNOWN_ACCESS_LEVEL = -1;
public VisibilityComparator(Comparator comparator) {
myNextComparator = comparator;
}
public int compare(Object descriptor1, Object descriptor2) {
int accessLevel1 = getAccessLevel(descriptor1);
int accessLevel2 = getAccessLevel(descriptor2);
if (accessLevel1 == accessLevel2 && myNextComparator != null) {
return myNextComparator.compare(descriptor1, descriptor2);
}
return accessLevel2 - accessLevel1;
}
private int getAccessLevel(Object element) {
if (element instanceof AccessLevelProvider) {
return ((AccessLevelProvider)element).getAccessLevel() * (GROUP_ACCESS_SUBLEVEL + 1) + ((AccessLevelProvider)element).getSubLevel();
}
else {
LOG.assertTrue(false, element.getClass().getName());
return UNKNOWN_ACCESS_LEVEL;
}
}
} |
package com.intellij.openapi.vcs.impl;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ModuleAdapter;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.BinaryContentRevision;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory;
import com.intellij.openapi.vcs.checkin.CodeAnalysisBeforeCheckinHandler;
import com.intellij.openapi.vcs.checkin.StandardBeforeCheckinHandler;
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx;
import com.intellij.openapi.vcs.fileView.impl.VirtualAndPsiFileDataProvider;
import com.intellij.openapi.vcs.update.ActionInfo;
import com.intellij.openapi.vcs.update.UpdateInfoTree;
import com.intellij.openapi.vcs.update.UpdatedFiles;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.peer.PeerFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.ContentManagerAdapter;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.util.ContentsUtil;
import com.intellij.util.EventDispatcher;
import com.intellij.util.Icons;
import com.intellij.util.Processor;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.ui.EditorAdapter;
import com.intellij.ProjectTopics;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.util.*;
public class ProjectLevelVcsManagerImpl extends ProjectLevelVcsManagerEx implements ProjectComponent, JDOMExternalizable {
private List<AbstractVcs> myVcss = new ArrayList<AbstractVcs>();
private AbstractVcs[] myCachedVCSs = null;
private final Project myProject;
private final MessageBus myMessageBus;
private boolean myIsDisposed = false;
private ContentManager myContentManager;
private EditorAdapter myEditorAdapter;
@NonNls private static final String OPTIONS_SETTING = "OptionsSetting";
@NonNls private static final String CONFIRMATIONS_SETTING = "ConfirmationsSetting";
@NonNls private static final String VALUE_ATTTIBUTE = "value";
@NonNls private static final String ID_ATTRIBUTE = "id";
@NonNls private static final String ELEMENT_MAPPING = "mapping";
@NonNls private static final String ATTRIBUTE_DIRECTORY = "directory";
@NonNls private static final String ATTRIBUTE_VCS = "vcs";
private final List<CheckinHandlerFactory> myRegisteredBeforeCheckinHandlers = new ArrayList<CheckinHandlerFactory>();
private boolean myHaveEmptyContentRevisions = true;
private EventDispatcher<VcsListener> myEventDispatcher = EventDispatcher.create(VcsListener.class);
private List<VcsDirectoryMapping> myDirectoryMappings = new ArrayList<VcsDirectoryMapping>();
private Set<AbstractVcs> myActiveVcss = new HashSet<AbstractVcs>();
private boolean myMappingsLoaded = false;
private boolean myHaveLegacyVcsConfiguration = false;
private volatile int myBackgroundOperationCounter = 0;
public ProjectLevelVcsManagerImpl(Project project, final MessageBus bus) {
this(project, new AbstractVcs[0], bus);
}
public ProjectLevelVcsManagerImpl(Project project, AbstractVcs[] vcses, MessageBus bus) {
myProject = project;
myMessageBus = bus;
myVcss = new ArrayList<AbstractVcs>(Arrays.asList(vcses));
doSetDirectoryMapping("", "");
}
private final Map<String, VcsShowOptionsSettingImpl> myOptions = new LinkedHashMap<String, VcsShowOptionsSettingImpl>();
private final Map<String, VcsShowConfirmationOptionImpl> myConfirmations = new LinkedHashMap<String, VcsShowConfirmationOptionImpl>();
public void initComponent() {
createSettingFor(VcsConfiguration.StandardOption.ADD);
createSettingFor(VcsConfiguration.StandardOption.REMOVE);
createSettingFor(VcsConfiguration.StandardOption.CHECKOUT);
createSettingFor(VcsConfiguration.StandardOption.UPDATE);
createSettingFor(VcsConfiguration.StandardOption.STATUS);
createSettingFor(VcsConfiguration.StandardOption.EDIT);
myConfirmations.put(VcsConfiguration.StandardConfirmation.ADD.getId(), new VcsShowConfirmationOptionImpl(
VcsConfiguration.StandardConfirmation.ADD.getId(),
VcsBundle.message("label.text.when.files.created.with.idea", ApplicationNamesInfo.getInstance().getProductName()),
VcsBundle.message("radio.after.creation.do.not.add"), VcsBundle.message("radio.after.creation.show.options"),
VcsBundle.message("radio.after.creation.add.silently")));
myConfirmations.put(VcsConfiguration.StandardConfirmation.REMOVE.getId(), new VcsShowConfirmationOptionImpl(
VcsConfiguration.StandardConfirmation.REMOVE.getId(),
VcsBundle.message("label.text.when.files.are.deleted.with.idea", ApplicationNamesInfo.getInstance().getProductName()),
VcsBundle.message("radio.after.deletion.do.not.remove"), VcsBundle.message("radio.after.deletion.show.options"),
VcsBundle.message("radio.after.deletion.remove.silently")));
restoreReadConfirm(VcsConfiguration.StandardConfirmation.ADD);
restoreReadConfirm(VcsConfiguration.StandardConfirmation.REMOVE);
}
private void restoreReadConfirm(final VcsConfiguration.StandardConfirmation confirm) {
if (myReadValue.containsKey(confirm.getId())) {
getConfirmation(confirm).setValue(myReadValue.get(confirm.getId()));
}
}
private void createSettingFor(final VcsConfiguration.StandardOption option) {
if (!myOptions.containsKey(option.getId())) {
myOptions.put(option.getId(), new VcsShowOptionsSettingImpl(option));
}
}
public void registerVcs(AbstractVcs vcs) {
try {
vcs.loadSettings();
vcs.start();
}
catch (VcsException e) {
LOG.debug(e);
}
if (!myVcss.contains(vcs)) {
myVcss.add(vcs);
}
vcs.getProvidedStatuses();
myCachedVCSs = null;
}
@Nullable
public AbstractVcs findVcsByName(String name) {
if (name == null) return null;
for (AbstractVcs vcs : myVcss) {
if (vcs.getName().equals(name)) {
return vcs;
}
}
final VcsEP[] vcsEPs = Extensions.getExtensions(VcsEP.EP_NAME, myProject);
for(VcsEP ep: vcsEPs) {
if (ep.getName().equals(name)) {
AbstractVcs vcs = ep.getVcs(myProject);
if (!myVcss.contains(vcs)) {
registerVcs(vcs);
}
return vcs;
}
}
return null;
}
public AbstractVcs[] getAllVcss() {
final VcsEP[] vcsEPs = Extensions.getExtensions(VcsEP.EP_NAME, myProject);
for(VcsEP ep: vcsEPs) {
AbstractVcs vcs = ep.getVcs(myProject);
if (!myVcss.contains(vcs)) {
registerVcs(vcs);
}
}
if (myCachedVCSs == null) {
Collections.sort(myVcss, new Comparator<AbstractVcs>() {
public int compare(final AbstractVcs o1, final AbstractVcs o2) {
return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName());
}
});
myCachedVCSs = myVcss.toArray(new AbstractVcs[myVcss.size()]);
}
return myCachedVCSs;
}
public void disposeComponent() {
}
public void projectOpened() {
myContentManager = PeerFactory.getInstance().getContentFactory().createContentManager(true, myProject);
registerCheckinHandlerFactory(new CheckinHandlerFactory() {
public
@NotNull
CheckinHandler createHandler(final CheckinProjectPanel panel) {
return new StandardBeforeCheckinHandler(myProject);
}
});
registerCheckinHandlerFactory(new CheckinHandlerFactory() {
public
@NotNull
CheckinHandler createHandler(final CheckinProjectPanel panel) {
return new CodeAnalysisBeforeCheckinHandler(myProject, panel);
}
});
initialize();
final StartupManager manager = StartupManager.getInstance(myProject);
manager.registerStartupActivity(new Runnable() {
public void run() {
if (!myHaveLegacyVcsConfiguration && !myMappingsLoaded) {
autoDetectVcsMappings();
}
updateActiveVcss();
}
});
manager.registerPostStartupActivity(new Runnable() {
public void run() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject);
if (toolWindowManager != null) { // Can be null in tests
ToolWindow toolWindow =
toolWindowManager.registerToolWindow(ToolWindowId.VCS, myContentManager.getComponent(), ToolWindowAnchor.BOTTOM);
toolWindow.setIcon(Icons.VCS_SMALL_TAB);
toolWindow.installWatcher(myContentManager);
}
if (myMessageBus != null) {
myMessageBus.connect().subscribe(ProjectTopics.MODULES, new ModuleAdapter() {
public void moduleAdded(final Project project, final Module module) {
autoDetectModuleVcsMapping(module);
}
});
}
}
});
}
public void initialize() {
final AbstractVcs[] abstractVcses = myVcss.toArray(new AbstractVcs[myVcss.size()]);
for (AbstractVcs abstractVcs : abstractVcses) {
registerVcs(abstractVcs);
}
}
public void projectClosed() {
dispose();
}
@NotNull
public String getComponentName() {
return "ProjectLevelVcsManager";
}
public boolean checkAllFilesAreUnder(AbstractVcs abstractVcs, VirtualFile[] files) {
if (files == null) return false;
for (VirtualFile file : files) {
if (getVcsFor(file) != abstractVcs) {
return false;
}
}
return true;
}
@Nullable
public AbstractVcs getVcsFor(VirtualFile file) {
VcsDirectoryMapping mapping = getMappingFor(file);
if (mapping == null) {
return null;
}
final String vcs = mapping.getVcs();
if (vcs.length() == 0) {
return null;
}
return findVcsByName(vcs);
}
@Nullable
private VcsDirectoryMapping getMappingFor(VirtualFile file) {
if (file == null) return null;
if (myProject.isDisposed()) return null;
if (!(file.getFileSystem() instanceof LocalFileSystem)) {
return null;
}
// performance: calculate file path just once, rather than once per mapping
String path = file.getPath();
// scan from bottom-most mapping to topmost
for(int i = myDirectoryMappings.size()-1; i >= 0; i
final VcsDirectoryMapping mapping = myDirectoryMappings.get(i);
if (fileMatchesMapping(file, path, mapping)) {
return mapping;
}
}
return null;
}
@Nullable
public AbstractVcs getVcsFor(final FilePath file) {
VirtualFile vFile = findValidParent(file);
if (vFile != null) {
return getVcsFor(vFile);
}
return null;
}
@Nullable
public VirtualFile getVcsRootFor(final VirtualFile file) {
VcsDirectoryMapping mapping = getMappingFor(file);
if (mapping == null) {
return null;
}
final String directory = mapping.getDirectory();
if (directory.length() == 0) {
final VirtualFile contentRoot = ProjectRootManager.getInstance(myProject).getFileIndex().getContentRootForFile(file);
if (contentRoot != null) {
return contentRoot;
}
return myProject.getBaseDir();
}
return LocalFileSystem.getInstance().findFileByPath(directory);
}
@Nullable
public VirtualFile getVcsRootFor(final FilePath file) {
VirtualFile vFile = findValidParent(file);
if (vFile != null) {
return getVcsRootFor(vFile);
}
return null;
}
@Nullable
private static VirtualFile findValidParent(FilePath file) {
ApplicationManager.getApplication().assertReadAccessAllowed();
VirtualFile parent = file.getVirtualFile();
if (parent == null) {
parent = file.getVirtualFileParent();
}
if (parent == null) {
File ioFile = file.getIOFile();
do {
parent = LocalFileSystem.getInstance().findFileByIoFile(ioFile);
if (parent != null) break;
ioFile = ioFile.getParentFile();
if (ioFile == null) return null;
}
while (true);
}
return parent;
}
private boolean fileMatchesMapping(final VirtualFile file, final String path, final VcsDirectoryMapping mapping) {
if (mapping.getDirectory().length() == 0) {
return VfsUtil.getModuleForFile(myProject, file) != null;
}
return FileUtil.startsWith(path, mapping.getDirectory());
}
private void dispose() {
if (myIsDisposed) return;
for(AbstractVcs vcs: myActiveVcss) {
vcs.deactivate();
}
myActiveVcss.clear();
AbstractVcs[] allVcss = myVcss.toArray(new AbstractVcs[myVcss.size()]);
for (AbstractVcs allVcs : allVcss) {
unregisterVcs(allVcs);
}
try {
myContentManager = null;
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject);
if (toolWindowManager != null && toolWindowManager.getToolWindow(ToolWindowId.VCS) != null) {
toolWindowManager.unregisterToolWindow(ToolWindowId.VCS);
}
}
finally {
myIsDisposed = true;
}
}
public void unregisterVcs(AbstractVcs vcs) {
try {
vcs.shutdown();
}
catch (VcsException e) {
LOG.info(e);
}
myVcss.remove(vcs);
myCachedVCSs = null;
}
public ContentManager getContentManager() {
return myContentManager;
}
@Nullable
String getBaseVersionContent(final VirtualFile file) {
final Change change = ChangeListManager.getInstance(myProject).getChange(file);
if (change != null) {
final ContentRevision beforeRevision = change.getBeforeRevision();
if (beforeRevision instanceof BinaryContentRevision) {
return null;
}
if (beforeRevision != null) {
String content;
try {
content = beforeRevision.getContent();
}
catch(VcsException ex) {
content = null;
}
if (content == null) myHaveEmptyContentRevisions = true;
return content;
}
return null;
}
final Document document = FileDocumentManager.getInstance().getCachedDocument(file);
if (document != null && document.getModificationStamp() != file.getModificationStamp()) {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
return LoadTextUtil.loadText(file).toString();
}
});
}
return null;
}
public boolean checkVcsIsActive(AbstractVcs vcs) {
for(VcsDirectoryMapping mapping: myDirectoryMappings) {
if (mapping.getVcs().equals(vcs.getName())) {
return true;
}
}
return false;
}
public String getPresentableRelativePathFor(final VirtualFile file) {
if (file == null) return "";
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject)
.getFileIndex();
Module module = fileIndex.getModuleForFile(file);
VirtualFile contentRoot = fileIndex.getContentRootForFile(file);
if (module == null) return file.getPresentableUrl();
StringBuffer result = new StringBuffer();
result.append("<");
result.append(module.getName());
result.append(">");
result.append(File.separatorChar);
result.append(contentRoot.getName());
String relativePath = VfsUtil.getRelativePath(file, contentRoot, File.separatorChar);
if (relativePath.length() > 0) {
result.append(File.separatorChar);
result.append(relativePath);
}
return result.toString();
}
});
}
public DataProvider createVirtualAndPsiFileDataProvider(VirtualFile[] virtualFileArray, VirtualFile selectedFile) {
return new VirtualAndPsiFileDataProvider(myProject, virtualFileArray, selectedFile);
}
public AbstractVcs[] getAllActiveVcss() {
return myActiveVcss.toArray(new AbstractVcs[myActiveVcss.size()]);
}
public void addMessageToConsoleWindow(final String message, final TextAttributes attributes) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
getOrCreateConsoleContent(getContentManager());
myEditorAdapter.appendString(message, attributes);
}
}, ModalityState.defaultModalityState());
}
private Content getOrCreateConsoleContent(final ContentManager contentManager) {
final String displayName = VcsBundle.message("vcs.console.toolwindow.display.name");
Content content = contentManager.findContent(displayName);
if (content == null) {
final EditorFactory editorFactory = EditorFactory.getInstance();
final Editor editor = editorFactory.createViewer(editorFactory.createDocument(""));
EditorSettings editorSettings = editor.getSettings();
editorSettings.setLineMarkerAreaShown(false);
editorSettings.setLineNumbersShown(false);
editorSettings.setFoldingOutlineShown(false);
myEditorAdapter = new EditorAdapter(editor, myProject);
final JComponent panel = editor.getComponent();
content = PeerFactory.getInstance().getContentFactory().createContent(panel, displayName, true);
contentManager.addContent(content);
contentManager.addContentManagerListener(new ContentManagerAdapter() {
public void contentRemoved(ContentManagerEvent event) {
if (event.getContent().getComponent() == panel) {
editorFactory.releaseEditor(editor);
contentManager.removeContentManagerListener(this);
}
}
});
}
return content;
}
@NotNull
public VcsShowSettingOption getOptions(VcsConfiguration.StandardOption option) {
return myOptions.get(option.getId());
}
public List<VcsShowOptionsSettingImpl> getAllOptions() {
return new ArrayList<VcsShowOptionsSettingImpl>(myOptions.values());
}
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl");
@NotNull
public VcsShowSettingOption getStandardOption(@NotNull VcsConfiguration.StandardOption option, @NotNull AbstractVcs vcs) {
final VcsShowOptionsSettingImpl options = myOptions.get(option.getId());
options.addApplicableVcs(vcs);
return options;
}
@NotNull
public VcsShowSettingOption getOrCreateCustomOption(@NotNull String vcsActionName, @NotNull AbstractVcs vcs) {
final VcsShowOptionsSettingImpl option = getOrCreateOption(vcsActionName);
option.addApplicableVcs(vcs);
return option;
}
public void showProjectOperationInfo(final UpdatedFiles updatedFiles, String displayActionName) {
showUpdateProjectInfo(updatedFiles, displayActionName, ActionInfo.STATUS);
}
public void showUpdateProjectInfo(final UpdatedFiles updatedFiles, final String displayActionName, final ActionInfo actionInfo) {
ContentManager contentManager = getInstanceEx(myProject).getContentManager();
final UpdateInfoTree updateInfoTree = new UpdateInfoTree(contentManager, null, myProject, updatedFiles, displayActionName, actionInfo);
Content content = PeerFactory.getInstance().getContentFactory().createContent(updateInfoTree, VcsBundle.message(
"toolwindow.title.update.action.info", displayActionName), true);
ContentsUtil.addOrReplaceContent(contentManager, content, true);
ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.VCS).activate(null);
updateInfoTree.expandRootChildren();
}
public void addMappingFromModule(final Module module, final String activeVcsName) {
for(VirtualFile file: ModuleRootManager.getInstance(module).getContentRoots()) {
setDirectoryMapping(file.getPath(), activeVcsName);
}
sortDirectoryMappings();
removeRedundantMappings();
}
private void removeRedundantMappings() {
int i=1;
while(i < myDirectoryMappings.size()) {
if (myDirectoryMappings.get(i).getDirectory().startsWith(myDirectoryMappings.get(i-1).getDirectory()) &&
myDirectoryMappings.get(i).getVcs().equals(myDirectoryMappings.get(i-1).getVcs())) {
myDirectoryMappings.remove(i);
}
else {
i++;
}
}
}
public List<VcsDirectoryMapping> getDirectoryMappings() {
return Collections.unmodifiableList(myDirectoryMappings);
}
public void setDirectoryMapping(final String path, final String activeVcsName) {
if (myMappingsLoaded) return; // ignore per-module VCS settings if the mapping table was loaded from .ipr
myHaveLegacyVcsConfiguration = true;
doSetDirectoryMapping(path, activeVcsName);
}
private void doSetDirectoryMapping(final String path, final String activeVcsName) {
for(VcsDirectoryMapping mapping: myDirectoryMappings) {
if (mapping.getDirectory().equals(path)) {
mapping.setVcs(activeVcsName);
return;
}
}
VcsDirectoryMapping mapping = new VcsDirectoryMapping(path, activeVcsName);
myDirectoryMappings.add(mapping);
sortDirectoryMappings();
}
private void sortDirectoryMappings() {
Collections.sort(myDirectoryMappings, new Comparator<VcsDirectoryMapping>() {
public int compare(final VcsDirectoryMapping m1, final VcsDirectoryMapping m2) {
return m1.getDirectory().compareTo(m2.getDirectory());
}
});
}
public void setDirectoryMappings(final List<VcsDirectoryMapping> items) {
myDirectoryMappings.clear();
myDirectoryMappings.addAll(items);
sortDirectoryMappings();
}
public void iterateVcsRoot(final VirtualFile root, final Processor<FilePath> iterator) {
Set<VirtualFile> filesToExclude = null;
VcsDirectoryMapping mapping = getMappingFor(root);
if (mapping != null) {
for(VcsDirectoryMapping otherMapping: myDirectoryMappings) {
if (otherMapping != mapping && otherMapping.getDirectory().startsWith(mapping.getDirectory())) {
if (filesToExclude == null) {
filesToExclude = new HashSet<VirtualFile>();
}
filesToExclude.add(LocalFileSystem.getInstance().findFileByPath(otherMapping.getDirectory()));
}
}
}
iterateChildren(root, iterator, filesToExclude);
}
private boolean iterateChildren(final VirtualFile root, final Processor<FilePath> iterator, final Collection<VirtualFile> filesToExclude) {
if (!iterator.process(new FilePathImpl(root))) {
return false;
}
if (root.isDirectory()) {
final VirtualFile[] files = root.getChildren();
for(VirtualFile child: files) {
if (child.isDirectory()) {
if (filesToExclude != null && filesToExclude.contains(child)) {
continue;
}
if (ProjectRootManager.getInstance(myProject).getFileIndex().isIgnored(child)) {
continue;
}
}
if (!iterateChildren(child, iterator, filesToExclude)) {
return false;
}
}
}
return true;
}
private VcsShowOptionsSettingImpl getOrCreateOption(String actionName) {
if (!myOptions.containsKey(actionName)) {
myOptions.put(actionName, new VcsShowOptionsSettingImpl(actionName));
}
return myOptions.get(actionName);
}
private final Map<String, VcsShowConfirmationOption.Value> myReadValue =
new com.intellij.util.containers.HashMap<String, VcsShowConfirmationOption.Value>();
public void readExternal(Element element) throws InvalidDataException {
List subElements = element.getChildren(OPTIONS_SETTING);
for (Object o : subElements) {
if (o instanceof Element) {
final Element subElement = ((Element)o);
final String id = subElement.getAttributeValue(ID_ATTRIBUTE);
final String value = subElement.getAttributeValue(VALUE_ATTTIBUTE);
if (id != null && value != null) {
try {
final boolean booleanValue = Boolean.valueOf(value).booleanValue();
getOrCreateOption(id).setValue(booleanValue);
}
catch (Exception e) {
//ignore
}
}
}
}
myReadValue.clear();
subElements = element.getChildren(CONFIRMATIONS_SETTING);
for (Object o : subElements) {
if (o instanceof Element) {
final Element subElement = ((Element)o);
final String id = subElement.getAttributeValue(ID_ATTRIBUTE);
final String value = subElement.getAttributeValue(VALUE_ATTTIBUTE);
if (id != null && value != null) {
try {
myReadValue.put(id, VcsShowConfirmationOption.Value.fromString(value));
}
catch (Exception e) {
//ignore
}
}
}
}
}
public void writeExternal(Element element) throws WriteExternalException {
for (VcsShowOptionsSettingImpl setting : myOptions.values()) {
final Element settingElement = new Element(OPTIONS_SETTING);
element.addContent(settingElement);
settingElement.setAttribute(VALUE_ATTTIBUTE, Boolean.toString(setting.getValue()));
settingElement.setAttribute(ID_ATTRIBUTE, setting.getDisplayName());
}
for (VcsShowConfirmationOptionImpl setting : myConfirmations.values()) {
final Element settingElement = new Element(CONFIRMATIONS_SETTING);
element.addContent(settingElement);
settingElement.setAttribute(VALUE_ATTTIBUTE, setting.getValue().toString());
settingElement.setAttribute(ID_ATTRIBUTE, setting.getDisplayName());
}
}
@NotNull
public VcsShowConfirmationOption getStandardConfirmation(@NotNull VcsConfiguration.StandardConfirmation option,
@NotNull AbstractVcs vcs) {
final VcsShowConfirmationOptionImpl result = myConfirmations.get(option.getId());
result.addApplicableVcs(vcs);
return result;
}
public List<VcsShowConfirmationOptionImpl> getAllConfirmations() {
return new ArrayList<VcsShowConfirmationOptionImpl>(myConfirmations.values());
}
@NotNull
public VcsShowConfirmationOptionImpl getConfirmation(VcsConfiguration.StandardConfirmation option) {
return myConfirmations.get(option.getId());
}
public List<CheckinHandlerFactory> getRegisteredCheckinHandlerFactories() {
return Collections.unmodifiableList(myRegisteredBeforeCheckinHandlers);
}
public void registerCheckinHandlerFactory(CheckinHandlerFactory factory) {
myRegisteredBeforeCheckinHandlers.add(factory);
}
public void unregisterCheckinHandlerFactory(CheckinHandlerFactory handler) {
myRegisteredBeforeCheckinHandlers.remove(handler);
}
public void addVcsListener(VcsListener listener) {
myEventDispatcher.addListener(listener);
}
public void removeVcsListener(VcsListener listener) {
myEventDispatcher.removeListener(listener);
}
public void startBackgroundVcsOperation() {
myBackgroundOperationCounter++;
}
public void stopBackgroundVcsOperation() {
LOG.assertTrue(myBackgroundOperationCounter > 0, "myBackgroundOperationCounter > 0");
myBackgroundOperationCounter
}
public boolean isBackgroundVcsOperationRunning() {
return myBackgroundOperationCounter > 0;
}
public VirtualFile[] getRootsUnderVcs(AbstractVcs vcs) {
List<VirtualFile> result = new ArrayList<VirtualFile>();
for(VcsDirectoryMapping mapping: myDirectoryMappings) {
if (mapping.getVcs().equals(vcs.getName())) {
if (mapping.getDirectory().length() == 0) {
addDefaultVcsRoots(vcs, result);
}
else {
VirtualFile file = LocalFileSystem.getInstance().findFileByPath(mapping.getDirectory());
if (file != null) {
result.add(file);
}
}
}
}
Collections.sort(result, new Comparator<VirtualFile>() {
public int compare(final VirtualFile o1, final VirtualFile o2) {
return o1.getPath().compareTo(o2.getPath());
}
});
int i=1;
while(i < result.size()) {
if (VfsUtil.isAncestor(result.get(i-1), result.get(i), false)) {
result.remove(i);
}
else {
i++;
}
}
return result.toArray(new VirtualFile[result.size()]);
}
public VirtualFile[] getAllVersionedRoots() {
List<VirtualFile> vFiles = new ArrayList<VirtualFile>();
for(AbstractVcs vcs: myActiveVcss) {
Collections.addAll(vFiles, getRootsUnderVcs(vcs));
}
return vFiles.toArray(new VirtualFile[vFiles.size()]);
}
private void addDefaultVcsRoots(final AbstractVcs vcs, final List<VirtualFile> result) {
final VirtualFile baseDir = myProject.getBaseDir();
if (getVcsFor(baseDir) == vcs) {
result.add(baseDir);
}
final Module[] modules = ModuleManager.getInstance(myProject).getModules();
for(Module module: modules) {
final VirtualFile[] files = ModuleRootManager.getInstance(module).getContentRoots();
for(VirtualFile file: files) {
if (getVcsFor(file) == vcs) {
result.add(file);
}
}
}
}
public void updateActiveVcss() {
HashSet<AbstractVcs> oldActiveVcss = new HashSet<AbstractVcs>(myActiveVcss);
myActiveVcss.clear();
for(VcsDirectoryMapping mapping: myDirectoryMappings) {
if (mapping.getVcs().length() > 0) {
AbstractVcs vcs = findVcsByName(mapping.getVcs());
if (vcs != null && !myActiveVcss.contains(vcs)) {
myActiveVcss.add(vcs);
if (!oldActiveVcss.contains(vcs)) {
vcs.activate();
}
}
}
}
for(AbstractVcs vcs: oldActiveVcss) {
if (!myActiveVcss.contains(vcs)) {
vcs.deactivate();
}
}
notifyDirectoryMappingChanged();
}
public void notifyDirectoryMappingChanged() {
myEventDispatcher.getMulticaster().directoryMappingChanged();
}
boolean hasEmptyContentRevisions() {
return myHaveEmptyContentRevisions;
}
void resetHaveEmptyContentRevisions() {
myHaveEmptyContentRevisions = false;
}
public void readDirectoryMappings(final Element element) {
myDirectoryMappings.clear();
final List list = element.getChildren(ELEMENT_MAPPING);
for(Object childObj: list) {
Element child = (Element) childObj;
VcsDirectoryMapping mapping = new VcsDirectoryMapping(child.getAttributeValue(ATTRIBUTE_DIRECTORY),
child.getAttributeValue(ATTRIBUTE_VCS));
myDirectoryMappings.add(mapping);
}
myMappingsLoaded = true;
}
public void writeDirectoryMappings(final Element element) {
for(VcsDirectoryMapping mapping: myDirectoryMappings) {
Element child = new Element(ELEMENT_MAPPING);
child.setAttribute(ATTRIBUTE_DIRECTORY, mapping.getDirectory());
child.setAttribute(ATTRIBUTE_VCS, mapping.getVcs());
element.addContent(child);
}
}
@Nullable
private AbstractVcs findVersioningVcs(VirtualFile file) {
for(AbstractVcs vcs: myVcss) {
if (vcs.isVersionedDirectory(file)) {
return vcs;
}
}
return null;
}
private void autoDetectVcsMappings() {
Set<AbstractVcs> usedVcses = new HashSet<AbstractVcs>();
Map<VirtualFile, AbstractVcs> vcsMap = new HashMap<VirtualFile, AbstractVcs>();
for(Module module: ModuleManager.getInstance(myProject).getModules()) {
final VirtualFile[] files = ModuleRootManager.getInstance(module).getContentRoots();
for(VirtualFile file: files) {
AbstractVcs contentRootVcs = findVersioningVcs(file);
if (contentRootVcs != null) {
vcsMap.put(file, contentRootVcs);
}
usedVcses.add(contentRootVcs);
}
}
if (usedVcses.size() == 1) {
final AbstractVcs[] abstractVcses = usedVcses.toArray(new AbstractVcs[1]);
if (abstractVcses [0] != null) {
doSetDirectoryMapping("", abstractVcses [0].getName());
}
}
else {
for(Map.Entry<VirtualFile, AbstractVcs> entry: vcsMap.entrySet()) {
doSetDirectoryMapping(entry.getKey().getPath(), entry.getValue() == null ? "" : entry.getValue().getName());
}
sortDirectoryMappings();
removeRedundantMappings();
}
}
private void autoDetectModuleVcsMapping(final Module module) {
final VirtualFile[] files = ModuleRootManager.getInstance(module).getContentRoots();
for(VirtualFile file: files) {
AbstractVcs vcs = findVersioningVcs(file);
if (vcs != null && vcs != getVcsFor(file)) {
doSetDirectoryMapping(file.getPath(), vcs.getName());
}
}
sortDirectoryMappings();
removeRedundantMappings();
updateActiveVcss();
}
} |
package org.subethamail.core.lists;
import java.net.URL;
import java.util.List;
import java.util.Set;
import javax.annotation.EJB;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.annotation.security.RunAs;
import javax.ejb.Stateless;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.annotation.security.SecurityDomain;
import org.subethamail.common.NotFoundException;
import org.subethamail.common.Permission;
import org.subethamail.core.lists.i.ListMgr;
import org.subethamail.core.lists.i.ListMgrRemote;
import org.subethamail.core.lists.i.SubscriberData;
import org.subethamail.core.util.PersonalBean;
import org.subethamail.core.util.Transmute;
import org.subethamail.entity.MailingList;
import org.subethamail.entity.Role;
import org.subethamail.entity.Subscription;
import org.subethamail.entity.dao.DAO;
/**
* Implementation of the AccountMgr interface.
*
* @author Jeff Schnitzer
*/
@Stateless(name="ListMgr")
@SecurityDomain("subetha")
@RolesAllowed("user")
@RunAs("siteAdmin")
public class ListMgrBean extends PersonalBean implements ListMgr, ListMgrRemote
{
private static Log log = LogFactory.getLog(ListMgrBean.class);
@EJB DAO dao;
/**
* @see ListMgr#lookup(URL)
*/
@PermitAll
public Long lookup(URL url) throws NotFoundException
{
return this.dao.findMailingList(url).getId();
}
/**
* @see ListMgr#getSubscribers(Long)
*/
public List<SubscriberData> getSubscribers(Long listId) throws NotFoundException
{
MailingList list = this.dao.findMailingList(listId);
Role role = list.getRoleFor(this.getMe());
if (! role.getPermissions().contains(Permission.VIEW_SUBSCRIBERS))
throw new IllegalStateException("Not allowed");
Set<Subscription> listSubscriptions = list.getSubscriptions();
return Transmute.subscribers(listSubscriptions);
}
} |
package com.intellij.openapi.wm.impl.welcomeScreen;
import com.intellij.help.impl.HelpManagerImpl;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.DataManager;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.plugins.PluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.plugins.PluginManagerConfigurable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionButtonLook;
import com.intellij.openapi.actionSystem.impl.EmptyIcon;
import com.intellij.openapi.actionSystem.impl.PresentationFactory;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.LabeledIcon;
import com.intellij.ui.ScrollPaneFactory;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Arrays;
public class WelcomeScreen {
private JPanel myWelcomePanel;
private JPanel myMainPanel;
private JPanel myPluginsPanel;
private static final Insets ICON_INSETS = new Insets(15, 0, 15, 0);
// The below 3 array lists are reserved for future use
private static ArrayList<MyActionButton> ourMainButtons = new ArrayList<MyActionButton>(5);
private static ArrayList<MyActionButton> ourPluginButtons = new ArrayList<MyActionButton>(5);
private static ArrayList<PluginDescriptor> ourPluginsWithActions = new ArrayList<PluginDescriptor>();
private MyActionButton myKeypressedButton = null;
private int mySelectedRow = -1;
private int mySelectedColumn = -1;
private int mySelectedGroup = -1;
private static final int MAIN_GROUP = 0;
private static final int PLUGINS_GROUP = 1;
private static final int COLUMNS_IN_MAIN = 2;
private static final int PLUGIN_DSC_MAX_WIDTH = 180;
private static final int PLUGIN_DSC_MAX_ROWS = 2;
private static final int PLUGIN_NAME_MAX_WIDTH = 180;
private static final int PLUGIN_NAME_MAX_ROWS = 2;
private static final int MAX_TOOLTIP_WIDTH = 400;
private static final Dimension ACTION_BUTTON_SIZE = new Dimension(78, 78);
private static final Dimension PLUGIN_LOGO_SIZE = new Dimension(16, 16);
private static final Dimension LEARN_MORE_SIZE = new Dimension(26, 26);
private static final Dimension OPEN_PLUGIN_MANAGER_SIZE = new Dimension(166, 31);
private static final Icon LEARN_MORE_ICON = IconLoader.getIcon("/general/learnMore.png");
private static final Icon OPEN_PLUGINS_ICON = IconLoader.getIcon("/general/openPluginManager.png");
private static final Icon CAPTION_IMAGE = IconLoader.getIcon("/general/welcomeCaption.png");
private static final Icon DEVELOP_SLOGAN = IconLoader.getIcon("/general/developSlogan.png");
private static final Icon NEW_PROJECT_ICON = IconLoader.getIcon("/general/createNewProject.png");
private static final Icon REOPEN_RECENT_ICON = IconLoader.getIcon("/general/reopenRecentProject.png");
private static final Icon FROM_VCS_ICON = IconLoader.getIcon("/general/getProjectfromVCS.png");
private static final Icon READ_HELP_ICON = IconLoader.getIcon("/general/readHelp.png");
private static final Icon KEYMAP_ICON = IconLoader.getIcon("/general/defaultKeymap.png");
private static final Icon DEFAULT_ICON = IconLoader.getIcon("/general/configurableDefault.png");
private static final String KEYMAP_URL = PathManager.getHomePath() + "/help/4.5_ReferenceCard.pdf";
private static final String JET_BRAINS = "JetBrains";
private static final String INTELLIJ = "IntelliJ";
private static final Font TEXT_FONT = new Font("Tahoma", Font.PLAIN, 11);
private static final Font LINK_FONT = new Font("Tahoma", Font.BOLD, 12);
private static final Font CAPTION_FONT = new Font("Tahoma", Font.BOLD, 18);
private static final Color CAPTION_COLOR = new Color(47, 67, 96);
private static final Color PLUGINS_PANEL_COLOR = new Color(229, 229, 229);
private static final Color MAIN_PANEL_COLOR = new Color(210, 213, 226);
private static final Color BUTTON_PUSHED_COLOR = new Color(130, 146, 185);
private static final Color BUTTON_POPPED_COLOR = new Color(181, 190, 214);
private static final Color MAIN_PANEL_BACKGROUND = new Color(238, 238, 238);
private static final Color LEARN_MORE_BUTTON_COLOR = new Color(238, 238, 238);
private static final Color GRAY_BORDER_COLOR = new Color(177, 177, 177);
private static final Color CAPTION_BACKGROUND = new Color(24, 52, 146);
private static final Color ACTION_BUTTON_COLOR = new Color(201, 205, 217);
private static final Color ACTION_BUTTON_BORDER_COLOR = new Color(166, 170, 182);
private static final Color WHITE_BORDER_COLOR = new Color(255, 255, 255);
private int myPluginsButtonsCount = 0;
private int myPluginsIdx = -1;
private class ActionGroupDescriptor {
private int myIdx = -1;
private int myCount = 0;
private JPanel myPanel;
private final int myColumnIdx;
public ActionGroupDescriptor(final String caption, final int columnIndex) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(MAIN_PANEL_COLOR);
JLabel quickStartCaption = new JLabel(caption);
quickStartCaption.setFont(CAPTION_FONT);
quickStartCaption.setForeground(CAPTION_COLOR);
GridBagConstraints gBC = new GridBagConstraints(0, 0, 2, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(20, 0, 5, 0), 0, 0);
panel.add(quickStartCaption, gBC);
myPanel = panel;
myColumnIdx = columnIndex;
}
public void addButton(final MyActionButton button, String commandLink, String description) {
final int y = myIdx += 2;
GridBagConstraints gBC =
new GridBagConstraints(0, y, 1, 2, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, ICON_INSETS, 5, 5);
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
myPanel.add(button, gBC);
button.setupWithinPanel(myMainPanel, MAIN_GROUP, myCount, myColumnIdx);
myCount++;
JLabel name = new JLabel("<html><nobr><u>" + commandLink + "</u></nobr></html>");
name.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
button.onPress(e);
}
});
name.setForeground(CAPTION_COLOR);
name.setFont(LINK_FONT);
name.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
gBC = new GridBagConstraints(1, y, 1, 1, 0, 0, GridBagConstraints.SOUTHWEST, GridBagConstraints.NONE, new Insets(15, 15, 0, 0), 5, 0);
myPanel.add(name, gBC);
description = "<HTML>" + description + "</html>";
JLabel shortDescription = new JLabel(description);
shortDescription.setFont(TEXT_FONT);
gBC = new GridBagConstraints(1, y + 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(7, 15, 0, 30), 5, 0);
myPanel.add(shortDescription, gBC);
}
private void appendActionsFromGroup(final DefaultActionGroup group) {
final AnAction[] actions = group.getChildren(null);
for (final AnAction action : actions) {
final Presentation presentation = action.getTemplatePresentation();
final Icon icon = presentation.getIcon();
final String text = presentation.getText();
MyActionButton button = new ButtonWithExtension(icon, "") {
protected void onPress(InputEvent e, MyActionButton button) {
final ActionManager actionManager = ActionManager.getInstance();
AnActionEvent evt = new AnActionEvent(
null,
DataManager.getInstance().getDataContext(this),
ActionPlaces.WELCOME_SCREEN,
action.getTemplatePresentation(),
actionManager,
0
);
action.update(evt);
if (evt.getPresentation().isEnabled()) {
action.actionPerformed(evt);
}
}
};
addButton(button, text, presentation.getDescription());
}
}
public JPanel getPanel() {
return myPanel;
}
public int getIdx() {
return myIdx;
}
}
private WelcomeScreen() {
// Create Plugins Panel
myPluginsPanel = new PluginsPanel(new GridBagLayout());
myPluginsPanel.setBackground(PLUGINS_PANEL_COLOR);
JLabel pluginsCaption = new JLabel("Plugins");
pluginsCaption.setFont(CAPTION_FONT);
pluginsCaption.setForeground(CAPTION_COLOR);
JLabel installedPluginsCaption = new JLabel("Installed Plugins:");
installedPluginsCaption.setFont(LINK_FONT);
installedPluginsCaption.setForeground(CAPTION_COLOR);
JPanel installedPluginsPanel = new JPanel(new GridBagLayout());
installedPluginsPanel.setBackground(PLUGINS_PANEL_COLOR);
JLabel embeddedPluginsCaption = new JLabel("Bundled Plugins:");
embeddedPluginsCaption.setFont(LINK_FONT);
embeddedPluginsCaption.setForeground(CAPTION_COLOR);
JPanel embeddedPluginsPanel = new JPanel(new GridBagLayout());
embeddedPluginsPanel.setBackground(PLUGINS_PANEL_COLOR);
JPanel topPluginsPanel = new JPanel(new GridBagLayout());
topPluginsPanel.setBackground(PLUGINS_PANEL_COLOR);
//Create the list of installed plugins
PluginDescriptor[] myInstalledPlugins = PluginManager.getPlugins();
if (myInstalledPlugins == null || myInstalledPlugins.length == 0) {
addListItemToPlugins(installedPluginsPanel, "<html><i>No plugins currently installed.</i></html>", null, null, null, null);
addListItemToPlugins(embeddedPluginsPanel, "<html><i>All bundled plugins are uninstalled.</i></html>", null, null, null, null);
}
else {
final Comparator<PluginDescriptor> pluginsComparator = new Comparator<PluginDescriptor>() {
public int compare(final PluginDescriptor o1, final PluginDescriptor o2) {
return o1.getName().compareTo(o2.getName());
}
};
Arrays.sort(myInstalledPlugins, pluginsComparator);
for (int i = 0; i < myInstalledPlugins.length; i++) {
PluginDescriptor plugin = myInstalledPlugins[i];
if (JET_BRAINS.equalsIgnoreCase(plugin.getVendor()) || INTELLIJ.equalsIgnoreCase(plugin.getVendor()) ) {
addListItemToPlugins(embeddedPluginsPanel, plugin.getName(), plugin.getDescription(), plugin.getVendorLogoPath(),
plugin.getPluginClassLoader(), plugin.getUrl());
}
else {
addListItemToPlugins(installedPluginsPanel, plugin.getName(), plugin.getDescription(), plugin.getVendorLogoPath(),
plugin.getPluginClassLoader(), plugin.getUrl());
}
}
}
GridBagConstraints gBC = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(17, 25, 0, 0), 0, 0);
topPluginsPanel.add(pluginsCaption, gBC);
JLabel emptyLabel_1 = new JLabel();
emptyLabel_1.setBackground(PLUGINS_PANEL_COLOR);
gBC = new GridBagConstraints(1, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
topPluginsPanel.add(emptyLabel_1, gBC);
gBC = new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(13, 0, 0, 10), 0, 0);
MyActionButton openPluginManager = new PluginsActionButton(OPEN_PLUGINS_ICON, null) {
protected void onPress(InputEvent e) {
ShowSettingsUtil.getInstance().editConfigurable(myPluginsPanel, PluginManagerConfigurable.getInstance());
}
public Dimension getMaximumSize() {
return OPEN_PLUGIN_MANAGER_SIZE;
}
public Dimension getMinimumSize() {
return OPEN_PLUGIN_MANAGER_SIZE;
}
public Dimension getPreferredSize() {
return OPEN_PLUGIN_MANAGER_SIZE;
}
};
openPluginManager.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
topPluginsPanel.add(openPluginManager, gBC);
openPluginManager.setupWithinPanel(myPluginsPanel, PLUGINS_GROUP, myPluginsButtonsCount, 0);
myPluginsButtonsCount++;
gBC = new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(15, 25, 0, 0), 0, 0);
topPluginsPanel.add(installedPluginsCaption, gBC);
JLabel emptyLabel_2 = new JLabel();
emptyLabel_2.setBackground(PLUGINS_PANEL_COLOR);
gBC = new GridBagConstraints(1, 1, 2, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
topPluginsPanel.add(emptyLabel_2, gBC);
gBC = new GridBagConstraints(0, 0, 1, 1, 0.5, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0);
myPluginsPanel.add(topPluginsPanel, gBC);
gBC = new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 5, 0, 0), 0, 0);
myPluginsPanel.add(installedPluginsPanel, gBC);
JPanel emptyPanel_1 = new JPanel();
emptyPanel_1.setBackground(PLUGINS_PANEL_COLOR);
gBC = new GridBagConstraints(0, 2, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 25, 0, 0), 0, 0);
myPluginsPanel.add(embeddedPluginsCaption, gBC);
gBC = new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(5, 5, 0, 0), 0, 0);
myPluginsPanel.add(embeddedPluginsPanel, gBC);
gBC = new GridBagConstraints(0, 4, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
myPluginsPanel.add(emptyPanel_1, gBC);
JScrollPane myPluginsScrollPane = ScrollPaneFactory.createScrollPane(myPluginsPanel);
myPluginsScrollPane.setBorder(BorderFactory.createLineBorder(GRAY_BORDER_COLOR));
myPluginsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myPluginsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
// Create Main Panel for Quick Start and Documentation
myMainPanel = new JPanel(new GridBagLayout());
myMainPanel.setBackground(MAIN_PANEL_COLOR);
ActionGroupDescriptor quickStarts = new ActionGroupDescriptor("Quick Start", 0);
MyActionButton newProject = new MyActionButton(NEW_PROJECT_ICON, null) {
protected void onPress(InputEvent e) {
ProjectUtil.createNewProject(null);
}
};
quickStarts.addButton(newProject, "Create New Project", "Start the \"New Project\" Wizard that will guide you through " +
"the steps necessary for creating a new project.");
// TODO[pti]: add button "Open Project" to the Quickstart list
final ActionManager actionManager = ActionManager.getInstance();
MyActionButton openRecentProject = new ButtonWithExtension(REOPEN_RECENT_ICON, null) {
protected void onPress(InputEvent e, final MyActionButton button) {
final AnAction action = new RecentProjectsAction();
action.actionPerformed(new AnActionEvent(e, new DataContext() {
public Object getData(String dataId) {
if (DataConstants.PROJECT.equals(dataId)) {
return null;
}
return button;
}
}, ActionPlaces.UNKNOWN, new PresentationFactory().getPresentation(action), actionManager, 0));
}
};
quickStarts.addButton(openRecentProject, "Reopen Recent Project...", "You can open one of the most recent " +
"projects you were working with. Click the icon " +
"or link to select a project from the list.");
MyActionButton getFromVCS = new ButtonWithExtension(FROM_VCS_ICON, null) {
protected void onPress(InputEvent e, final MyActionButton button) {
final GetFromVcsAction action = new GetFromVcsAction();
action.actionPerformed(button, e);
}
};
quickStarts.addButton(getFromVCS, "Get Project From Version Control...", "You can check out an entire project from " +
"a Version Control System. Click the icon or link to " +
"select your VCS.");
// TODO[pti]: add button "Check for Updates" to the Quickstart list
// Append plug-in actions to the end of the QuickStart list
quickStarts.appendActionsFromGroup((DefaultActionGroup)actionManager.getAction(IdeActions.GROUP_WELCOME_SCREEN_QUICKSTART));
ActionGroupDescriptor docsGroup = new ActionGroupDescriptor("Documentation", 1);
MyActionButton readHelp = new MyActionButton(READ_HELP_ICON, null) {
protected void onPress(InputEvent e) {
HelpManagerImpl.getInstance().invokeHelp("");
}
};
docsGroup.addButton(readHelp, "Read Help", "Open IntelliJ IDEA \"Help Topics\" in a new window.");
MyActionButton defaultKeymap = new MyActionButton(KEYMAP_ICON, null) {
protected void onPress(InputEvent e) {
try {
BrowserUtil.launchBrowser(KEYMAP_URL);
}
catch (IllegalThreadStateException ex) {
// it's not a problem
}
}
};
docsGroup.addButton(defaultKeymap, "Default Keymap", "Open PDF file with the default keymap reference card.");
// Append plug-in actions to the end of the QuickStart list
docsGroup.appendActionsFromGroup((DefaultActionGroup)actionManager.getAction(IdeActions.GROUP_WELCOME_SCREEN_DOC));
JPanel emptyPanel_2 = new JPanel();
emptyPanel_2.setBackground(MAIN_PANEL_COLOR);
final JPanel quickStartPanel = quickStarts.getPanel();
quickStartPanel.add(emptyPanel_2,
new GridBagConstraints(0, quickStarts.getIdx() + 2, 2, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
JPanel emptyPanel_3 = new JPanel();
emptyPanel_3.setBackground(MAIN_PANEL_COLOR);
final JPanel docsPanel = docsGroup.getPanel();
docsPanel.add(emptyPanel_3,
new GridBagConstraints(0, docsGroup.getIdx() + 2, 2, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
// Fill Main Panel with Quick Start and Documentation lists
gBC = new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 30, 0, 0), 0, 0);
myMainPanel.add(quickStartPanel, gBC);
gBC = new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 15, 0, 0), 0, 0);
myMainPanel.add(docsPanel, gBC);
myMainPanel.setPreferredSize(new Dimension(650, 450));
JScrollPane myMainScrollPane = ScrollPaneFactory.createScrollPane(myMainPanel);
myMainScrollPane.setBorder(null);
myMainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myMainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
// Create caption pane
JPanel topPanel = new JPanel(new GridBagLayout()) {
public void paint(Graphics g) {
Icon welcome = CAPTION_IMAGE;
welcome.paintIcon(null, g, 0, 0);
g.setColor(CAPTION_BACKGROUND);
g.fillRect(welcome.getIconWidth(), 0, this.getWidth() - welcome.getIconWidth(), welcome.getIconHeight());
super.paint(g);
}
};
topPanel.setOpaque(false);
JPanel transparentTopPanel = new JPanel();
transparentTopPanel.setOpaque(false);
topPanel.add(transparentTopPanel,
new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
topPanel.add(new JLabel(DEVELOP_SLOGAN),
new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.SOUTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
// Create the base welcome panel
myWelcomePanel = new JPanel(new GridBagLayout());
myWelcomePanel.setBackground(MAIN_PANEL_BACKGROUND);
gBC = new GridBagConstraints(0, 0, 3, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 5, 0, 5), 0, 0);
myWelcomePanel.add(topPanel, gBC);
gBC = new GridBagConstraints(0, 1, 2, 1, 1.4, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(15, 15, 15, 0), 0, 0);
myWelcomePanel.add(myMainScrollPane, gBC);
gBC = new GridBagConstraints(2, 1, 1, 1, 0.6, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(15, 15, 15, 15), 0, 0);
myWelcomePanel.add(myPluginsScrollPane, gBC);
}
public static JPanel createWelcomePanel() {
return new WelcomeScreen().myWelcomePanel;
}
public void addListItemToPlugins(JPanel panel, String name, String description, String iconPath, ClassLoader pluginClassLoader, final String url) {
if (StringUtil.isEmptyOrSpaces(name)) {
return;
}
else {
name = name.trim();
}
final int y = myPluginsIdx += 2;
Icon logoImage;
// Check the iconPath and insert empty icon in case of empty or invalid value
if (StringUtil.isEmptyOrSpaces(iconPath)) {
logoImage = EmptyIcon.create(PLUGIN_LOGO_SIZE.width, PLUGIN_LOGO_SIZE.height);
}
else {
logoImage = IconLoader.findIcon(iconPath, pluginClassLoader);
if (logoImage == null) logoImage = EmptyIcon.create(PLUGIN_LOGO_SIZE.width, PLUGIN_LOGO_SIZE.height);
}
JLabel imageLabel = new JLabel(logoImage);
GridBagConstraints gBC = new GridBagConstraints(0, y, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(15, 20, 0, 0), 0, 0);
panel.add(imageLabel, gBC);
String shortenedName = adjustStringBreaksByWidth(name, LINK_FONT, false, PLUGIN_NAME_MAX_WIDTH, PLUGIN_NAME_MAX_ROWS);
JLabel logoName = new JLabel(shortenedName);
logoName.setFont(LINK_FONT);
logoName.setForeground(CAPTION_COLOR);
if (shortenedName.endsWith("...</html>")) {
logoName.setToolTipText(adjustStringBreaksByWidth(name, UIManager.getFont("ToolTip.font"), false, MAX_TOOLTIP_WIDTH, 0));
}
gBC = new GridBagConstraints(1, y, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(15, 7, 0, 0), 0, 0);
panel.add(logoName, gBC);
if (!StringUtil.isEmpty(description)) {
description = description.trim();
if (description.startsWith("<html>")) {
description = description.replaceAll("<html>", "");
if (description.endsWith("</html>")) {
description = description.replaceAll("</html>", "");
}
}
description = description.replaceAll("\\n", "");
String shortenedDcs = adjustStringBreaksByWidth(description, TEXT_FONT, false, PLUGIN_DSC_MAX_WIDTH, PLUGIN_DSC_MAX_ROWS);
JLabel pluginDescription = new JLabel(shortenedDcs);
pluginDescription.setFont(TEXT_FONT);
if (shortenedDcs.endsWith("...</html>")) {
pluginDescription.setToolTipText(adjustStringBreaksByWidth(description, UIManager.getFont("ToolTip.font"), false, MAX_TOOLTIP_WIDTH, 0));
}
gBC = new GridBagConstraints(1, y + 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 7, 0, 0), 5, 0);
panel.add(pluginDescription, gBC);
}
if (!StringUtil.isEmptyOrSpaces(url)) {
gBC = new GridBagConstraints(2, y, 1, 2, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 7, 0, 0), 0, 0);
JLabel label = new JLabel("<html><nobr><u>Learn More...</u></nobr></html>");
label.setFont(TEXT_FONT);
label.setForeground(CAPTION_COLOR);
label.setToolTipText(url);
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
BrowserUtil.launchBrowser(url);
}
catch (IllegalThreadStateException ex) {
// it's not a problem
}
}
});
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
panel.add(label, gBC);
gBC = new GridBagConstraints(3, y, 1, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 7, 0, 10), 0, 0);
MyActionButton learnMore = new PluginsActionButton(LEARN_MORE_ICON, null) {
protected void onPress(InputEvent e) {
try {
BrowserUtil.launchBrowser(url);
}
catch (IllegalThreadStateException ex) {
// it's not a problem
}
}
};
learnMore.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
panel.add(learnMore, gBC);
learnMore.setupWithinPanel(myPluginsPanel, PLUGINS_GROUP, myPluginsButtonsCount, 0);
myPluginsButtonsCount++;
}
else {
gBC = new GridBagConstraints(2, y, 2, 2, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 10), 0, 0);
JPanel emptyPane = new JPanel();
emptyPane.setBackground(PLUGINS_PANEL_COLOR);
panel.add(emptyPane, gBC);
}
}
/**
* This method checks the width of the given string with given font applied, breaks the string into the specified number of lines if necessary,
* and/or cuts it, so that the string does not exceed the given width (with ellipsis concatenated at the end if needed).
* Returns the resulting or original string surrounded by html tags.
* @param string not <code>null</code> {@link String String} value, otherwise the "Not specified." string is returned.
* @return the resulting or original string ({@link String String}) surrounded by <code>html</html> tags.
* @param font not <code>null</code> {@link Font Font} object.
* @param isAntiAliased <code>boolean</code> value to denote whether the font is antialiased or not.
* @param maxWidth <code>int</code> value specifying maximum width of the resulting string in pixels.
* @param maxRows <code>int</code> value spesifying the number of rows. If the value is positive, the string is modified to not exceed
* the specified number, and method adds an ellipsis instead of the exceeding part. If the value is zero or negative, the entire string is broken
* into lines until its end.
*/
private String adjustStringBreaksByWidth(String string,
final Font font,
final boolean isAntiAliased,
final int maxWidth,
final int maxRows) {
String modifiedString = string.trim();
if (StringUtil.isEmpty(modifiedString)) {
return "<html>Not specified.</html>";
}
Rectangle2D r = font.getStringBounds(string, new FontRenderContext(new AffineTransform(), isAntiAliased, false));
if (r.getWidth() > maxWidth) {
String prefix = "";
String suffix = string.trim();
int maxIdxPerLine = (int)(maxWidth / r.getWidth() * string.length());
int lengthLeft = string.length();
int rows = maxRows;
if (rows <= 0) {
rows = string.length() / maxIdxPerLine + 1;
}
while (lengthLeft > maxIdxPerLine && rows > 1) {
int i;
for (i = maxIdxPerLine; i > 0; i
if (suffix.charAt(i) == ' ') {
prefix += suffix.substring(0, i) + "<br>";
suffix = suffix.substring(i + 1, suffix.length());
lengthLeft = suffix.length();
if (maxRows > 0) {
rows
}
else {
rows = lengthLeft / maxIdxPerLine + 1;
}
break;
}
}
if (i == 0) {
if (rows > 1 && maxRows <= 0) {
prefix += suffix.substring(0, maxIdxPerLine) + "<br>";
suffix = suffix.substring(maxIdxPerLine, suffix.length());
lengthLeft = suffix.length();
rows
}
else {
break;
}
}
}
if (suffix.length() > maxIdxPerLine) {
suffix = suffix.substring(0, maxIdxPerLine - 3) + "...";
}
modifiedString = prefix + suffix;
}
return "<html>" + modifiedString + "</html>";
}
private abstract class MyActionButton extends JComponent implements ActionButtonComponent {
private int myGroupIdx;
private int myRowIdx;
private int myColumnIdx;
private String myDisplayName;
private Icon myIcon;
private MyActionButton(Icon icon, String displayName) {
myDisplayName = displayName;
myIcon = new LabeledIcon(icon != null ? icon : DEFAULT_ICON, getDisplayName(), null);
}
private void setupWithinPanel(JPanel panel, int groupIdx, int rowIdx, int columnIdx) {
myGroupIdx = groupIdx;
myRowIdx = rowIdx;
myColumnIdx = columnIdx;
if (groupIdx == MAIN_GROUP) {
ourMainButtons.add(MyActionButton.this);
}
else if (groupIdx == PLUGINS_GROUP) {
ourPluginButtons.add(MyActionButton.this);
}
setToolTipText(null);
setupListeners(panel);
}
protected int getColumnIdx() {
return myColumnIdx;
}
protected int getGroupIdx() {
return myGroupIdx;
}
protected int getRowIdx() {
return myRowIdx;
}
protected String getDisplayName() {
return myDisplayName != null ? myDisplayName : "";
}
public Dimension getMaximumSize() {
return ACTION_BUTTON_SIZE;
}
public Dimension getMinimumSize() {
return ACTION_BUTTON_SIZE;
}
public Dimension getPreferredSize() {
return ACTION_BUTTON_SIZE;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
ActionButtonLook look = ActionButtonLook.IDEA_LOOK;
paintBackground(g);
look.paintIcon(g, this, myIcon);
paintBorder(g);
}
protected Color getNormalButtonColor() {
return ACTION_BUTTON_COLOR;
}
protected void paintBackground(Graphics g) {
Dimension dimension = getSize();
int state = getPopState();
if (state != ActionButtonComponent.NORMAL) {
if (state == ActionButtonComponent.POPPED) {
g.setColor(BUTTON_POPPED_COLOR);
g.fillRect(0, 0, dimension.width, dimension.height);
}
else {
g.setColor(BUTTON_PUSHED_COLOR);
g.fillRect(0, 0, dimension.width, dimension.height);
}
}
else {
g.setColor(getNormalButtonColor());
g.fillRect(0, 0, dimension.width, dimension.height);
}
if (state == ActionButtonComponent.PUSHED) {
g.setColor(BUTTON_PUSHED_COLOR);
g.fillRect(0, 0, dimension.width, dimension.height);
}
}
protected void paintBorder(Graphics g) {
Rectangle rectangle = new Rectangle(getSize());
Color color = ACTION_BUTTON_BORDER_COLOR;
g.setColor(color);
g.drawLine(rectangle.x, rectangle.y, rectangle.x, (rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x, rectangle.y, (rectangle.x + rectangle.width) - 1, rectangle.y);
g.drawLine((rectangle.x + rectangle.width) - 1, rectangle.y, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x, (rectangle.y + rectangle.height) - 1, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
}
public int getPopState() {
if (myKeypressedButton == this) return ActionButtonComponent.PUSHED;
if (myKeypressedButton != null) return ActionButtonComponent.NORMAL;
if (mySelectedColumn == myColumnIdx &&
mySelectedRow == myRowIdx &&
mySelectedGroup == myGroupIdx) {
return ActionButtonComponent.POPPED;
}
return ActionButtonComponent.NORMAL;
}
private void setupListeners(final JPanel panel) {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
myKeypressedButton = MyActionButton.this;
panel.repaint();
}
public void mouseReleased(MouseEvent e) {
if (myKeypressedButton == MyActionButton.this) {
myKeypressedButton = null;
onPress(e);
}
else {
myKeypressedButton = null;
}
panel.repaint();
}
public void mouseExited(MouseEvent e) {
mySelectedColumn = -1;
mySelectedRow = -1;
mySelectedGroup = -1;
panel.repaint();
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
mySelectedColumn = myColumnIdx;
mySelectedRow = myRowIdx;
mySelectedGroup = myGroupIdx;
panel.repaint();
}
});
}
protected abstract void onPress(InputEvent e);
}
private abstract class ButtonWithExtension extends MyActionButton {
private ButtonWithExtension(Icon icon, String displayName) {
super(icon, displayName);
}
protected void onPress(InputEvent e) {
onPress(e, this);
}
protected abstract void onPress(InputEvent e, MyActionButton button);
}
private abstract class PluginsActionButton extends MyActionButton {
protected PluginsActionButton(Icon icon, String displayName) {
super(icon, displayName);
}
public Dimension getMaximumSize() {
return LEARN_MORE_SIZE;
}
public Dimension getMinimumSize() {
return LEARN_MORE_SIZE;
}
public Dimension getPreferredSize() {
return LEARN_MORE_SIZE;
}
@Override protected Color getNormalButtonColor() {
return LEARN_MORE_BUTTON_COLOR;
}
protected void paintBorder(Graphics g) {
Rectangle rectangle = new Rectangle(getSize());
Color color = WHITE_BORDER_COLOR;
g.setColor(color);
g.drawLine(rectangle.x, rectangle.y, rectangle.x, (rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x, rectangle.y, (rectangle.x + rectangle.width) - 1, rectangle.y);
color = GRAY_BORDER_COLOR;
g.setColor(color);
g.drawLine((rectangle.x + rectangle.width) - 1, rectangle.y + 1, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x + 1, (rectangle.y + rectangle.height) - 1, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
}
}
} |
package com.intellij.openapi.wm.impl.welcomeScreen;
import com.intellij.help.impl.HelpManagerImpl;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.DataManager;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.plugins.PluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.plugins.PluginManagerConfigurable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionButtonLook;
import com.intellij.openapi.actionSystem.impl.EmptyIcon;
import com.intellij.openapi.actionSystem.impl.PresentationFactory;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.LabeledIcon;
import com.intellij.ui.ScrollPaneFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
public class WelcomeScreen {
private JPanel myWelcomePanel;
private JPanel myMainPanel;
private JPanel myPluginsPanel;
private static final Insets ICON_INSETS = new Insets(15, 0, 15, 0);
// The below 3 array lists are reserved for future use
private static ArrayList<MyActionButton> ourMainButtons = new ArrayList<MyActionButton>(5);
private static ArrayList<MyActionButton> ourPluginButtons = new ArrayList<MyActionButton>(5);
private static ArrayList<PluginDescriptor> ourPluginsWithActions = new ArrayList<PluginDescriptor>();
private MyActionButton myKeypressedButton = null;
private int mySelectedRow = -1;
private int mySelectedColumn = -1;
private int mySelectedGroup = -1;
private static final int MAIN_GROUP = 0;
private static final int PLUGINS_GROUP = 1;
private static final int COLUMNS_IN_MAIN = 2;
private static final int PLUGIN_DSC_MAX_WIDTH = 180;
private static final int PLUGIN_DSC_MAX_ROWS = 2;
private static final int PLUGIN_NAME_MAX_WIDTH = 180;
private static final int PLUGIN_NAME_MAX_ROWS = 2;
private static final int MAX_TOOLTIP_WIDTH = 400;
private static final Dimension ACTION_BUTTON_SIZE = new Dimension(78, 78);
private static final Dimension PLUGIN_LOGO_SIZE = new Dimension(16, 16);
private static final Dimension LEARN_MORE_SIZE = new Dimension(26, 26);
private static final Dimension OPEN_PLUGIN_MANAGER_SIZE = new Dimension(166, 31);
private static final Icon LEARN_MORE_ICON = IconLoader.getIcon("/general/learnMore.png");
private static final Icon OPEN_PLUGINS_ICON = IconLoader.getIcon("/general/openPluginManager.png");
private static final Icon CAPTION_IMAGE = IconLoader.getIcon("/general/welcomeCaption.png");
private static final Icon DEVELOP_SLOGAN = IconLoader.getIcon("/general/developSlogan.png");
private static final Icon NEW_PROJECT_ICON = IconLoader.getIcon("/general/createNewProject.png");
private static final Icon REOPEN_RECENT_ICON = IconLoader.getIcon("/general/reopenRecentProject.png");
private static final Icon FROM_VCS_ICON = IconLoader.getIcon("/general/getProjectfromVCS.png");
private static final Icon READ_HELP_ICON = IconLoader.getIcon("/general/readHelp.png");
private static final Icon KEYMAP_ICON = IconLoader.getIcon("/general/defaultKeymap.png");
private static final Icon DEFAULT_ICON = IconLoader.getIcon("/general/configurableDefault.png");
private static final String KEYMAP_URL = PathManager.getHomePath() + "/help/4.5_ReferenceCard.pdf";
private static final Font TEXT_FONT = new Font("Tahoma", Font.PLAIN, 11);
private static final Font LINK_FONT = new Font("Tahoma", Font.BOLD, 12);
private static final Font CAPTION_FONT = new Font("Tahoma", Font.BOLD, 18);
private static final Color CAPTION_COLOR = new Color(47, 67, 96);
private static final Color PLUGINS_PANEL_COLOR = new Color(229, 229, 229);
private static final Color MAIN_PANEL_COLOR = new Color(210, 213, 226);
private static final Color BUTTON_PUSHED_COLOR = new Color(130, 146, 185);
private static final Color BUTTON_POPPED_COLOR = new Color(181, 190, 214);
private static final Color MAIN_PANEL_BACKGROUND = new Color(238, 238, 238);
private static final Color LEARN_MORE_BUTTON_COLOR = new Color(238, 238, 238);
private static final Color GRAY_BORDER_COLOR = new Color(177, 177, 177);
private static final Color CAPTION_BACKGROUND = new Color(24, 52, 146);
private static final Color ACTION_BUTTON_COLOR = new Color(201, 205, 217);
private static final Color ACTION_BUTTON_BORDER_COLOR = new Color(166, 170, 182);
private static final Color WHITE_BORDER_COLOR = new Color(255, 255, 255);
private int myPluginsButtonsCount = 0;
private int myPluginsIdx = -1;
private class ActionGroupDescriptor {
private int myIdx = -1;
private int myCount = 0;
private JPanel myPanel;
private final int myColumnIdx;
public ActionGroupDescriptor(final String caption, final int columnIndex) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(MAIN_PANEL_COLOR);
JLabel quickStartCaption = new JLabel(caption);
quickStartCaption.setFont(CAPTION_FONT);
quickStartCaption.setForeground(CAPTION_COLOR);
GridBagConstraints gBC = new GridBagConstraints(0, 0, 2, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(20, 0, 5, 0), 0, 0);
panel.add(quickStartCaption, gBC);
myPanel = panel;
myColumnIdx = columnIndex;
}
public void addButton(final MyActionButton button, String commandLink, String description) {
final int y = myIdx += 2;
GridBagConstraints gBC =
new GridBagConstraints(0, y, 1, 2, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, ICON_INSETS, 5, 5);
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
myPanel.add(button, gBC);
button.setupWithinPanel(myMainPanel, MAIN_GROUP, myCount, myColumnIdx);
myCount++;
JLabel name = new JLabel("<html><nobr><u>" + commandLink + "</u></nobr></html>");
name.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
button.onPress(e);
}
});
name.setForeground(CAPTION_COLOR);
name.setFont(LINK_FONT);
name.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
gBC = new GridBagConstraints(1, y, 1, 1, 0, 0, GridBagConstraints.SOUTHWEST, GridBagConstraints.NONE, new Insets(15, 15, 0, 0), 5, 0);
myPanel.add(name, gBC);
description = "<HTML>" + description + "</html>";
JLabel shortDescription = new JLabel(description);
shortDescription.setFont(TEXT_FONT);
gBC = new GridBagConstraints(1, y + 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(7, 15, 0, 30), 5, 0);
myPanel.add(shortDescription, gBC);
}
private void appendActionsFromGroup(final DefaultActionGroup group) {
final AnAction[] actions = group.getChildren(null);
for (final AnAction action : actions) {
final Presentation presentation = action.getTemplatePresentation();
final Icon icon = presentation.getIcon();
final String text = presentation.getText();
MyActionButton button = new ButtonWithExtension(icon, "") {
protected void onPress(InputEvent e, MyActionButton button) {
final ActionManager actionManager = ActionManager.getInstance();
AnActionEvent evt = new AnActionEvent(
null,
DataManager.getInstance().getDataContext(this),
ActionPlaces.WELCOME_SCREEN,
action.getTemplatePresentation(),
actionManager,
0
);
action.update(evt);
if (evt.getPresentation().isEnabled()) {
action.actionPerformed(evt);
}
}
};
addButton(button, text, presentation.getDescription());
}
}
public JPanel getPanel() {
return myPanel;
}
public int getIdx() {
return myIdx;
}
}
private WelcomeScreen() {
// Create Plugins Panel
myPluginsPanel = new PluginsPanel(new GridBagLayout());
myPluginsPanel.setBackground(PLUGINS_PANEL_COLOR);
JLabel pluginsCaption = new JLabel("Plugins");
pluginsCaption.setFont(CAPTION_FONT);
pluginsCaption.setForeground(CAPTION_COLOR);
JLabel installedPluginsCaption = new JLabel("Installed Plugins");
installedPluginsCaption.setFont(LINK_FONT);
installedPluginsCaption.setForeground(CAPTION_COLOR);
JPanel pluginsListPanel = new JPanel(new GridBagLayout());
pluginsListPanel.setBackground(PLUGINS_PANEL_COLOR);
JPanel topPluginsPanel = new JPanel(new GridBagLayout());
topPluginsPanel.setBackground(PLUGINS_PANEL_COLOR);
//Create the list of installed plugins
PluginDescriptor[] myInstalledPlugins = PluginManager.getPlugins();
if (myInstalledPlugins == null || myInstalledPlugins.length == 0) {
addListItemToPlugins(pluginsListPanel, "<html><i>No plugins currently installed.</i></html>", null, null, null, null);
}
else {
for (int i = 0; i < myInstalledPlugins.length; i++) {
PluginDescriptor plugin = myInstalledPlugins[i];
addListItemToPlugins(pluginsListPanel, plugin.getName(), plugin.getDescription(), plugin.getVendorLogoPath(),
plugin.getPluginClassLoader(), plugin.getUrl());
}
}
GridBagConstraints gBC = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(17, 25, 0, 0), 0, 0);
topPluginsPanel.add(pluginsCaption, gBC);
JLabel emptyLabel_1 = new JLabel();
emptyLabel_1.setBackground(PLUGINS_PANEL_COLOR);
gBC = new GridBagConstraints(1, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
topPluginsPanel.add(emptyLabel_1, gBC);
gBC = new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(13, 0, 0, 10), 0, 0);
MyActionButton openPluginManager = new PluginsActionButton(OPEN_PLUGINS_ICON, null) {
protected void onPress(InputEvent e) {
ShowSettingsUtil.getInstance().editConfigurable(myPluginsPanel, PluginManagerConfigurable.getInstance());
}
public Dimension getMaximumSize() {
return OPEN_PLUGIN_MANAGER_SIZE;
}
public Dimension getMinimumSize() {
return OPEN_PLUGIN_MANAGER_SIZE;
}
public Dimension getPreferredSize() {
return OPEN_PLUGIN_MANAGER_SIZE;
}
};
openPluginManager.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
topPluginsPanel.add(openPluginManager, gBC);
openPluginManager.setupWithinPanel(myPluginsPanel, PLUGINS_GROUP, myPluginsButtonsCount, 0);
myPluginsButtonsCount++;
gBC = new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(15, 25, 0, 0), 0, 0);
topPluginsPanel.add(installedPluginsCaption, gBC);
JLabel emptyLabel_2 = new JLabel();
emptyLabel_2.setBackground(PLUGINS_PANEL_COLOR);
gBC = new GridBagConstraints(1, 1, 2, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
topPluginsPanel.add(emptyLabel_2, gBC);
gBC = new GridBagConstraints(0, 0, 1, 1, 0.5, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0);
myPluginsPanel.add(topPluginsPanel, gBC);
gBC = new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 5, 0, 0), 0, 0);
myPluginsPanel.add(pluginsListPanel, gBC);
JPanel emptyPanel_1 = new JPanel();
emptyPanel_1.setBackground(PLUGINS_PANEL_COLOR);
gBC = new GridBagConstraints(0, 2, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
myPluginsPanel.add(emptyPanel_1, gBC);
JScrollPane myPluginsScrollPane = ScrollPaneFactory.createScrollPane(myPluginsPanel);
myPluginsScrollPane.setBorder(BorderFactory.createLineBorder(GRAY_BORDER_COLOR));
myPluginsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myPluginsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
// Create Main Manel for Quick Start and Documentation
myMainPanel = new JPanel(new GridBagLayout());
myMainPanel.setBackground(MAIN_PANEL_COLOR);
ActionGroupDescriptor quickStarts = new ActionGroupDescriptor("Quick Start", 0);
MyActionButton newProject = new MyActionButton(NEW_PROJECT_ICON, null) {
protected void onPress(InputEvent e) {
ProjectUtil.createNewProject(null);
}
};
quickStarts.addButton(newProject, "Create New Project", "Start the \"New Project\" Wizard that will guide you through " +
"the steps necessary for creating a new project.");
// TODO[pti]: add button "Open Project" to the Quickstart list
final ActionManager actionManager = ActionManager.getInstance();
MyActionButton openRecentProject = new ButtonWithExtension(REOPEN_RECENT_ICON, null) {
protected void onPress(InputEvent e, final MyActionButton button) {
final AnAction action = new RecentProjectsAction();
action.actionPerformed(new AnActionEvent(e, new DataContext() {
public Object getData(String dataId) {
if (DataConstants.PROJECT.equals(dataId)) {
return null;
}
return button;
}
}, ActionPlaces.UNKNOWN, new PresentationFactory().getPresentation(action), actionManager, 0));
}
};
quickStarts.addButton(openRecentProject, "Reopen Recent Project...", "You can open one of the most recent " +
"projects you were working with. Click the icon " +
"or link to select project from the list.");
MyActionButton getFromVCS = new ButtonWithExtension(FROM_VCS_ICON, null) {
protected void onPress(InputEvent e, final MyActionButton button) {
final GetFromVcsAction action = new GetFromVcsAction();
action.actionPerformed(button, e);
}
};
quickStarts.addButton(getFromVCS, "Get Project From Version Control...", "You can check out entire project from " +
"Version Control System. Click the icon or link to " +
"select the VCS.");
// TODO[pti]: add button "Check for Updates" to the Quickstart list
// Append plug-in actions to the end of the QuickStart list
quickStarts.appendActionsFromGroup((DefaultActionGroup)actionManager.getAction(IdeActions.GROUP_WELCOME_SCREEN_QUICKSTART));
ActionGroupDescriptor docsGroup = new ActionGroupDescriptor("Documentation", 1);
MyActionButton readHelp = new MyActionButton(READ_HELP_ICON, null) {
protected void onPress(InputEvent e) {
HelpManagerImpl.getInstance().invokeHelp("");
}
};
docsGroup.addButton(readHelp, "Read Help", "Open IntelliJ IDEA \"Help Topics\" in a new window.");
MyActionButton defaultKeymap = new MyActionButton(KEYMAP_ICON, null) {
protected void onPress(InputEvent e) {
try {
BrowserUtil.launchBrowser(KEYMAP_URL);
}
catch (IllegalThreadStateException ex) {
// it's not a problem
}
}
};
docsGroup.addButton(defaultKeymap, "Default Keymap", "Open PDF file with the default keymap reference card.");
// Append plug-in actions to the end of the QuickStart list
docsGroup.appendActionsFromGroup((DefaultActionGroup)actionManager.getAction(IdeActions.GROUP_WELCOME_SCREEN_DOC));
JPanel emptyPanel_2 = new JPanel();
emptyPanel_2.setBackground(MAIN_PANEL_COLOR);
final JPanel quickStartPanel = quickStarts.getPanel();
quickStartPanel.add(emptyPanel_2,
new GridBagConstraints(0, quickStarts.getIdx() + 2, 2, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
JPanel emptyPanel_3 = new JPanel();
emptyPanel_3.setBackground(MAIN_PANEL_COLOR);
final JPanel docsPanel = docsGroup.getPanel();
docsPanel.add(emptyPanel_3,
new GridBagConstraints(0, docsGroup.getIdx() + 2, 2, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
// Fill Main Panel with Quick Start and Documentation lists
gBC = new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 30, 0, 0), 0, 0);
myMainPanel.add(quickStartPanel, gBC);
gBC = new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 15, 0, 0), 0, 0);
myMainPanel.add(docsPanel, gBC);
myMainPanel.setPreferredSize(new Dimension(650, 450));
JScrollPane myMainScrollPane = ScrollPaneFactory.createScrollPane(myMainPanel);
myMainScrollPane.setBorder(null);
myMainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myMainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
// Create caption pane
JPanel topPanel = new JPanel(new GridBagLayout()) {
public void paint(Graphics g) {
Icon welcome = CAPTION_IMAGE;
welcome.paintIcon(null, g, 0, 0);
g.setColor(CAPTION_BACKGROUND);
g.fillRect(welcome.getIconWidth(), 0, this.getWidth() - welcome.getIconWidth(), welcome.getIconHeight());
super.paint(g);
}
};
topPanel.setOpaque(false);
JPanel transparentTopPanel = new JPanel();
transparentTopPanel.setOpaque(false);
topPanel.add(transparentTopPanel,
new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
topPanel.add(new JLabel(DEVELOP_SLOGAN),
new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.SOUTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
// Create the base welcome panel
myWelcomePanel = new JPanel(new GridBagLayout());
myWelcomePanel.setBackground(MAIN_PANEL_BACKGROUND);
gBC = new GridBagConstraints(0, 0, 3, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 5, 0, 5), 0, 0);
myWelcomePanel.add(topPanel, gBC);
gBC = new GridBagConstraints(0, 1, 2, 1, 1.4, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(15, 15, 15, 0), 0, 0);
myWelcomePanel.add(myMainScrollPane, gBC);
gBC = new GridBagConstraints(2, 1, 1, 1, 0.6, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(15, 15, 15, 15), 0, 0);
myWelcomePanel.add(myPluginsScrollPane, gBC);
}
public static JPanel createWelcomePanel() {
return new WelcomeScreen().myWelcomePanel;
}
public void addListItemToPlugins(JPanel panel, String name, String description, String iconPath, ClassLoader pluginClassLoader, final String url) {
if (StringUtil.isEmptyOrSpaces(name)) {
return;
}
else {
name = name.trim();
}
final int y = myPluginsIdx += 2;
Icon logoImage;
// Check the iconPath and insert empty icon in case of empty or invalid value
if (StringUtil.isEmptyOrSpaces(iconPath)) {
logoImage = EmptyIcon.create(PLUGIN_LOGO_SIZE.width, PLUGIN_LOGO_SIZE.height);
}
else {
logoImage = IconLoader.findIcon(iconPath, pluginClassLoader);
if (logoImage == null) logoImage = EmptyIcon.create(PLUGIN_LOGO_SIZE.width, PLUGIN_LOGO_SIZE.height);
}
JLabel imageLabel = new JLabel(logoImage);
GridBagConstraints gBC = new GridBagConstraints(0, y, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(15, 20, 0, 0), 0, 0);
panel.add(imageLabel, gBC);
String shortenedName = adjustStringBreaksByWidth(name, LINK_FONT, false, PLUGIN_NAME_MAX_WIDTH, PLUGIN_NAME_MAX_ROWS);
JLabel logoName = new JLabel(shortenedName);
logoName.setFont(LINK_FONT);
logoName.setForeground(CAPTION_COLOR);
if (shortenedName.endsWith("...</html>")) {
logoName.setToolTipText(adjustStringBreaksByWidth(name, UIManager.getFont("ToolTip.font"), false, MAX_TOOLTIP_WIDTH, 0));
}
gBC = new GridBagConstraints(1, y, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(15, 7, 0, 0), 0, 0);
panel.add(logoName, gBC);
if (!StringUtil.isEmpty(description)) {
description = description.trim();
if (description.startsWith("<html>")) {
description = description.replaceAll("<html>", "");
if (description.endsWith("</html>")) {
description = description.replaceAll("</html>", "");
}
}
description = description.replaceAll("\\n", "");
String shortenedDcs = adjustStringBreaksByWidth(description, TEXT_FONT, false, PLUGIN_DSC_MAX_WIDTH, PLUGIN_DSC_MAX_ROWS);
JLabel pluginDescription = new JLabel(shortenedDcs);
pluginDescription.setFont(TEXT_FONT);
if (shortenedDcs.endsWith("...</html>")) {
pluginDescription.setToolTipText(adjustStringBreaksByWidth(description, UIManager.getFont("ToolTip.font"), false, MAX_TOOLTIP_WIDTH, 0));
}
gBC = new GridBagConstraints(1, y + 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 7, 0, 0), 5, 0);
panel.add(pluginDescription, gBC);
}
if (!StringUtil.isEmptyOrSpaces(url)) {
gBC = new GridBagConstraints(2, y, 1, 2, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 7, 0, 0), 0, 0);
JLabel label = new JLabel("<html><nobr><u>Learn More...</u></nobr></html>");
label.setFont(TEXT_FONT);
label.setForeground(CAPTION_COLOR);
label.setToolTipText(url);
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
BrowserUtil.launchBrowser(url);
}
catch (IllegalThreadStateException ex) {
// it's not a problem
}
}
});
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
panel.add(label, gBC);
gBC = new GridBagConstraints(3, y, 1, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 7, 0, 10), 0, 0);
MyActionButton learnMore = new PluginsActionButton(LEARN_MORE_ICON, null) {
protected void onPress(InputEvent e) {
try {
BrowserUtil.launchBrowser(url);
}
catch (IllegalThreadStateException ex) {
// it's not a problem
}
}
};
learnMore.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
panel.add(learnMore, gBC);
learnMore.setupWithinPanel(myPluginsPanel, PLUGINS_GROUP, myPluginsButtonsCount, 0);
myPluginsButtonsCount++;
}
else {
gBC = new GridBagConstraints(2, y, 2, 2, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 10), 0, 0);
JPanel emptyPane = new JPanel();
emptyPane.setBackground(PLUGINS_PANEL_COLOR);
panel.add(emptyPane, gBC);
}
}
/**
* This method checks the width of the given string with given font applied, breaks the string into the specified number of lines if necessary,
* and/or cuts it, so that the string does not exceed the given width (with ellipsis concatenated at the end if needed).
* Returns the resulting or original string surrounded by html tags.
* @param string not <code>null</code> {@link String String} value, otherwise the "Not specified." string is returned.
* @return the resulting or original string ({@link String String}) surrounded by <code>html</html> tags.
* @param font not <code>null</code> {@link Font Font} object.
* @param isAntiAliased <code>boolean</code> value to denote whether the font is antialiased or not.
* @param maxWidth <code>int</code> value specifying maximum width of the resulting string in pixels.
* @param maxRows <code>int</code> value spesifying the number of rows. If the value is positive, the string is modified to not exceed
* the specified number, and method adds an ellipsis instead of the exceeding part. If the value is zero or negative, the entire string is broken
* into lines until its end.
*/
private String adjustStringBreaksByWidth(String string,
final Font font,
final boolean isAntiAliased,
final int maxWidth,
final int maxRows) {
String modifiedString = string.trim();
if (StringUtil.isEmpty(modifiedString)) {
return "<html>Not specified.</html>";
}
Rectangle2D r = font.getStringBounds(string, new FontRenderContext(new AffineTransform(), isAntiAliased, false));
if (r.getWidth() > maxWidth) {
String prefix = "";
String suffix = string.trim();
int maxIdxPerLine = (int)(maxWidth / r.getWidth() * string.length());
int lengthLeft = string.length();
int rows = maxRows;
if (rows <= 0) {
rows = string.length() / maxIdxPerLine + 1;
}
while (lengthLeft > maxIdxPerLine && rows > 1) {
int i;
for (i = maxIdxPerLine; i > 0; i
if (suffix.charAt(i) == ' ') {
prefix += suffix.substring(0, i) + "<br>";
suffix = suffix.substring(i + 1, suffix.length());
lengthLeft = suffix.length();
if (maxRows > 0) {
rows
}
else {
rows = lengthLeft / maxIdxPerLine + 1;
}
break;
}
}
if (i == 0) {
if (rows > 1 && maxRows <= 0) {
prefix += suffix.substring(0, maxIdxPerLine) + "<br>";
suffix = suffix.substring(maxIdxPerLine, suffix.length());
lengthLeft = suffix.length();
rows
}
else {
break;
}
}
}
if (suffix.length() > maxIdxPerLine) {
suffix = suffix.substring(0, maxIdxPerLine - 3) + "...";
}
modifiedString = prefix + suffix;
}
return "<html>" + modifiedString + "</html>";
}
private abstract class MyActionButton extends JComponent implements ActionButtonComponent {
private int myGroupIdx;
private int myRowIdx;
private int myColumnIdx;
private String myDisplayName;
private Icon myIcon;
private MyActionButton(Icon icon, String displayName) {
myDisplayName = displayName;
myIcon = new LabeledIcon(icon != null ? icon : DEFAULT_ICON, getDisplayName(), null);
}
private void setupWithinPanel(JPanel panel, int groupIdx, int rowIdx, int columnIdx) {
myGroupIdx = groupIdx;
myRowIdx = rowIdx;
myColumnIdx = columnIdx;
if (groupIdx == MAIN_GROUP) {
ourMainButtons.add(MyActionButton.this);
}
else if (groupIdx == PLUGINS_GROUP) {
ourPluginButtons.add(MyActionButton.this);
}
setToolTipText(null);
setupListeners(panel);
}
protected int getColumnIdx() {
return myColumnIdx;
}
protected int getGroupIdx() {
return myGroupIdx;
}
protected int getRowIdx() {
return myRowIdx;
}
protected String getDisplayName() {
return myDisplayName != null ? myDisplayName : "";
}
public Dimension getMaximumSize() {
return ACTION_BUTTON_SIZE;
}
public Dimension getMinimumSize() {
return ACTION_BUTTON_SIZE;
}
public Dimension getPreferredSize() {
return ACTION_BUTTON_SIZE;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
ActionButtonLook look = ActionButtonLook.IDEA_LOOK;
paintBackground(g);
look.paintIcon(g, this, myIcon);
paintBorder(g);
}
protected Color getNormalButtonColor() {
return ACTION_BUTTON_COLOR;
}
protected void paintBackground(Graphics g) {
Dimension dimension = getSize();
int state = getPopState();
if (state != ActionButtonComponent.NORMAL) {
if (state == ActionButtonComponent.POPPED) {
g.setColor(BUTTON_POPPED_COLOR);
g.fillRect(0, 0, dimension.width, dimension.height);
}
else {
g.setColor(BUTTON_PUSHED_COLOR);
g.fillRect(0, 0, dimension.width, dimension.height);
}
}
else {
g.setColor(getNormalButtonColor());
g.fillRect(0, 0, dimension.width, dimension.height);
}
if (state == ActionButtonComponent.PUSHED) {
g.setColor(BUTTON_PUSHED_COLOR);
g.fillRect(0, 0, dimension.width, dimension.height);
}
}
protected void paintBorder(Graphics g) {
Rectangle rectangle = new Rectangle(getSize());
Color color = ACTION_BUTTON_BORDER_COLOR;
g.setColor(color);
g.drawLine(rectangle.x, rectangle.y, rectangle.x, (rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x, rectangle.y, (rectangle.x + rectangle.width) - 1, rectangle.y);
g.drawLine((rectangle.x + rectangle.width) - 1, rectangle.y, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x, (rectangle.y + rectangle.height) - 1, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
}
public int getPopState() {
if (myKeypressedButton == this) return ActionButtonComponent.PUSHED;
if (myKeypressedButton != null) return ActionButtonComponent.NORMAL;
if (mySelectedColumn == myColumnIdx &&
mySelectedRow == myRowIdx &&
mySelectedGroup == myGroupIdx) {
return ActionButtonComponent.POPPED;
}
return ActionButtonComponent.NORMAL;
}
private void setupListeners(final JPanel panel) {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
myKeypressedButton = MyActionButton.this;
panel.repaint();
}
public void mouseReleased(MouseEvent e) {
if (myKeypressedButton == MyActionButton.this) {
myKeypressedButton = null;
onPress(e);
}
else {
myKeypressedButton = null;
}
panel.repaint();
}
public void mouseExited(MouseEvent e) {
mySelectedColumn = -1;
mySelectedRow = -1;
mySelectedGroup = -1;
panel.repaint();
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
mySelectedColumn = myColumnIdx;
mySelectedRow = myRowIdx;
mySelectedGroup = myGroupIdx;
panel.repaint();
}
});
}
protected abstract void onPress(InputEvent e);
}
private abstract class ButtonWithExtension extends MyActionButton {
private ButtonWithExtension(Icon icon, String displayName) {
super(icon, displayName);
}
protected void onPress(InputEvent e) {
onPress(e, this);
}
protected abstract void onPress(InputEvent e, MyActionButton button);
}
private abstract class PluginsActionButton extends MyActionButton {
protected PluginsActionButton(Icon icon, String displayName) {
super(icon, displayName);
}
public Dimension getMaximumSize() {
return LEARN_MORE_SIZE;
}
public Dimension getMinimumSize() {
return LEARN_MORE_SIZE;
}
public Dimension getPreferredSize() {
return LEARN_MORE_SIZE;
}
@Override protected Color getNormalButtonColor() {
return LEARN_MORE_BUTTON_COLOR;
}
protected void paintBorder(Graphics g) {
Rectangle rectangle = new Rectangle(getSize());
Color color = WHITE_BORDER_COLOR;
g.setColor(color);
g.drawLine(rectangle.x, rectangle.y, rectangle.x, (rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x, rectangle.y, (rectangle.x + rectangle.width) - 1, rectangle.y);
color = GRAY_BORDER_COLOR;
g.setColor(color);
g.drawLine((rectangle.x + rectangle.width) - 1, rectangle.y + 1, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
g.drawLine(rectangle.x + 1, (rectangle.y + rectangle.height) - 1, (rectangle.x + rectangle.width) - 1,
(rectangle.y + rectangle.height) - 1);
}
}
} |
package hudson.util;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import hudson.Util;
import static org.hamcrest.Matchers.is;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.rules.ErrorCollector;
import org.jvnet.hudson.test.Issue;
/**
* Test for {@link Util#isOverridden} method.
*/
public class IsOverriddenTest {
@Rule
public ErrorCollector errors = new ErrorCollector();
/**
* Test that a method is found by isOverridden even when it is inherited from an intermediate class.
*/
@Test
public void isOverriddenTest() {
assertTrue(Util.isOverridden(Base.class, Derived.class, "method"));
assertTrue(Util.isOverridden(Base.class, Intermediate.class, "method"));
assertFalse(Util.isOverridden(Base.class, Base.class, "method"));
assertTrue(Util.isOverridden(Base.class, Intermediate.class, "setX", Object.class));
assertTrue(Util.isOverridden(Base.class, Intermediate.class, "getX"));
}
/**
* Negative test.
* Trying to check for a method which does not exist in the hierarchy,
*/
@Test(expected = IllegalArgumentException.class)
public void isOverriddenNegativeTest() {
Util.isOverridden(Base.class, Derived.class, "method2");
}
/**
* Do not inspect private methods.
*/
@Test(expected = IllegalArgumentException.class)
public void avoidPrivateMethodsInspection() {
Util.isOverridden(Base.class, Intermediate.class, "aPrivateMethod");
}
public static abstract class Base<T> {
protected abstract void method();
private void aPrivateMethod() {}
public void setX(T t) {}
public T getX() { return null; }
}
public abstract class Intermediate extends Base<Integer> {
protected void method() {}
private void aPrivateMethod() {}
public void setX(Integer i) {}
public Integer getX() { return 0; }
}
public class Derived extends Intermediate {}
@Ignore("TODO fails as predicted")
@Issue("JENKINS-62723")
@Test
public void finalOverrides() {
errors.checkThat("X1 overrides X.m1", Util.isOverridden(X.class, X1.class, "m1"), is(true));
errors.checkThat("X1 does not override X.m2", Util.isOverridden(X.class, X1.class, "m2"), is(false));
errors.checkThat("X2 overrides X.m1", Util.isOverridden(X.class, X2.class, "m1"), is(true));
errors.checkThat("X2 does not override X.m2", Util.isOverridden(X.class, X2.class, "m2"), is(false));
errors.checkThat("X3 overrides X.m1", Util.isOverridden(X.class, X3.class, "m1"), is(true));
errors.checkThat("X3 overrides X.m2", Util.isOverridden(X.class, X3.class, "m2"), is(true));
errors.checkThat("X4 overrides X.m1", Util.isOverridden(X.class, X4.class, "m1"), is(true));
errors.checkThat("X4 overrides X.m2", Util.isOverridden(X.class, X4.class, "m2"), is(true));
}
public static interface X {
void m1();
default void m2() {}
}
public static class X1 implements X {
public void m1() {}
}
public static class X2 implements X {
public final void m1() {}
}
public static class X3 implements X {
public void m1() {}
@Override
public void m2() {}
}
public static class X4 implements X {
public void m1() {}
@Override
public final void m2() {}
}
} |
package app.android.simpleflashcards.ui;
import java.util.HashMap;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import app.android.simpleflashcards.R;
import app.android.simpleflashcards.SimpleFlashcardsApplication;
import app.android.simpleflashcards.models.Deck;
import app.android.simpleflashcards.models.Decks;
import app.android.simpleflashcards.models.ModelsException;
public class FlashcardsDecksListActivity extends SimpleAdapterListActivity
{
private final Context activityContext = this;
private static final String LIST_ITEM_TEXT_ID = "text";
private static final String LIST_ITEM_OBJECT_ID = "object";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flashcards_decks);
initializeActionbar();
initializeList();
}
@Override
protected void onResume() {
super.onResume();
new LoadDecksTask().execute();
}
private void initializeActionbar() {
ImageButton updateButton = (ImageButton) findViewById(R.id.updateButton);
updateButton.setOnClickListener(updateListener);
ImageButton newItemCreationButton = (ImageButton) findViewById(R.id.itemCreationButton);
newItemCreationButton.setOnClickListener(deckCreationListener);
}
private OnClickListener updateListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO: Call update task
}
};
private OnClickListener deckCreationListener = new OnClickListener() {
@Override
public void onClick(View v) {
ActivityStarter.start(activityContext, FlashcardsDeckCreationActivity.class);
}
};
@Override
protected void initializeList() {
SimpleAdapter decksAdapter = new SimpleAdapter(activityContext, listData,
R.layout.flashcards_decks_list_item, new String[] { LIST_ITEM_TEXT_ID },
new int[] { R.id.text });
setListAdapter(decksAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
registerForContextMenu(getListView());
}
private class LoadDecksTask extends AsyncTask<Void, Void, String>
{
private Decks decks = null;
@Override
protected void onPreExecute() {
setEmptyListText(getString(R.string.loadingFlashcardsDecks));
listData.clear();
}
@Override
protected String doInBackground(Void... params) {
try {
decks = SimpleFlashcardsApplication.getInstance().getDecks();
addItemsToList(decks.getDecksList());
}
catch (ModelsException e) {
return getString(R.string.someError);
}
return new String();
}
@Override
protected void onPostExecute(String result) {
if (listData.isEmpty()) {
setEmptyListText(getString(R.string.noFlashcardsDecks));
} else {
updateList();
}
if (!result.isEmpty()) {
UserAlerter.alert(activityContext, result);
}
}
}
@Override
protected void addItemToList(Object itemData) {
Deck deck = (Deck) itemData;
HashMap<String, Object> deckItem = new HashMap<String, Object>();
deckItem.put(LIST_ITEM_TEXT_ID, deck.getTitle());
deckItem.put(LIST_ITEM_OBJECT_ID, deck);
listData.add(deckItem);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.flashcards_decks_context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo itemInfo = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.editItem:
// TODO: Call edit
return true;
case R.id.editItemContents:
// TODO: Call edit contents
return true;
case R.id.delete:
new DeleteDeckTask(itemInfo.position).execute();
return true;
default:
return super.onContextItemSelected(item);
}
}
private class DeleteDeckTask extends AsyncTask<Void, Void, String>
{
private ProgressDialogShowHelper progressDialogHelper;
private int deckAdapterPosition;
public DeleteDeckTask(int deckAdapterPosition) {
super();
this.deckAdapterPosition = deckAdapterPosition;
}
@Override
protected void onPreExecute() {
progressDialogHelper = new ProgressDialogShowHelper();
progressDialogHelper.show(activityContext, getString(R.string.deletingFlashcardsDeck));
}
@Override
protected String doInBackground(Void... params) {
Deck deck = getDeck(deckAdapterPosition);
try {
SimpleFlashcardsApplication.getInstance().getDecks().deleteDeck(deck);
}
catch (ModelsException e) {
return getString(R.string.someError);
}
listData.remove(deckAdapterPosition);
return new String();
}
@Override
protected void onPostExecute(String result) {
updateList();
if (listData.isEmpty()) {
setEmptyListText(getString(R.string.noFlashcardsDecks));
}
progressDialogHelper.hide();
if (!result.isEmpty()) {
UserAlerter.alert(activityContext, result);
}
}
}
private Deck getDeck(int adapterPosition) {
SimpleAdapter listAdapter = (SimpleAdapter) getListAdapter();
HashMap<String, Object> adapterItem = (HashMap<String, Object>) listAdapter
.getItem(adapterPosition);
return (Deck) adapterItem.get(LIST_ITEM_OBJECT_ID);
}
} |
package mousio.client.retry;
import mousio.client.ConnectionState;
/**
* Retries with an exponential backoff
*/
public class RetryWithExponentialBackOff extends RetryPolicy {
private final int maxRetryCount;
private final int maxDelay;
/**
* Constructor
*
* @param startMsBeforeRetry milliseconds before retrying base time
*/
public RetryWithExponentialBackOff(int startMsBeforeRetry) {
this(startMsBeforeRetry, -1, -1);
}
/**
* Constructor
*
* @param startMsBeforeRetry milliseconds before retrying base time
* @param maxRetryCount max retry count
* @param maxDelay max delay between retries
*/
public RetryWithExponentialBackOff(int startMsBeforeRetry, int maxRetryCount, int maxDelay) {
super(startMsBeforeRetry);
this.maxRetryCount = maxRetryCount;
this.maxDelay = maxDelay;
}
@Override public boolean shouldRetry(ConnectionState state) {
if (this.maxRetryCount != -1 && state.retryCount >= this.maxRetryCount) {
return false;
}
if (state.msBeforeRetry == 0) {
state.msBeforeRetry = this.startRetryTime;
} else if (maxDelay == -1) {
state.msBeforeRetry *= 2;
} else if (state.msBeforeRetry < maxDelay) {
state.msBeforeRetry *= 2;
if (state.msBeforeRetry > maxDelay) {
state.msBeforeRetry = maxDelay;
}
} else {
return false;
}
return true;
}
} |
package com.monits.agilefant.fragment.iteration;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import roboguice.fragment.RoboFragment;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.inject.Inject;
import com.monits.agilefant.R;
import com.monits.agilefant.dialog.DateTimePickerDialogFragment;
import com.monits.agilefant.dialog.DateTimePickerDialogFragment.OnDateSetListener;
import com.monits.agilefant.model.StateKey;
import com.monits.agilefant.model.Task;
import com.monits.agilefant.service.MetricsService;
import com.monits.agilefant.service.UserService;
import com.monits.agilefant.util.DateUtils;
import com.monits.agilefant.util.HoursUtils;
import com.monits.agilefant.util.InputUtils;
import com.monits.agilefant.util.ValidationUtils;
public class SpentEffortFragment extends RoboFragment {
private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm";
private static final String TASK = "task";
private static final String MINUTES_SPENT = "minutes_spent";
@Inject
private MetricsService metricsService;
@Inject
private UserService userService;
private TextView mDateInput;
private Button mSubmitButton;
private EditText mResponsiblesInput;
private EditText mHoursInput;
private EditText mCommentInput;
private ImageButton mTriggerPickerButton;
private EditText mEffortLeftInput;
private SimpleDateFormat dateFormatter;
private Task task;
private long minutesSpent = -1;
private Listener<String> spentRequestSuccessCallback;
private ErrorListener spentRequestFailedCallback;
public static SpentEffortFragment newInstance(final Task task) {
final Bundle arguments = new Bundle();
arguments.putSerializable(TASK, task);
final SpentEffortFragment fragment = new SpentEffortFragment();
fragment.setArguments(arguments);
return fragment;
}
public static SpentEffortFragment newInstance(final Task task, final long minutes) {
final Bundle arguments = new Bundle();
arguments.putSerializable(TASK, task);
arguments.putLong(MINUTES_SPENT, minutes);
final SpentEffortFragment fragment = new SpentEffortFragment();
fragment.setArguments(arguments);
return fragment;
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle arguments = getArguments();
task = (Task) arguments.getSerializable(TASK);
minutesSpent = arguments.getLong(MINUTES_SPENT);
dateFormatter = new SimpleDateFormat(DATE_PATTERN, Locale.US);
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_spent_effort, null);
final Date time = Calendar.getInstance().getTime();
final String formattedDate = dateFormatter.format(time);
mDateInput = (TextView) view.findViewById(R.id.date);
mDateInput.setText(formattedDate);
mResponsiblesInput = (EditText) view.findViewById(R.id.responsibles);
mResponsiblesInput.setText(userService.getLoggedUser().getInitials());
mHoursInput = (EditText) view.findViewById(R.id.effort_spent);
mEffortLeftInput = (EditText) view.findViewById(R.id.effort_left);
mEffortLeftInput.setText(String.valueOf((float) task.getEffortLeft() / 60));
if (minutesSpent != -1) {
final float difference = (task.getEffortLeft() - minutesSpent) / 60.0f;
mHoursInput.setText(
HoursUtils.convertMinutesToHours(minutesSpent));
mEffortLeftInput.setText(
String.valueOf(difference < 0 ? 0 : difference));
}
mCommentInput = (EditText) view.findViewById(R.id.comment);
mTriggerPickerButton = (ImageButton) view.findViewById(R.id.datepicker_button);
mTriggerPickerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
final DateTimePickerDialogFragment dateTimePickerDialogFragment = DateTimePickerDialogFragment.newInstance();
dateTimePickerDialogFragment.setOnDateSetListener(new OnDateSetListener() {
@Override
public void onDateSet(final Date date) {
final String formattedDate = DateUtils.formatDate(date, DATE_PATTERN);
mDateInput.setText(formattedDate);
}
});
dateTimePickerDialogFragment.show(SpentEffortFragment.this.getFragmentManager(), "datePickerDialog");
}
});
mSubmitButton = (Button) view.findViewById(R.id.submit_btn);
mSubmitButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
final Context context = SpentEffortFragment.this.getActivity();
final StateKey taskState = task.getState();
if (Float.valueOf(mEffortLeftInput.getText().toString()) == 0
&& taskState != StateKey.IMPLEMENTED
&& taskState != StateKey.DONE) {
final AlertDialog.Builder builder = new Builder(context);
builder.setNegativeButton(R.string.dialog_update_task_state_negative, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
saveEffortLeft();
metricsService.taskChangeState(
StateKey.IMPLEMENTED,
task,
new Listener<Task>() {
@Override
public void onResponse(final Task arg0) {
Toast.makeText(context, R.string.feedback_successfully_updated_state, Toast.LENGTH_SHORT).show();
}
},
new ErrorListener() {
@Override
public void onErrorResponse(
final VolleyError arg0) {
Toast.makeText(context, R.string.feedback_failed_update_state, Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
}
});
builder.setMessage(R.string.dialog_update_task_state);
builder.show();
} else {
saveEffortLeft();
}
}
});
return view;
}
private void saveEffortLeft() {
final Context context = SpentEffortFragment.this.getActivity();
if (isValid()) {
final long minutes = HoursUtils.convertHoursStringToMinutes(mHoursInput.getText().toString().trim());
metricsService.taskChangeSpentEffort(
DateUtils.parseDate(mDateInput.getText().toString().trim(), DATE_PATTERN),
minutes,
mCommentInput.getText().toString(),
task,
userService.getLoggedUser().getId(),
new Listener<String>() {
@Override
public void onResponse(final String arg0) {
Toast.makeText(context, R.string.feedback_succesfully_updated_spent_effort, Toast.LENGTH_SHORT).show();
getFragmentManager().popBackStack();
if (spentRequestSuccessCallback != null) {
spentRequestSuccessCallback.onResponse(arg0);
}
}
},
new ErrorListener() {
@Override
public void onErrorResponse(final VolleyError arg0) {
Toast.makeText(context, R.string.feedback_failed_update_spent_effort, Toast.LENGTH_SHORT).show();
if (spentRequestFailedCallback != null) {
spentRequestFailedCallback.onErrorResponse(arg0);
}
}
});
metricsService.changeEffortLeft(
InputUtils.parseStringToDouble(mEffortLeftInput.getText().toString()),
task,
new Listener<Task>() {
@Override
public void onResponse(final Task arg0) {
Toast.makeText(context, R.string.feedback_succesfully_updated_effort_left, Toast.LENGTH_SHORT).show();
}
},
new ErrorListener() {
@Override
public void onErrorResponse(final VolleyError arg0) {
Toast.makeText(context, R.string.feedback_failed_update_effort_left, Toast.LENGTH_SHORT).show();
}
});
}
}
public void setEffortSpentCallbacks(final Listener<String> listener, final ErrorListener error) {
this.spentRequestSuccessCallback = listener;
this.spentRequestFailedCallback = error;
}
private boolean isValid() {
if (!ValidationUtils.validDate(DATE_PATTERN, mDateInput.getText().toString().trim())) {
Toast.makeText(getActivity(), R.string.error_validation_date, Toast.LENGTH_SHORT).show();
return false;
} else {
final String hoursInputValue = mHoursInput.getText().toString().trim();
if (hoursInputValue.equals("—")
|| hoursInputValue.equals("")
|| hoursInputValue.equals("0")) {
Toast.makeText(getActivity(), R.string.error_validate_effort_left, Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
} |
package me.nallar.patched.world.tracking;
import java.util.HashSet;
import java.util.concurrent.ConcurrentLinkedQueue;
import me.nallar.tickthreading.patcher.Declare;
import net.minecraft.server.management.PlayerInstance;
import net.minecraft.server.management.PlayerManager;
import net.minecraft.tileentity.TileEntity;
public abstract class PatchPlayerInstance extends PlayerInstance {
private ConcurrentLinkedQueue<TileEntity> tilesToUpdate;
private static java.lang.reflect.Method getChunkWatcherWithPlayers;
public PatchPlayerInstance(PlayerManager par1PlayerManager, int par2, int par3) {
super(par1PlayerManager, par2, par3);
}
public void construct() {
tilesToUpdate = new ConcurrentLinkedQueue<TileEntity>();
}
public void sendTiles() {
HashSet<TileEntity> tileEntities = new HashSet<TileEntity>();
for (TileEntity tileEntity = tilesToUpdate.poll(); tileEntity != null; tileEntity = tilesToUpdate.poll()) {
tileEntities.add(tileEntity);
}
for (TileEntity tileEntity : tileEntities) {
this.sendTileToAllPlayersWatchingChunk(tileEntity);
}
tileEntities.clear();
}
@Override
@Declare
public void updateTile(TileEntity tileEntity) {
if (numberOfTilesToUpdate == 0) {
this.myManager.playerUpdateLock.lock();
try {
this.myManager.getChunkWatcherWithPlayers().add(this);
} finally {
this.myManager.playerUpdateLock.unlock();
}
numberOfTilesToUpdate++;
}
tilesToUpdate.add(tileEntity);
}
} |
package de.gurkenlabs.litiengine.configuration;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
@ConfigurationGroupInfo(prefix = "gfx_")
public class GraphicConfiguration extends ConfigurationGroup {
private boolean fullscreen;
private Quality graphicQuality;
private boolean renderDynamicShadows;
private int resolutionHeight;
private int resolutionWidth;
private boolean enableResolutionScale;
private boolean reduceFramesWhenNotFocused;
private boolean antiAliasing;
private boolean colorInterpolation;
/**
* Instantiates a new graphic configuration.
*/
public GraphicConfiguration() {
this.graphicQuality = Quality.LOW;
this.fullscreen = false;
this.renderDynamicShadows = false;
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
this.resolutionWidth = d.width;
this.resolutionHeight = d.height - 100;
this.setEnableResolutionScale(true);
this.setReduceFramesWhenNotFocused(true);
this.setAntiAliasing(false);
this.setColorInterpolation(false);
}
/**
* Gets the graphic quality.
*
* @return the graphic quality
*/
public Quality getGraphicQuality() {
return this.graphicQuality;
}
/**
* Gets the resolution.
*
* @return the resolution
*/
public Dimension getResolution() {
if (this.isFullscreen()) {
final GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
final int width = gd.getDisplayMode().getWidth();
final int height = gd.getDisplayMode().getHeight();
return new Dimension(width, height);
}
return new Dimension(this.resolutionWidth, this.resolutionHeight);
}
public int getResolutionHeight() {
return this.resolutionHeight;
}
public int getResolutionWidth() {
return this.resolutionWidth;
}
/**
* Checks if is fullscreen.
*
* @return true, if is fullscreen
*/
public boolean isFullscreen() {
return this.fullscreen;
}
public boolean renderDynamicShadows() {
return this.renderDynamicShadows;
}
public boolean antiAlising() {
return this.antiAliasing;
}
public boolean colorInterpolation() {
return this.colorInterpolation;
}
/**
* Sets the fullscreen.
*
* @param fullscreen
* the new fullscreen
*/
public void setFullscreen(final boolean fullscreen) {
if (fullscreen == this.fullscreen) {
return;
}
this.fullscreen = fullscreen;
}
/**
* Sets the graphic quality.
*
* @param graphicQuality
* the new graphic quality
*/
public void setGraphicQuality(final Quality graphicQuality) {
this.graphicQuality = graphicQuality;
}
public void setRenderDynamicShadows(final boolean renderDynamicShadows) {
this.renderDynamicShadows = renderDynamicShadows;
}
public void setResolutionHeight(final int resolutionHeight) {
this.resolutionHeight = resolutionHeight;
}
public void setResolutionWidth(final int resolutionWidth) {
this.resolutionWidth = resolutionWidth;
}
public boolean enableResolutionScaling() {
return this.enableResolutionScale;
}
public void setEnableResolutionScale(boolean enableResolutionScale) {
this.enableResolutionScale = enableResolutionScale;
}
public boolean reduceFramesWhenNotFocused() {
return this.reduceFramesWhenNotFocused;
}
public void setReduceFramesWhenNotFocused(boolean reduceFramesWhenNotFocused) {
this.reduceFramesWhenNotFocused = reduceFramesWhenNotFocused;
}
public void setAntiAliasing(boolean antiAliasing) {
this.antiAliasing = antiAliasing;
}
public void setColorInterpolation(boolean colorInterpolation) {
this.colorInterpolation = colorInterpolation;
}
} |
package de.lmu.ifi.dbs.data.synthetic;
import de.lmu.ifi.dbs.data.DoubleVector;
import de.lmu.ifi.dbs.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.math.linearalgebra.LinearEquationSystem;
import de.lmu.ifi.dbs.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.utilities.Util;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.Parameter;
import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Provides automatic generation of arbitrary oriented hyperplanes of arbitrary correlation dimensionalities.
* <p/>
*
* @author Elke Achtert (<a href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>)
*/
public class ArbitraryCorrelationGenerator extends AxesParallelCorrelationGenerator {
/**
* Parameter for model point.
*/
public static final String POINT_P = "point";
/**
* Description for parameter point.
*/
public static final String POINT_D = "<p_1,...,p_d>a comma separated list of the coordinates of the model point, " +
"default is the centroid of the defined feature space.";
/**
* Parameter for basis.
*/
public static final String BASIS_P = "basis";
/**
* Description for parameter basis.
*/
public static final String BASIS_D = "<b_11,...,b_1d:...:b_c1,...,b_cd>a list of basis vectors of the correlation hyperplane, " +
"where c denotes the correlation dimensionality and d the dimensionality of the " +
"feature space. Each basis vector is separated by :, the coordinates within " +
"the basis vectors are separated by a comma. If no basis is specified, the " +
"basis vectors are generated randomly.";
/**
* Number Formatter for output.
*/
private static final NumberFormat NF = NumberFormat.getInstance(Locale.US);
/**
* The model point.
*/
private Vector point;
/**
* The basis vectors.
*/
private Matrix basis;
/**
* The standard deviation for jitter.
*/
private double jitter_std;
/**
* Creates a new arbitrary correlation generator that provides automatic generation
* of arbitrary oriented hyperplanes of arbitrary correlation dimensionalities.
*/
public ArbitraryCorrelationGenerator() {
super();
optionHandler.put(POINT_P, new Parameter(POINT_P, POINT_D));
optionHandler.put(BASIS_P, new Parameter(BASIS_P, BASIS_D));
}
/**
* Main method to run this wrapper.
*
* @param args the arguments to run this wrapper
*/
public static void main(String[] args) {
LoggingConfiguration.configureRoot(LoggingConfiguration.CLI);
ArbitraryCorrelationGenerator wrapper = new ArbitraryCorrelationGenerator();
try {
wrapper.setParameters(args);
wrapper.run();
}
catch (ParameterException e) {
Throwable cause = e.getCause() != null ? e.getCause() : e;
wrapper.exception(wrapper.optionHandler.usage(e.getMessage()), cause);
}
catch (Exception e) {
wrapper.exception(wrapper.optionHandler.usage(e.getMessage()), e);
e.printStackTrace();
}
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
// model point
if (optionHandler.isSet(POINT_P)) {
String pointString = optionHandler.getOptionValue(POINT_P);
String[] pointCoordinates = COMMA_SPLIT.split(pointString);
if (pointCoordinates.length != dataDim)
throw new WrongParameterValueException("Value of parameter " + POINT_P + " has not the specified dimensionality " + DIM_P + " = " + dataDim);
double[] p = new double[dataDim];
for (int i = 0; i < dataDim; i++) {
try {
p[i] = Double.parseDouble(pointCoordinates[i]);
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(POINT_P, pointString, POINT_D);
}
}
point = new Vector(p);
}
else {
point = centroid(dataDim);
}
// basis
if (optionHandler.isSet(BASIS_P)) {
String basisString = optionHandler.getOptionValue(BASIS_P);
String[] basisVectors = VECTOR_SPLIT.split(basisString);
if (basisVectors.length != corrDim) {
throw new WrongParameterValueException("Value of parameter " + BASIS_P + " has not the specified dimensionality " +
CORRDIM_P + " = " + corrDim);
}
double[][] b = new double[dataDim][corrDim];
for (int c = 0; c < corrDim; c++) {
String[] basisCoordinates = COMMA_SPLIT.split(basisVectors[c]);
if (basisCoordinates.length != dataDim)
throw new WrongParameterValueException("Value of parameter " + BASIS_P + " has not the specified dimensionality " + DIM_P + " = " + dataDim);
for (int d = 0; d < dataDim; d++) {
try {
b[d][c] = Double.parseDouble(basisCoordinates[d]);
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(BASIS_P, basisString, BASIS_D);
}
}
}
basis = new Matrix(b);
}
else {
basis = correlationBasis(dataDim, corrDim);
}
// jitter std
jitter_std = 0;
for (int d = 0; d < dataDim; d++) {
jitter_std = Math.max(jitter * (max[d] - min[d]), jitter_std);
}
return remainingParameters;
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#getAttributeSettings()
*/
public List<AttributeSettings> getAttributeSettings() {
List<AttributeSettings> settings = super.getAttributeSettings();
AttributeSettings mySettings = settings.get(0);
mySettings.addSetting(POINT_P, Util.format(point.getArray()[0]));
mySettings.addSetting(BASIS_P, Util.format(basis.getArray(), ":", ",", 2));
return settings;
}
/**
* Generates a correlation hyperplane and writes
* it to the specified according output stream writer.
*
* @param outStream the output stream to write into
*/
void generateCorrelation(OutputStreamWriter outStream) throws IOException {
if (this.debug) {
StringBuffer msg = new StringBuffer();
msg.append("\nbasis");
msg.append(basis.toString(NF));
msg.append("\npoint");
msg.append(point.toString(NF));
debugFine(msg.toString());
}
if (point.getRowDimension() != basis.getRowDimension())
throw new IllegalArgumentException("point.getRowDimension() != basis.getRowDimension()!");
if (point.getColumnDimension() != 1)
throw new IllegalArgumentException("point.getColumnDimension() != 1!");
if (! inMinMax(point))
throw new IllegalArgumentException("point not in min max!");
if (basis.getColumnDimension() == basis.getRowDimension()) {
generateNoise(outStream);
return;
}
// determine the dependency
Dependency dependency = determineDependency();
if (isVerbose()) {
StringBuffer msg = new StringBuffer();
msg.append(dependency.toString());
verbose(msg.toString());
}
Matrix b = dependency.basisVectors;
List<DoubleVector> featureVectors = new ArrayList<DoubleVector>(number);
while (featureVectors.size() != number) {
Vector featureVector = generateFeatureVector(point, b);
double distance = distance(featureVector, point, b);
if (distance > 1E-13 && isVerbose())
verbose("distance " + distance);
if (jitter != 0) {
featureVector = jitter(featureVector, dependency.normalVectors);
}
if (inMinMax(featureVector)) {
featureVectors.add(new DoubleVector(featureVector));
}
}
double std = standardDeviation(featureVectors, point, b);
if (isVerbose()) {
verbose("standard deviation " + std);
}
output(outStream, featureVectors, dependency.dependency, std);
}
/**
* Determines the linear equation system describing the dependencies
* of the correlation hyperplane depicted by the model point and the basis.
*
* @return the dependencies
*/
private Dependency determineDependency() {
StringBuffer msg = new StringBuffer();
// orthonormal basis of subvectorspace U
Matrix orthonormalBasis_U = orthonormalize(basis);
Matrix completeVectors = completeBasis(orthonormalBasis_U);
if (this.debug) {
msg.append("\npoint ").append(point.toString(NF));
msg.append("\nbasis ").append(basis.toString(NF));
msg.append("\northonormal basis ").append(orthonormalBasis_U.toString(NF));
msg.append("\ncomplete vectors ").append(completeVectors.toString(NF));
debugFine(msg.toString());
}
// orthonormal basis of vectorspace V
Matrix basis_V = appendColumns(orthonormalBasis_U, completeVectors);
basis_V = orthonormalize(basis_V);
if (this.debug) {
debugFine("basis V " + basis_V.toString(NF));
}
// normal vectors of U
Matrix normalVectors_U = basis_V.getMatrix(0, basis_V.getRowDimension() - 1,
basis.getColumnDimension(),
basis.getRowDimension() - basis.getColumnDimension() + basis.getColumnDimension() - 1);
if (this.debug) {
debugFine("normal vector U " + normalVectors_U.toString(NF));
}
Matrix transposedNormalVectors = normalVectors_U.transpose();
if (this.debug) {
debugFine("tNV " + transposedNormalVectors.toString(NF));
debugFine("point " + point.toString(NF));
}
// gauss jordan
Matrix B = transposedNormalVectors.times(point);
if (this.debug) {
debugFine("B " + B.toString(NF));
}
Matrix gaussJordan = new Matrix(transposedNormalVectors.getRowDimension(), transposedNormalVectors.getColumnDimension() + B.getColumnDimension());
gaussJordan.setMatrix(0, transposedNormalVectors.getRowDimension() - 1, 0, transposedNormalVectors.getColumnDimension() - 1, transposedNormalVectors);
gaussJordan.setMatrix(0, gaussJordan.getRowDimension() - 1, transposedNormalVectors.getColumnDimension(), gaussJordan.getColumnDimension() - 1, B);
double[][] a = new double[transposedNormalVectors.getRowDimension()][transposedNormalVectors.getColumnDimension()];
double[][] we = transposedNormalVectors.getArray();
double[] b = B.getColumn(0).getRowPackedCopy();
System.arraycopy(we, 0, a, 0, transposedNormalVectors.getRowDimension());
LinearEquationSystem lq = new LinearEquationSystem(a, b);
lq.solveByTotalPivotSearch();
Dependency dependency = new Dependency(orthonormalBasis_U, normalVectors_U, lq);
return dependency;
}
/**
* Generates a vector lying on the hyperplane defined by the
* specified parameters.
*
* @param point the model point of the hyperplane
* @param basis the basis of the hyperplane
* @return a matrix consisting of the po
*/
private Vector generateFeatureVector(Vector point, Matrix basis) {
Vector featureVector = point.copy();
for (int i = 0; i < basis.getColumnDimension(); i++) {
double lambda_i = RANDOM.nextGaussian();
Vector b_i = basis.getColumnVector(i);
featureVector = featureVector.plus(b_i.times(lambda_i));
}
return featureVector;
}
/**
* Adds a jitter to each dimension of the specified feature vector.
*
* @param featureVector the feature vector
* @param normalVectors the normal vectors
* @return the new (jittered) feature vector
*/
private Vector jitter(Vector featureVector, Matrix normalVectors) {
for (int i = 0; i < normalVectors.getColumnDimension(); i++) {
Vector n_i = normalVectors.getColumnVector(i);
n_i.normalizeColumns();
double distance = RANDOM.nextGaussian() * jitter_std;
featureVector = n_i.times(distance).plus(featureVector);
}
return featureVector;
}
/**
* Returns true, if the specified feature vector is in
* the interval [min, max], false otherwise.
*
* @param featureVector the feature vector to be tested
* @return true, if the specified feature vector is in
* the interval [min, max], false otherwise
*/
private boolean inMinMax(Vector featureVector) {
for (int i = 0; i < featureVector.getRowDimension(); i++) {
for (int j = 0; j < featureVector.getColumnDimension(); j++) {
double value = featureVector.get(i, j);
if (value < min[i]) return false;
if (value > max[i]) return false;
}
}
return true;
}
/**
* Writes the specified list of feature vectors to the output.
*
* @param outStream the output stream to write into
* @param featureVectors the feature vectors to be written
* @param dependency the dependeny of the feature vectors
* @param std the standard deviation of the jitter of the feature vectors
* @throws IOException
*/
private void output(OutputStreamWriter outStream, List<DoubleVector> featureVectors, LinearEquationSystem dependency, double std) throws IOException {
outStream.write("
outStream.write("### " + MIN_P + " [" + Util.format(min, ",", NF) + "]" + LINE_SEPARATOR);
outStream.write("### " + MAX_P + " [" + Util.format(max, ",", NF) + "]" + LINE_SEPARATOR);
outStream.write("### " + NUMBER_P + " " + number + LINE_SEPARATOR);
outStream.write("### " + POINT_P + " [" + Util.format(point.getColumnPackedCopy(), NF) + "]" + LINE_SEPARATOR);
outStream.write("### " + BASIS_P + " ");
for (int i = 0; i < basis.getColumnDimension(); i++) {
outStream.write("[" + Util.format(basis.getColumn(i).getColumnPackedCopy(), NF) + "]");
if (i < basis.getColumnDimension() - 1) outStream.write(",");
}
outStream.write(LINE_SEPARATOR);
if (jitter != 0) {
outStream.write("### max jitter in each dimension " + Util.format(jitter, NF) + "%" + LINE_SEPARATOR);
outStream.write("### Randomized standard deviation " + Util.format(jitter_std, NF) + LINE_SEPARATOR);
outStream.write("### Real standard deviation " + Util.format(std, NF) + LINE_SEPARATOR);
outStream.write("###" + LINE_SEPARATOR);
}
if (dependency != null) {
outStream.write("### " + LINE_SEPARATOR);
outStream.write("### dependency ");
outStream.write(dependency.equationsToString("### ", NF.getMaximumFractionDigits()));
}
outStream.write("
for (DoubleVector featureVector : featureVectors) {
if (label == null)
outStream.write(featureVector + LINE_SEPARATOR);
else {
outStream.write(featureVector.toString());
outStream.write(" " + label + LINE_SEPARATOR);
}
}
}
/**
* Completes the specified d x c basis of a subspace of R^d to a
* d x d basis of R^d, i.e. appends c-d columns to the specified basis b.
*
* @param b the basis of the subspace of R^d
* @return a basis of R^d
*/
private Matrix completeBasis(Matrix b) {
StringBuffer msg = new StringBuffer();
Matrix e = Matrix.unitMatrix(b.getRowDimension());
Matrix basis = b.copy();
Matrix result = null;
for (int i = 0; i < e.getColumnDimension(); i++) {
Matrix e_i = e.getColumn(i);
boolean li = basis.linearlyIndependent(e_i);
if (this.debug) {
msg.append("\nbasis ").append(basis.toString(NF));
msg.append("\ne_i ").append(e_i.toString(NF));
msg.append("\nlinearlyIndependent ").append(li);
debugFine(msg.toString());
}
if (li) {
if (result == null) {
result = e_i.copy();
}
else {
result = appendColumns(result, e_i);
}
basis = appendColumns(basis, e_i);
}
}
return result;
}
/**
* Appends the specified columns to the given matrix.
*
* @param m the matrix
* @param columns the columns to be appended
* @return the new matrix with the appended columns
*/
private Matrix appendColumns(Matrix m, Matrix columns) {
if (m.getRowDimension() != columns.getRowDimension())
throw new IllegalArgumentException("m.getRowDimension() != column.getRowDimension()");
Matrix result = new Matrix(m.getRowDimension(), m.getColumnDimension() + columns.getColumnDimension());
for (int i = 0; i < result.getColumnDimension(); i++) {
if (i < m.getColumnDimension()) {
result.setColumn(i, m.getColumn(i));
}
else {
result.setColumn(i, columns.getColumn(i - m.getColumnDimension()));
}
}
return result;
}
/**
* Orthonormalizes the specified matrix.
*
* @param u the matrix to be orthonormalized
* @return the orthonormalized matrixr
*/
private Matrix orthonormalize(Matrix u) {
Matrix v = u.getColumn(0).copy();
for (int i = 1; i < u.getColumnDimension(); i++) {
Matrix u_i = u.getColumn(i);
Matrix sum = new Matrix(u.getRowDimension(), 1);
for (int j = 0; j < i; j++) {
Matrix v_j = v.getColumn(j);
double scalar = u_i.scalarProduct(0, v_j, 0) / v_j.scalarProduct(0, v_j, 0);
sum = sum.plus(v_j.times(scalar));
}
Matrix v_i = u_i.minus(sum);
v = appendColumns(v, v_i);
}
v.normalizeColumns();
return v;
}
/**
* Returns the standard devitaion of the distance of the feature vectors to the
* hyperplane defined by the specified point and basis.
*
* @param featureVectors the feature vectors
* @param point the model point of the hyperplane
* @param basis the basis of the hyperplane
* @return the standard devitaion of the distance
*/
private double standardDeviation(List<DoubleVector> featureVectors, Vector point, Matrix basis) {
double std_2 = 0;
for (DoubleVector doubleVector : featureVectors) {
double distance = distance(doubleVector.getColumnVector(), point, basis);
std_2 += distance * distance;
}
return Math.sqrt(std_2 / featureVectors.size());
}
/**
* Returns the distance of the specified feature vector to the
* hyperplane defined by the specified point and basis.
*
* @param featureVector the feature vector
* @param point the model point of the hyperplane
* @param basis the basis of the hyperplane
* @return the distance of the specified feature vector to the
* hyperplane
*/
private double distance(Vector featureVector, Vector point, Matrix basis) {
Matrix p_minus_a = featureVector.minus(point);
Matrix proj = p_minus_a.projection(basis);
return p_minus_a.minus(proj).euclideanNorm(0);
}
/**
* Generates noise and writes it to the specified outStream.
*
* @param outStream the output stream to write to
*/
private void generateNoise(OutputStreamWriter outStream) throws IOException {
List<DoubleVector> featureVectors = new ArrayList<DoubleVector>(number);
int dim = min.length;
for (int i = 0; i < number; i++) {
double[] values = new double[dim];
for (int d = 0; d < dim; d++) {
values[d] = RANDOM.nextDouble() * (max[d] - min[d]) + min[d];
}
featureVectors.add(new DoubleVector(values));
}
output(outStream, featureVectors, null, 0);
}
/**
* Returns the centroid of the feature space.
*
* @param dim the dimensionality of the feature space.
* @return the centroid of the feature space
*/
private Vector centroid(int dim) {
double[] p = new double[dim];
for (int i = 0; i < p.length; i++) {
p[i] = (max[i] - min[i]) / 2;
}
return new Vector(p);
}
/**
* Returns a basis for for a hyperplane of the specified correleation dimension
*
* @param dim the dimensionality of the feature space
* @param corrDim the correlation dimensionality
* @return a basis for a hyperplane of the specified correleation dimension
*/
private Matrix correlationBasis(int dim, int corrDim) {
double[][] b = new double[dim][corrDim];
for (int i = 0; i < b.length; i++) {
if (i < corrDim) {
b[i][i] = 1;
}
else {
for (int j = 0; j < corrDim; j++) {
b[i][j] = RANDOM.nextDouble() * (max[i] - min[i]) + min[i];
}
}
}
Matrix basis = new Matrix(b);
return basis;
}
/**
* Encapsulates dependencies.
*/
private static class Dependency {
/**
* The basis vectors.
*/
Matrix basisVectors;
/**
* The normal vectors.
*/
Matrix normalVectors;
/**
* The linear equation system.
*/
LinearEquationSystem dependency;
/**
* Provied a new dependency object.
*
* @param basisVectors the basis vectors
* @param normalvectors the normal vectors
* @param linearEquationSystem the linear equation system
*/
public Dependency(Matrix basisVectors, Matrix normalvectors, LinearEquationSystem linearEquationSystem) {
this.basisVectors = basisVectors;
this.normalVectors = normalvectors;
this.dependency = linearEquationSystem;
}
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
public String toString() {
return
// "basisVectors : " + basisVectors.toString(NF) +
// "normalVectors: " + normalVectors.toString(NF) +
"dependency: " + dependency.equationsToString(NF.getMaximumFractionDigits());
}
}
} |
package edu.mit.streamjit.impl.distributed.runtimer;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import edu.mit.streamjit.impl.distributed.StreamJitAppManager;
import edu.mit.streamjit.impl.distributed.common.AppStatus;
import edu.mit.streamjit.impl.distributed.common.AppStatus.AppStatusProcessor;
import edu.mit.streamjit.impl.distributed.common.Error;
import edu.mit.streamjit.impl.distributed.common.Error.ErrorProcessor;
import edu.mit.streamjit.impl.distributed.common.NodeInfo;
import edu.mit.streamjit.impl.distributed.common.NodeInfo.NodeInfoProcessor;
import edu.mit.streamjit.impl.distributed.common.Request;
import edu.mit.streamjit.impl.distributed.common.SNDrainElement;
import edu.mit.streamjit.impl.distributed.common.SNDrainElement.SNDrainProcessor;
import edu.mit.streamjit.impl.distributed.common.SNException;
import edu.mit.streamjit.impl.distributed.common.SNException.SNExceptionProcessor;
import edu.mit.streamjit.impl.distributed.common.SNMessageVisitor;
import edu.mit.streamjit.impl.distributed.common.SystemInfo;
import edu.mit.streamjit.impl.distributed.common.SystemInfo.SystemInfoProcessor;
import edu.mit.streamjit.impl.distributed.node.StreamNode;
/**
* StreamNodeAgent represents a {@link StreamNode} at {@link Controller} side.
* Controller will be having a StreamNodeAgent for each connected StreamNode.
* <p>
* IO connection is not part of the StreamNodeAgent and StreamNodeAgent is
* expected to be a passive object. This decision is made because single thread
* or a dispatcher thread pool is expected to be running for asynchronous IO or
* non blocking IO implementation of the {@link CommunicationManager}. It is
* {@link CommunicationManager}'s responsibility to run the IO connections of
* each {@link StreamNode} on appropriate thread. If it is blocking IO then each
* communication can be run on separate thread. Otherwise, single thread or a
* thread pool may handle all IO communications. IO threads will read the
* incoming messages and act accordingly. Controller thread also can send
* messages to {@link StreamNode}s in parallel.
* </p>
*/
public abstract class StreamNodeAgent {
/**
* {@link MessageVisitor} for this streamnode.
*/
private final SNMessageVisitor mv;
private final NodeInfoProcessor np;
private final SystemInfoProcessor sp;
// TODO: How to avoid volatile here. Because we set only once and read
// forever later. So if it is volatile, every read will need to access
// memory. Is there any way to avoid this?
// Will removing volatile modifier be OK in this context? consider
// using piggybacking sync or atomicreferenc with compareandset. This is
// actually effectively immutable/safe publication case. But how to
// implement it.
private volatile StreamJitAppManager manager;
/**
* Assigned nodeID of the corresponding {@link StreamNode}.
*/
private final int nodeID;
/**
* Recent {@link AppStatus} from the corresponding {@link StreamNode}.
*/
private volatile AppStatus appStatus;
/**
* {@link NodeInfo} of the {@link StreamNode} that is mapped to this
* {@link StreamNodeAgent}.
*/
private volatile NodeInfo nodeInfo;
/**
* Recent {@link SystemInfo} from the corresponding {@link StreamNode}.
*/
private volatile SystemInfo systemInfo;
/**
* Stop the communication with corresponding {@link StreamNode}.
* {@link Controller} is expected to set this flag and the IO thread
* response for that.
*/
private AtomicBoolean stopFlag;
public StreamNodeAgent(int nodeID) {
this.nodeID = nodeID;
stopFlag = new AtomicBoolean(false);
np = new NodeInfoProcessorImpl();
sp = new SystemInfoProcessorImpl();
mv = new SNMessageVisitorImpl();
}
/**
* @return the nodeID
*/
public int getNodeID() {
return nodeID;
}
/**
* @return the appStatus
*/
public AppStatus getAppStatus() {
return appStatus;
}
/**
* @param appStatus
* the appStatus to set
*/
public void setAppStatus(AppStatus appStatus) {
this.appStatus = appStatus;
}
/**
* @return the nodeInfo
*/
public NodeInfo getNodeInfo() {
if (nodeInfo == null) {
try {
writeObject(Request.NodeInfo);
} catch (IOException e) {
e.printStackTrace();
}
// TODO: If in any chance the IO thread call this function then
// it will get blocked on this loop forever. Need to handle
// this.
while (nodeInfo == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return nodeInfo;
}
/**
* @return the systemInfo
*/
public SystemInfo getSystemInfo() {
return systemInfo;
}
/**
* Stop the communication with corresponding {@link StreamNode}.
*/
public void stopRequest() {
this.stopFlag.set(true);
}
public boolean isStopRequested() {
return this.stopFlag.get();
}
/**
* @return Human readable name of the streamNode.
*/
public String streamNodeName() {
if (nodeInfo == null) {
getNodeInfo();
}
return nodeInfo.getHostName();
}
/**
* Send a object to corresponding {@link StreamNode}. While IO threads
* reading the incoming messages from the stream node, controller may send
* any messages through this function.
*
* @param obj
* @throws IOException
*/
public abstract void writeObject(Object obj) throws IOException;
/**
* Is still the connection with corresponding {@link StreamNode} is alive?
*
* @return
*/
public abstract boolean isConnected();
/**
* @return the mv
*/
public SNMessageVisitor getMv() {
return mv;
}
public void registerManager(StreamJitAppManager manager) {
assert this.manager == null : "StreamJitAppManager has already been set";
this.manager = manager;
}
private class SystemInfoProcessorImpl implements SystemInfoProcessor {
@Override
public void process(SystemInfo systemInfo) {
StreamNodeAgent.this.systemInfo = systemInfo;
}
}
/**
* {@link NodeInfoProcessor} at {@link StreamNode} side.
*
* @author Sumanan sumanan@mit.edu
* @since Aug 11, 2013
*/
private class NodeInfoProcessorImpl implements NodeInfoProcessor {
@Override
public void process(NodeInfo nodeInf) {
nodeInfo = nodeInf;
}
}
/**
* @author Sumanan sumanan@mit.edu
* @since May 20, 2013
*/
private class SNMessageVisitorImpl implements SNMessageVisitor {
@Override
public void visit(Error error) {
assert manager != null : "StreamJitAppManager has not been set";
ErrorProcessor ep = manager.errorProcessor();
error.process(ep);
}
@Override
public void visit(SystemInfo systemInfo) {
sp.process(systemInfo);
}
@Override
public void visit(AppStatus appStatus) {
assert manager != null : "StreamJitAppManager has not been set";
AppStatusProcessor ap = manager.appStatusProcessor();
if (ap == null) {
System.err.println("No AppStatusProcessor processor.");
return;
}
appStatus.process(ap);
}
@Override
public void visit(NodeInfo nodeInfo) {
np.process(nodeInfo);
}
@Override
public void visit(SNDrainElement snDrainElement) {
assert manager != null : "StreamJitAppManager has not been set";
SNDrainProcessor dp = manager.drainProcessor();
if (dp == null) {
System.err.println("No drainer processor.");
return;
}
snDrainElement.process(dp);
}
@Override
public void visit(SNException snException) {
assert manager != null : "StreamJitAppManager has not been set";
SNExceptionProcessor snExP = manager.exceptionProcessor();
snException.process(snExP);
}
}
} |
package me.gregorias.dfuntest.example;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import me.gregorias.dfuntest.ApplicationFactory;
import me.gregorias.dfuntest.Environment;
import me.gregorias.dfuntest.EnvironmentFactory;
import me.gregorias.dfuntest.EnvironmentPreparator;
import me.gregorias.dfuntest.LocalEnvironmentFactory;
import me.gregorias.dfuntest.MultiTestRunner;
import me.gregorias.dfuntest.SSHEnvironmentFactory;
import me.gregorias.dfuntest.TestResult;
import me.gregorias.dfuntest.TestRunner;
import me.gregorias.dfuntest.TestScript;
import me.gregorias.dfuntest.testrunnerbuilders.GuiceTestRunnerModule;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* <p>
* Main class for running dfuntest for PingApplication. It uses Guice and automatic configuration
* parsing to smooth out dependency injection.
* </p>
*
* <p>
* It expects user to specify which environment type to use and hierarchical specification of
* parameters. Names of paramaters directly correspond to Guice's Named tag value.
* </p>
*
* <p>
* This class provides default values for most paramaters, but they are overridden by config file
* specification on conflict. Config file values are overriden by command line arguments on
* conflict.
* </p>
*
* <p>
* Example usage:
*
* {@code ExampleGuiceMain --env-factory local --config-file resource/config/exampledfuntest.xml
* --config LocalEnvironmentFactory.environmentCount=10}
* </p>
*
* <p>
* For help:
*
* {@code ExampleGuiceMain --help}
* </p>
*
* <p>
* This Main assumes that in current working directory there is dfuntest-example.jar with
* dfuntest.example package and lib directory with all necessary dependencies.
* </p>
*
* <p>
* Run "./gradlew cERD" to ensure all dependencies are in place.
* </p>
*/
public class ExampleGuiceMain {
private static final Logger LOGGER = LoggerFactory.getLogger(ExampleGuiceMain.class);
private static final String CONFIG_OPTION = "config";
private static final String CONFIG_FILE_OPTION = "config-file";
private static final String ENV_FACTORY_OPTION = "env-factory";
private static final String HELP_OPTION = "help";
private static final String REPORT_PATH_PREFIX = "report_";
private static final String ENV_DIR_PREFIX = "Example";
private static final Map<String, String> DEFAULT_PROPERTIES = newDefaultProperties();
private static Class<? extends EnvironmentFactory<Environment>> mEnvironmentFactoryClass;
public static void main(String[] args) {
mEnvironmentFactoryClass = null;
Map<String, String> properties = new HashMap<>(DEFAULT_PROPERTIES);
Map<String, String> argumentProperties;
try {
argumentProperties = parseAndProcessArguments(args);
} catch (ConfigurationException | IllegalArgumentException | ParseException e) {
System.exit(1);
return;
}
if (argumentProperties == null) {
return;
}
properties.putAll(argumentProperties);
if (mEnvironmentFactoryClass == null) {
LOGGER.error("main(): EnvironmentFactory has not been set.");
System.exit(1);
return;
}
GuiceTestRunnerModule guiceBaseModule = new GuiceTestRunnerModule();
guiceBaseModule.addProperties(properties);
ExampleGuiceModule guiceExampleModule = new ExampleGuiceModule();
Injector injector = Guice.createInjector(guiceBaseModule, guiceExampleModule);
TestRunner testRunner = injector.getInstance(TestRunner.class);
TestResult result = testRunner.run();
int status;
String resultStr;
if (result.getType() == TestResult.Type.SUCCESS) {
status = 0;
resultStr = "successfully";
} else {
status = 1;
resultStr = "with failure";
}
LOGGER.info("main(): Test has ended {} with description: {}", resultStr,
result.getDescription());
System.exit(status);
}
private static class ExampleGuiceModule extends AbstractModule {
@Override
protected void configure() {
bind(new AppFactoryTypeLiteral()).to(ExampleAppFactory.class).in(Singleton.class);
bind(new EnvironmentPreparatorTypeLiteral()).to(ExampleEnvironmentPreparator.class)
.in(Singleton.class);
bind(new EnvironmentFactoryTypeLiteral()).to(mEnvironmentFactoryClass).in(Singleton.class);
Multibinder<TestScript<ExampleApp>> multiBinder = Multibinder.newSetBinder(binder(),
new TestScriptTypeLiteral(), Names.named(MultiTestRunner.SCRIPTS_ARGUMENT_NAME));
multiBinder.addBinding().toInstance(new ExampleSanityTestScript());
multiBinder.addBinding().toInstance(new ExamplePingGetIDTestScript());
multiBinder.addBinding().toInstance(new ExampleDistributedPingTestScript());
bind(TestRunner.class).to(new MultiTestRunnerTypeLiteral()).in(Singleton.class);
}
@Provides
@Named(SSHEnvironmentFactory.EXECUTOR_ARGUMENT_NAME)
@Singleton
@SuppressWarnings("unused")
Executor provideSSHEnvironmentFactoryExecutor() {
return Executors.newCachedThreadPool();
}
private static class AppFactoryTypeLiteral
extends TypeLiteral<ApplicationFactory<Environment, ExampleApp>> {
}
private static class EnvironmentFactoryTypeLiteral
extends TypeLiteral<EnvironmentFactory<Environment>> {
}
private static class EnvironmentPreparatorTypeLiteral
extends TypeLiteral<EnvironmentPreparator<Environment>> {
}
private static class TestScriptTypeLiteral extends TypeLiteral<TestScript<ExampleApp>> {
}
}
private static class MultiTestRunnerTypeLiteral extends
TypeLiteral<MultiTestRunner<Environment, ExampleApp>> {
}
private static String calculateCurrentTimeStamp() {
return new SimpleDateFormat("yyyyMMdd-HHmmssSSS").format(new Date());
}
private static Path calculateReportPath() {
return FileSystems.getDefault().getPath(REPORT_PATH_PREFIX + calculateCurrentTimeStamp());
}
private static Options createOptions() {
Options options = new Options();
OptionBuilder.withLongOpt(CONFIG_OPTION);
OptionBuilder.hasArgs();
OptionBuilder.withValueSeparator(' ');
OptionBuilder.withDescription("Configure initial dependencies. Arguments should be a list of"
+ " the form: a.b=value1 a.c=value2.");
Option configOption = OptionBuilder.create();
OptionBuilder.withLongOpt(CONFIG_FILE_OPTION);
OptionBuilder.hasArg();
OptionBuilder.withDescription("XML configuration filename.");
Option configFileOption = OptionBuilder.create();
OptionBuilder.withLongOpt(ENV_FACTORY_OPTION);
OptionBuilder.hasArg();
OptionBuilder.withDescription("Environment factory name. Can be either local or ssh.");
Option envFactoryOption = OptionBuilder.create();
options.addOption(configOption);
options.addOption(configFileOption);
options.addOption(envFactoryOption);
options.addOption("h", HELP_OPTION, false, "Print help.");
return options;
}
private static Map<String, String> newDefaultProperties() {
Map<String, String> properties = new HashMap<>();
properties.put(LocalEnvironmentFactory.DIR_PREFIX_ARGUMENT_NAME, ENV_DIR_PREFIX);
properties.put(SSHEnvironmentFactory.REMOTE_DIR_ARGUMENT_NAME, ENV_DIR_PREFIX);
properties.put(MultiTestRunner.SHOULD_PREPARE_ARGUMENT_NAME, "true");
properties.put(MultiTestRunner.SHOULD_CLEAN_ARGUMENT_NAME, "true");
properties.put(MultiTestRunner.REPORT_PATH_ARGUMENT_NAME, calculateReportPath().toString());
return properties;
}
private static Map<String,String> parseAndProcessArguments(String[] args)
throws ConfigurationException, ParseException {
Map<String, String> properties = new HashMap<>();
CommandLineParser parser = new BasicParser();
Options options = createOptions();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
LOGGER.error("parseAndProcessArguments(): ParseException caught parsing arguments.", e);
throw e;
}
if (cmd.hasOption(HELP_OPTION)) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ExampleGuiceMain", options);
return null;
}
if (cmd.hasOption(CONFIG_FILE_OPTION)) {
String argValue = cmd.getOptionValue(CONFIG_FILE_OPTION);
HierarchicalConfiguration config;
try {
config = new XMLConfiguration(argValue);
} catch (ConfigurationException e) {
LOGGER.error("parseAndProcessArguments(): ConfigurationException caught when reading"
+ " configuration file.", e);
throw e;
}
properties.putAll(constructPropertiesFromRootsChildren(config));
}
if (cmd.hasOption(CONFIG_OPTION)) {
String[] argValues = cmd.getOptionValues(CONFIG_OPTION);
for (String arg : argValues) {
String[] keyAndValue = arg.split("=", 2);
String key = keyAndValue[0];
String value = "";
if (keyAndValue.length == 2) {
value = keyAndValue[1];
}
properties.put(key, value);
}
}
if (cmd.hasOption(ENV_FACTORY_OPTION)) {
String argValue = cmd.getOptionValue(ENV_FACTORY_OPTION);
switch (argValue) {
case "local":
mEnvironmentFactoryClass = LocalEnvironmentFactory.class;
break;
case "ssh":
mEnvironmentFactoryClass = SSHEnvironmentFactory.class;
break;
default:
String errorMsg = "Unknown environment factory " + argValue;
LOGGER.error("parseAndProcessArguments(): {}", errorMsg);
throw new IllegalArgumentException(errorMsg);
}
} else {
String errorMsg = String.format("--%s option is required. Use --help to get usage help.",
ENV_FACTORY_OPTION);
LOGGER.error("parseAndProcessArguments(): {}", errorMsg);
throw new IllegalArgumentException(errorMsg);
}
return properties;
}
private static Map<String, String> constructPropertiesFromRootsChildren(
HierarchicalConfiguration config) {
Map<String, String> properties = new HashMap<>();
List<ConfigurationNode> rootsChildrenList = config.getRoot().getChildren();
for (ConfigurationNode child : rootsChildrenList) {
HierarchicalConfiguration subConfig = config.configurationAt(child.getName());
properties.putAll(GuiceTestRunnerModule.configurationToProperties(subConfig));
}
return properties;
}
} |
package gov.nih.nci.calab.dto.characterization;
import gov.nih.nci.calab.domain.InstrumentConfiguration;
import gov.nih.nci.calab.domain.ProtocolFile;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.dto.common.InstrumentConfigBean;
import gov.nih.nci.calab.dto.common.ProtocolFileBean;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class represents shared characterization properties to be shown in
* characterization view pages.
*
* @author pansu
*
*/
public class CharacterizationBean {
private String id;
private String characterizationSource;
// used to distinguish different instances of characterizations, which are
// shown as different links on the view pages.
private String viewTitle;
// used for link color on the side menu
private String viewColor;
private String description;
// not set by application
private String name;
// Abbreviation
private String abbr;
// not set by application
private String classification;
private String createdBy;
private Date createdDate;
private InstrumentConfigBean instrumentConfigBean = new InstrumentConfigBean();
private List<DerivedBioAssayDataBean> derivedBioAssayDataList = new ArrayList<DerivedBioAssayDataBean>();
private String numberOfDerivedBioAssayData;
private ProtocolFileBean protocolFileBean = new ProtocolFileBean();
private String actionName;
private String particleName;
public String getActionName() {
actionName = StringUtils.getOneWordLowerCaseFirstLetter(name);
return actionName;
}
public CharacterizationBean() {
}
/**
* Copy constructor
*
* @param charBean
*/
public CharacterizationBean(CharacterizationBean charBean) {
this.id = charBean.getId();
this.name = charBean.getName();
this.viewTitle = charBean.getViewTitle();
this.characterizationSource = charBean.getCharacterizationSource();
this.classification = charBean.getClassification();
this.createdBy = charBean.getCreatedBy();
this.createdDate = charBean.getCreatedDate();
this.derivedBioAssayDataList = charBean.getDerivedBioAssayDataList();
this.description = charBean.getDescription();
this.instrumentConfigBean = charBean.getInstrumentConfigBean();
this.protocolFileBean = charBean.getProtocolFileBean();
}
public CharacterizationBean(String id, String name, String viewTitle) {
this.id = id;
this.name = name;
setAbbr(name);
this.viewTitle = viewTitle;
}
public CharacterizationBean(Characterization characterization) {
this.setId(characterization.getId().toString());
this.setViewTitle(characterization.getIdentificationName());
this.setCharacterizationSource(characterization.getSource());
this.setCreatedBy(characterization.getCreatedBy());
this.setCreatedDate(characterization.getCreatedDate());
this.name = characterization.getName();
setAbbr(name);
this.setDescription(characterization.getDescription());
InstrumentConfiguration instrumentConfigObj = characterization
.getInstrumentConfiguration();
if (instrumentConfigObj != null) {
instrumentConfigBean = new InstrumentConfigBean(instrumentConfigObj);
}
this.setNumberOfDerivedBioAssayData(Integer.valueOf(
characterization.getDerivedBioAssayDataCollection().size())
.toString());
for (DerivedBioAssayData table : characterization
.getDerivedBioAssayDataCollection()) {
DerivedBioAssayDataBean ctBean = new DerivedBioAssayDataBean(table);
this.getDerivedBioAssayDataList().add(ctBean);
}
ProtocolFile protocolFile = characterization.getProtocolFile();
if (protocolFile != null) {
protocolFileBean = new ProtocolFileBean(protocolFile);
}
this.numberOfDerivedBioAssayData = derivedBioAssayDataList.size() + "";
}
public String getCharacterizationSource() {
return characterizationSource;
}
public void setCharacterizationSource(String characterizationSource) {
this.characterizationSource = characterizationSource;
}
public String getViewTitle() {
// get only the first number of characters of the title
if (viewTitle != null
&& viewTitle.length() > CaNanoLabConstants.MAX_VIEW_TITLE_LENGTH) {
return viewTitle.substring(0,
CaNanoLabConstants.MAX_VIEW_TITLE_LENGTH);
}
return viewTitle;
}
public void setViewTitle(String viewTitle) {
this.viewTitle = viewTitle;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Update the domain characterization object from the dto bean properties
*
* @return
*/
public void updateDomainObj(Characterization aChar) {
if (getId() != null && getId().length() > 0) {
aChar.setId(new Long(getId()));
}
aChar.setSource(getCharacterizationSource());
aChar.setIdentificationName(getViewTitle());
aChar.setDescription(getDescription());
aChar.setCreatedBy(getCreatedBy());
aChar.setCreatedDate(getCreatedDate());
for (DerivedBioAssayDataBean table : getDerivedBioAssayDataList()) {
aChar.getDerivedBioAssayDataCollection().add(
table.getDomainObject());
}
InstrumentConfiguration instrumentConfig = instrumentConfigBean
.getDomainObject();
//only set instrument config if instrument is selected.
if ((instrumentConfig.getInstrument() != null)&& (instrumentConfig.getInstrument().getType() != null))
if (instrumentConfig.getInstrument().getType().length() > 0) {
aChar.setInstrumentConfiguration(instrumentConfig);
}
if (protocolFileBean.getId() != null
&& protocolFileBean.getId().length() > 0) {
ProtocolFile protocolFile = new ProtocolFile();
protocolFile.setId(new Long(protocolFileBean.getId()));
aChar.setProtocolFile(protocolFile);
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getClassification() {
return classification;
}
public String getName() {
return name;
}
private void setAbbr(String name) {
if (name.equals(CaNanoLabConstants.PHYSICAL_COMPOSITION)) {
this.abbr = CaNanoLabConstants.ABBR_COMPOSITION;
} else if (name.equals(CaNanoLabConstants.PHYSICAL_SIZE)) {
this.abbr = CaNanoLabConstants.ABBR_SIZE;
} else if (name.equals(CaNanoLabConstants.PHYSICAL_MOLECULAR_WEIGHT)) {
this.abbr = CaNanoLabConstants.ABBR_MOLECULAR_WEIGHT;
} else if (name.equals(CaNanoLabConstants.PHYSICAL_MORPHOLOGY)) {
this.abbr = CaNanoLabConstants.ABBR_MORPHOLOGY;
} else if (name.equals(CaNanoLabConstants.PHYSICAL_SHAPE)) {
this.abbr = CaNanoLabConstants.ABBR_SHAPE;
} else if (name.equals(CaNanoLabConstants.PHYSICAL_SOLUBILITY)) {
this.abbr = CaNanoLabConstants.ABBR_SOLUBILITY;
} else if (name.equals(CaNanoLabConstants.PHYSICAL_SURFACE)) {
this.abbr = CaNanoLabConstants.ABBR_SURFACE;
} else if (name.equals(CaNanoLabConstants.PHYSICAL_PURITY)) {
this.abbr = CaNanoLabConstants.ABBR_PURITY;
} else if (name.equals(CaNanoLabConstants.TOXICITY_OXIDATIVE_STRESS)) {
this.abbr = CaNanoLabConstants.ABBR_OXIDATIVE_STRESS;
} else if (name.equals(CaNanoLabConstants.TOXICITY_ENZYME_FUNCTION)) {
this.abbr = CaNanoLabConstants.ABBR_ENZYME_FUNCTION;
} else if (name.equals(CaNanoLabConstants.CYTOTOXICITY_CELL_VIABILITY)) {
this.abbr = CaNanoLabConstants.ABBR_CELL_VIABILITY;
} else if (name
.equals(CaNanoLabConstants.CYTOTOXICITY_CASPASE3_ACTIVIATION)) {
this.abbr = CaNanoLabConstants.ABBR_CASPASE3_ACTIVATION;
} else if (name
.equals(CaNanoLabConstants.BLOODCONTACTTOX_PLATE_AGGREGATION)) {
this.abbr = CaNanoLabConstants.ABBR_PLATELET_AGGREGATION;
} else if (name.equals(CaNanoLabConstants.BLOODCONTACTTOX_HEMOLYSIS)) {
this.abbr = CaNanoLabConstants.ABBR_HEMOLYSIS;
} else if (name
.equals(CaNanoLabConstants.BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING)) {
this.abbr = CaNanoLabConstants.ABBR_PLASMA_PROTEIN_BINDING;
} else if (name.equals(CaNanoLabConstants.BLOODCONTACTTOX_COAGULATION)) {
this.abbr = CaNanoLabConstants.ABBR_COAGULATION;
} else if (name
.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_OXIDATIVE_BURST)) {
this.abbr = CaNanoLabConstants.ABBR_OXIDATIVE_BURST;
} else if (name.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_CHEMOTAXIS)) {
this.abbr = CaNanoLabConstants.ABBR_CHEMOTAXIS;
} else if (name
.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION)) {
this.abbr = CaNanoLabConstants.ABBR_LEUKOCYTE_PROLIFERATION;
} else if (name
.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_PHAGOCYTOSIS)) {
this.abbr = CaNanoLabConstants.ABBR_PHAGOCYTOSIS;
} else if (name
.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION)) {
this.abbr = CaNanoLabConstants.ABBR_CYTOKINE_INDUCTION;
} else if (name.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_CFU_GM)) {
this.abbr = CaNanoLabConstants.ABBR_CFU_GM;
} else if (name
.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION)) {
this.abbr = CaNanoLabConstants.ABBR_COMPLEMENT_ACTIVATION;
} else if (name
.equals(CaNanoLabConstants.IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY)) {
this.abbr = CaNanoLabConstants.ABBR_NKCELL_CYTOTOXIC_ACTIVITY;
} else {
this.abbr = CaNanoLabConstants.OTHER; // shouldn't happen at all.
}
}
public String getAbbr() {
return abbr;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public List<DerivedBioAssayDataBean> getDerivedBioAssayDataList() {
return derivedBioAssayDataList;
}
public void setDerivedBioAssayDataList(
List<DerivedBioAssayDataBean> derivedBioAssayData) {
this.derivedBioAssayDataList = derivedBioAssayData;
}
public InstrumentConfigBean getInstrumentConfigBean() {
return instrumentConfigBean;
}
public void setInstrumentConfigBean(
InstrumentConfigBean instrumentConfigBean) {
this.instrumentConfigBean = instrumentConfigBean;
}
public String getNumberOfDerivedBioAssayData() {
return numberOfDerivedBioAssayData;
}
public void setNumberOfDerivedBioAssayData(
String numberOfDerivedBioAssayData) {
this.numberOfDerivedBioAssayData = numberOfDerivedBioAssayData;
}
public ProtocolFileBean getProtocolFileBean() {
return protocolFileBean;
}
public void setProtocolFileBean(ProtocolFileBean protocolFileBean) {
this.protocolFileBean = protocolFileBean;
}
public String getViewColor() {
if (viewTitle.matches("^copy_\\d{15}?")) {
viewColor=CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_COLOR;
}
return viewColor;
}
public String getParticleName() {
return particleName;
}
public void setParticleName(String particleName) {
this.particleName = particleName;
}
/**
* Create a new instance of CharacterizationBean with the same metadata
* except DerivedBioAssayDataList and InstrumentConfig.
*
* @return
*/
public CharacterizationBean copy(boolean copyData) {
CharacterizationBean newCharBean = new CharacterizationBean(this);
//unset id
newCharBean.setId(null);
// set InstrumentConfig, DerivedBioAssayDataList
InstrumentConfigBean newInstrumentConfigBean = instrumentConfigBean
.copy();
newCharBean.setInstrumentConfigBean(newInstrumentConfigBean);
List<DerivedBioAssayDataBean> newDerivedBioAssayDataList = new ArrayList<DerivedBioAssayDataBean>();
for (DerivedBioAssayDataBean derivedBioAssayDataBean : derivedBioAssayDataList) {
DerivedBioAssayDataBean newDerivedBioAssayDataBean = derivedBioAssayDataBean
.copy(copyData);
newDerivedBioAssayDataList.add(newDerivedBioAssayDataBean);
}
newCharBean.setDerivedBioAssayDataList(newDerivedBioAssayDataList);
return newCharBean;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mapviewer.business.servlets;
import com.mapviewer.business.LayerMenuManagerSingleton;
import com.mapviewer.exceptions.XMLFilesException;
import com.mapviewer.model.BoundaryBox;
import com.mapviewer.model.Layer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This servlet obtains the 'punctual' data of the layers by generating a WMS
* 'GetFeatureInfo' request. In order to avoid the AJAX restriction of the 'same domain
* request this servlet makes the request on its own and stores all the result in a
* string, then it returns the string to the page. Fills in the ${server} variable
*
* @author Olmo Zavala Romero
*/
@WebServlet(name = "RedirectServersServlet", urlPatterns = {"/redirect"})
public class RedirectServersServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=iso-8859-1");
synchronized (this) {
String reqResult = "";
try {
reqResult = generateRedirect(request);
} catch (Exception e) {
Logger.getLogger(RedirectServersServlet.class.getName()).log(Level.SEVERE, "Error MapViewer en Redirect en ProcessRequest" + e.getMessage(), e);
}
request.setAttribute("server", reqResult);
}
RequestDispatcher view = request.getRequestDispatcher("Pages/Datos/Datos.jsp");//basically where to display the response
view.forward(request, response);
}
/**
*
* @param request object containing the parameters
*
* @return string that contains the html to geenrate the WCS page
*/
private String generateRedirect(HttpServletRequest request) {
String result = "";
boolean finish = false; //check to see if the request finished
int numberOfRetries = 10; //retry number
int retry = 0;
String server = request.getParameter("server");
String layers = request.getParameter("LAYERS");
String styles = request.getParameter("STYLES");
String width = request.getParameter("WIDTH");
String height = request.getParameter("HEIGHT");
String srs = request.getParameter("SRS");
String format = request.getParameter("FORMAT");
String service = request.getParameter("SERVICE");
String version = request.getParameter("VERSION");
String req = request.getParameter("REQUEST");
String exceptions = request.getParameter("EXCEPTIONS");
String bbox = request.getParameter("BBOX");
String x = request.getParameter("x");
String y = request.getParameter("y");
String infoFormat = request.getParameter("INFO_FORMAT");
String queryLayers = request.getParameter("QUERY_LAYERS");
String featureCount = request.getParameter("FEATURE_COUNT");
String cql_filter = request.getParameter("CQL_FILTER");
//Only for Ol3 We need to be sure is always necessary
BoundaryBox bboxObject= new BoundaryBox(bbox);
bbox = bboxObject.toString();
//final url request.
String finalRequest = server + "?LAYERS=" + layers + "&STYLES=" + styles + "&WIDTH=" + width + "&HEIGHT=" + height + "&SRS=" + srs + "&FORMAT=" + format + "&SERVICE=" + service + "&VERSION=" + version + "&REQUEST=" + req + "&EXCEPTIONS=" + exceptions + "&BBOX=" + bbox + "&x=" + x + "&y=" + y + "&INFO_FORMAT=" + infoFormat + "&QUERY_LAYERS=" + queryLayers + "&FEATURE_COUNT=" + featureCount;
//Adding the CQL filter request
if (cql_filter != null) {
//The next line replaces spaces with the proper space character.
//It may be necessary to replace other chars that are not allowed inside an URL
cql_filter = cql_filter.replace(" ", "%20");
finalRequest += "&CQL_FILTER=" + cql_filter;
}
if(server == null || server == "null"){
return "";
}
String elevation = "";
String time = "";
String timeSeriesUrl = "";
//Just for netcdf
boolean isNetCDF = Boolean.parseBoolean(request.getParameter("NETCDF"));
if (isNetCDF) {//In this case we have a NetCDF layer
elevation = request.getParameter("ELEVATION");
time = request.getParameter("TIME");
if( elevation != "" && elevation != null ){
finalRequest += "&ELEVATION=" + elevation;
}
if (!time.equals("No current date")) {
finalRequest += "&TIME=" + time;
timeSeriesUrl = server + "?LAYERS=" + layers + "&STYLES=" + styles + "&WIDTH=" + width + "&HEIGHT=" + height + "&SRS=" + srs
+ "&FORMAT=image/png&SERVICE=" + service + "&VERSION=" + version
+ "&REQUEST=" + req + "&BBOX=" + bbox + "&x=" + x + "&y=" + y + "&INFO_FORMAT=image/png&QUERY_LAYERS=" + queryLayers;
if(elevation != null){
timeSeriesUrl += "&ELEVATION=" + elevation ;
}
}
}
DecimalFormat myFormatter = new DecimalFormat("
//we keep trying until server answers or numberOfRetries is reached.
while (!finish && retry < numberOfRetries) {
try {
URL acdm = new URL(finalRequest);//make the request to the server.
try {
acdm.openConnection(); //we connect ot eh server.
} catch (MalformedURLException e) {
System.out.println("Error MapViewer en RedirectServer en generateRedirect url: "+finalRequest + e.getMessage());
}
//repeat process until we obtain data.
retry++; //increment tryies.
finish = true; //by default we supose data is good.
result = "";
InputStreamReader input = new InputStreamReader(acdm.openStream());
BufferedReader in = new BufferedReader(input);
String inputLine;
// These two variables are only used when requesting ncWMS layers
// and are used to generate the link for the vertical profile
float lon = 0;
float lat = 0;
boolean ncWMS_HeaderAdded = false;//Keeps track of adding a header of main layer
//sometimes the server return wierd characters so we filter them. (caracteres ,??,*, etc.)
while ((inputLine = in.readLine()) != null) {
//In version 1.7.5 of the geoserver, we otain an error when we ask for data outside the the correspoinding layer
//in this case we detect the execption type and we terminate.
if (inputLine.contains("Internal error occurred")) {
result = "";
break;
}
if (inputLine.contains("")
|| inputLine.contains("??")
|| inputLine.contains("`")
|| inputLine.contains("*")) {
finish = false;//if a invalid character comes we dont terminate it.
break;
} else {
// If using ncWMS the responses are very different so we need to 'patch'
// the answer in order to make it look nice.
if (isNetCDF) {
if(!ncWMS_HeaderAdded){
result += " <hr style='border: 0;" +
" height: 1px;" +
" background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0)); " +
" background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0)); " +
" background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0)); " +
" background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));" +
" margin: 5px; '>";
ncWMS_HeaderAdded = true;
}
// We are interested in 3 lines. The one that contains the 'value'
// at the specific point. The ones that contains 'lon' and 'lat'
// to create the vertical profile link
if (inputLine.toLowerCase().contains("longitude")) {
inputLine = inputLine.replace("<longitude>", "");
inputLine = inputLine.replace("</longitude>", "");
lon = Float.parseFloat(inputLine);
}
if (inputLine.toLowerCase().contains("latitude")) {
inputLine = inputLine.replace("<latitude>", "");
inputLine = inputLine.replace("</latitude>", "");
lat = Float.parseFloat(inputLine);
}
if (inputLine.contains("value")) {
if (!inputLine.contains("none")) {
inputLine = inputLine.replace("<value>", "");
inputLine = inputLine.replace("</value>", "");
float value = Float.parseFloat(inputLine);
if (layers.toLowerCase().contains("Temp") || layers.toLowerCase().contains("temp")) {
result += "<b >Temp: </b>" + myFormatter.format(value) + " °C <br>";//if no random characters then we save the result.
} else {
result += "<b >Value: </b>" + myFormatter.format(value) + " ADD_UNITS <br>";
}
} else {
result = "";
break;
}
}
} else {
result += inputLine;
}
}
}
//Finally we add the link to generate the vertical profile
// for netCDF layers with more than one elevation.
// Not needed any more, the vertical profile and vertical transect is generated by PunctualData.js
//if (isNetCDF) {
// LayerMenuManagerSingleton layersSing = LayerMenuManagerSingleton.getInstance();
// Layer layer = layersSing.getLayerByName(layers);//Search current layer
// BoundaryBox BBOX = layer.getBbox();
// if ((lat <= BBOX.getMaxLat()) && (lat >= BBOX.getMinLat())
// && (lon <= BBOX.getMaxLong()) && (lon >= BBOX.getMinLong())) {
// if (elevation != null && !elevation.equals("")) {
// String vertProfUrl = server + "?REQUEST=GetVerticalProfile&VERSION=1.1.1&STYLES="+styles+"&LAYER=" + layers + "&CRS=CRS:84"
// + "&POINT=" + lon + " " + lat + "&FORMAT=image/png";
// if (!time.equals("No current date")) {
// vertProfUrl += "&TIME=" + time;
// }//if no current date
// result += "<b>Vertical profile: </b> <a href='#' onclick=\"owgis.utils.popUp('" + vertProfUrl + "',520,420)\" > show </a><br>";
// // Add link for time series plot
// time = request.getParameter("BOTHTIMES");
// //We only add the link if we receive the TIME information
// if (!time.equals("No current date") && !time.equals("undefined")) {
// timeSeriesUrl += "&TIME=" + time;
// result += "<b>Time series plot: </b> <a href='#' onclick=\"owgis.utils.popUp('" + timeSeriesUrl + "',520,420)\" > show </a><br>";
// } else {
// result = "";
// }//else outside BBOX
//}//if isNetCDF
in.close();//close the connection with the server.
input.close();
} catch (IOException ex) {
Logger.getLogger(RedirectServersServlet.class.getName()).log(Level.SEVERE, "Error MapViewer en RedirectServer en generateRedirect url: "+finalRequest + ex.getMessage(), ex);
finish = false;
}
}
if (retry == numberOfRetries) {//if max number of tryies is reached we just send an empty string.
result = "";
}
return result;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
synchronized (this) {
this.processRequest(request, response);
}
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
synchronized (this) {
this.processRequest(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
} |
package gov.nih.nci.cadsr.cadsrpasswordchange.core;
import gov.nih.nci.cadsr.cadsrpasswordchange.domain.UserSecurityQuestion;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.Period;
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(MainServlet.class.getName());
// private static Connection connection = null;
private static DataSource datasource = null;
private static PasswordChange dao;
private static String HELP_LINK;
private static String LOGO_LINK;
private static void connect() {
boolean isConnectionException = true; // use to modify returned messages when exceptions are system issues instead of password change issues
Result result = new Result(ResultCode.UNKNOWN_ERROR); // (should get replaced)
try {
// if(connection == null) {
datasource = ConnectionUtil.getDS(PasswordChangeDAO._jndiSystem);
dao = new PasswordChangeDAO(datasource);
logger.info("Connected to database");
isConnectionException = false;
} catch (Exception e) {
e.printStackTrace();
if (isConnectionException)
result = new Result(ResultCode.UNKNOWN_ERROR); // error not related to user, provide a generic error
else
result = ConnectionUtil.decode(e);
}
}
private static void disconnect() {
try {
datasource.getConnection().close();
datasource = null;
} catch (Exception e) {
e.printStackTrace();
}
}
private static final int TOTAL_QUESTIONS = 3;
private static final String ERROR_MESSAGE_SESSION_ATTRIBUTE = "ErrorMessage";
private static final String USER_MESSAGE_SESSION_ATTRIBUTE = "UserMessage";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.debug("doGet");
}
private void handleQuestionsOptions(HttpServletRequest req, String[] selectedQuestion) {
req.getSession().setAttribute("selectedQuestion1", selectedQuestion[0]);
req.getSession().setAttribute("selectedQuestion2", selectedQuestion[1]);
req.getSession().setAttribute("selectedQuestion3", selectedQuestion[2]);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.info("doPost");
QuestionHelper.initQuestionsOptions(req);
try {
String servletPath = req.getServletPath();
logger.debug("getServletPath |" + servletPath +"|");
if (servletPath.equals(Constants.SERVLET_URI + "/login")) {
doLogin(req, resp);
} else if (servletPath.equals(Constants.SERVLET_URI + "/changePassword")) {
if(req.getParameter("cancel") != null) {
resp.sendRedirect(Constants.LANDING_URL);
} else {
req.getSession().setAttribute(Constants.ACTION_TOKEN, Constants.CHANGE_TOKEN);
doChangePassword(req, resp);
}
} else if (servletPath.equals(Constants.SERVLET_URI + "/saveQuestions")) {
if(req.getParameter("cancel") != null) {
resp.sendRedirect(Constants.LANDING_URL);
} else {
req.getSession().setAttribute(Constants.ACTION_TOKEN, Constants.SAVE_TOKEN);
doSaveQuestions(req, resp);
}
} else if (servletPath.equals(Constants.SERVLET_URI + "/promptUserQuestions")) {
if(req.getParameter("cancel") != null) {
resp.sendRedirect(Constants.LANDING_URL);
} else {
doRequestUserQuestions(req, resp);
}
} else if (servletPath.equals(Constants.SERVLET_URI + "/promptQuestion1")) {
doQuestion1(req, resp);
} else if (servletPath.equals(Constants.SERVLET_URI + "/promptQuestion2")) {
doQuestion2(req, resp);
} else if (servletPath.equals(Constants.SERVLET_URI + "/promptQuestion3")) {
doQuestion3(req, resp);
} else if (servletPath.equals(Constants.SERVLET_URI + "/validateQuestion1")) {
if(req.getParameter("cancel") != null) {
resp.sendRedirect(Constants.LANDING_URL);
} else {
doValidateQuestion1(req, resp);
}
} else if (servletPath.equals(Constants.SERVLET_URI + "/validateQuestion2")) {
if(req.getParameter("cancel") != null) {
resp.sendRedirect(Constants.LANDING_URL);
} else {
doValidateQuestion2(req, resp);
}
} else if (servletPath.equals(Constants.SERVLET_URI + "/validateQuestion3")) {
if(req.getParameter("cancel") != null) {
resp.sendRedirect(Constants.LANDING_URL);
} else {
doValidateQuestion3(req, resp);
}
} else if (servletPath.equals(Constants.SERVLET_URI + "/resetPassword")) {
if(req.getParameter("cancel") != null) {
resp.sendRedirect(Constants.LANDING_URL);
} else {
doChangePassword2(req, resp);
}
} else {
// this also catches the intentional logout with path /logout
logger.info("logging out because of invalid servlet path");
HttpSession session = req.getSession(false);
if (session != null) {
logger.debug("non-null session");
session.invalidate();
}
resp.sendRedirect("./jsp/loggedOut.jsp");
}
}
catch (Throwable theException) {
logger.error(CommonUtil.toString(theException));
}
}
private void doQuestion3(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.sendRedirect(Constants.RESET_URL);
}
private void doQuestion2(HttpServletRequest req, HttpServletResponse resp) throws Exception {
doValidateQuestion2(req, resp);
}
private void doQuestion1(HttpServletRequest req, HttpServletResponse resp) {
logger.info("doQuestion1");
try {
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
String username = req.getParameter("userid");
if(username != null) {
username = username.toUpperCase();
}
logger.debug("username " + username);
// Security enhancement
Map<String, String> userQuestions = new HashMap<String, String>();
Map<String, String> userAnswers = new HashMap<String, String>();
//pull all questions related to this user
loadUserStoredQna(username, userQuestions, userAnswers);
//TBD - retrieve all questions related to the users from dao and set them into sessions
session.setAttribute(Constants.USERNAME, username);
session.setAttribute(Constants.Q1, userQuestions.get(Constants.Q1));
session.setAttribute(Constants.ALL_QUESTIONS, userQuestions);
session.setAttribute(Constants.ALL_ANSWERS, userAnswers);
if(userQuestions.size() == 0) {
logger.info("no security question found");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.140"));
resp.sendRedirect(Constants.ASK_USERID_URL);
} else {
//resp.sendRedirect(Constants.Q1_URL);
req.getRequestDispatcher("./jsp/askQuestion1.jsp").forward(req, resp);
}
}
catch (Throwable theException) {
logger.error(theException);
}
}
private void saveUserStoredQna(String username, Map<String, String> userQuestions, Map<String, String> userAnswers) throws Exception {
UserSecurityQuestion qna = new UserSecurityQuestion();
logger.debug("entering saveUserStoredQna ...");
try {
qna.setUaName(username);
qna.setQuestion1((String)userQuestions.get(Constants.Q1));
qna.setAnswer1(CommonUtil.encode((String)userAnswers.get(Constants.A1)));
qna.setQuestion2((String)userQuestions.get(Constants.Q2));
qna.setAnswer2(CommonUtil.encode((String)userAnswers.get(Constants.A2)));
qna.setQuestion3((String)userQuestions.get(Constants.Q3));
qna.setAnswer3(CommonUtil.encode((String)userAnswers.get(Constants.A3)));
logger.info("saveUserStoredQna:qna object saved ...");
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
try {
logger.debug("saveUserStoredQna:connecting to the db ...");
connect();
logger.info("saveUserStoredQna:connected 1");
PasswordChangeDAO dao = new PasswordChangeDAO(datasource);
UserSecurityQuestion oldQna = dao.findByUaName(username);
if(oldQna != null) {
logger.debug("saveUserStoredQna:dao.findByUaName(" + username + "' queried ...");
logger.debug("saveUserStoredQna:oldQna.getAttemptedCount() = '" + oldQna.getAttemptedCount() + "'");
qna.setAttemptedCount(oldQna.getAttemptedCount());
logger.debug("saveUserStoredQna:qna.getAttemptedCount() = '" + qna.getAttemptedCount() + "'");
logger.debug("saveUserStoredQna:oldQna.getDateModified() = '" + oldQna.getDateModified() + "'");
qna.setDateModified(oldQna.getDateModified());
logger.debug("saveUserStoredQna:qna.getDateModified() = '" + qna.getDateModified() + "'");
}
connect();
logger.info("saveUserStoredQna:connected 2");
PasswordChangeDAO dao1 = new PasswordChangeDAO(datasource);
if(oldQna == null) {
dao1.insert(qna);
logger.debug("saveUserStoredQna:inserted qna [" + qna.toString() + "]");
} else {
dao1.update(username, qna);
logger.debug("saveUserStoredQna:updated username ["+ username + "] qna [" + qna.toString() + "]");
}
//showUserSecurityQuestionList(); //just for debug
disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private long getUserStoredAttemptedCount(String username) throws Exception {
long count = 0;
try {
connect();
dao = new PasswordChangeDAO(datasource);
UserSecurityQuestion oldQna = dao.findByUaName(username);
if(oldQna == null) {
throw new Exception("Questions have to exists before attempted count can be retrieved.");
}
if(oldQna.getAttemptedCount() != null) {
count = oldQna.getAttemptedCount().longValue();
}
} catch (Exception e) {
logger.error(e);
throw e;
}
return count;
}
private void updateUserStoredAttemptedCount(String username) throws Exception {
try {
PasswordChangeDAO dao = null;
connect();
dao = new PasswordChangeDAO(datasource);
UserSecurityQuestion oldQna = dao.findByUaName(username);
if(oldQna == null) {
throw new Exception("Questions have to exists before attempted count can be updated.");
}
connect();
dao = new PasswordChangeDAO(datasource);
long count = 1;
if(oldQna.getAttemptedCount() != null) {
count = oldQna.getAttemptedCount().longValue() + 1;
}
oldQna.setAttemptedCount(new Long(count));
oldQna.setDateModified(new Timestamp(DateTimeUtils.currentTimeMillis()));
boolean saved = dao.update(username, oldQna);
if(!saved) {
throw new Exception("Answer attempt count not updated properly.");
}
//showUserSecurityQuestionList(); //just for debug
disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private void resetUserStoredAttemptedCount(String username) throws Exception {
try {
connect();
UserSecurityQuestion oldQna = dao.findByUaName(username);
if(oldQna == null) {
throw new Exception("Questions have to exists before attempted count can be reset.");
}
connect();
long count = 0;
oldQna.setAttemptedCount(new Long(count));
oldQna.setDateModified(new Timestamp(DateTimeUtils.currentTimeMillis()));
dao.update(username, oldQna);
//showUserSecurityQuestionList(); //just for debug
disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
//Please the following method for debugging
/*
private void showUserSecurityQuestionList() {
UserSecurityQuestion[] results;
try {
connect();
results = dao.findAll();
if (results.length > 0) {
for (UserSecurityQuestion e : results) {
System.out.println("User [" + e.getUaName() + "] updated ["
+ new Date() + "] question [" + e.getQuestion1()
+ "] answer [" + e.getAnswer1() + "]");
}
} else {
System.out.println("no question");
}
disconnect();
} catch (Exception e1) {
e1.printStackTrace();
}
}
*/
protected void doLogin(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
init();
logger.info("doLogin");
UserBean userBean = null;
try {
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, "");
String username = req.getParameter("userid");
if(username != null) {
username = username.toUpperCase();
}
String password = req.getParameter("pswd");
logger.info("unvalidated username " + username);
if(Messages.getString("PasswordChangeHelper.1").equals(PasswordChangeHelper.validateLogin(username, password))) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.1"));
resp.sendRedirect("./jsp/login.jsp");
return;
}
if(Messages.getString("PasswordChangeHelper.2").equals(PasswordChangeHelper.validateLogin(username, password))) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.2"));
resp.sendRedirect("./jsp/login.jsp");
return;
}
connect();
PasswordChangeDAO loginDAO = new PasswordChangeDAO(datasource);
userBean = loginDAO.checkValidUser(username, password);
disconnect();
session.setAttribute(UserBean.USERBEAN_SESSION_ATTRIBUTE, userBean);
logger.debug ("validUser " + userBean.isLoggedIn());
logger.debug ("resultCode " + userBean.getResult().getResultCode().toString());
if (userBean.isLoggedIn()) {
//preload the questions
QuestionHelper.initQuestionsOptions(req);
// Provide a user message that notes the "expired" status
String userMessage = userBean.getResult().getMessage();
logger.debug ("userMessage " + userMessage);
session.setAttribute(USER_MESSAGE_SESSION_ATTRIBUTE, userMessage);
session.setAttribute("username", username);
resp.sendRedirect("./jsp/changePassword.jsp"); //logged-in page
} else {
String errorMessage1 = userBean.getResult().getMessage();
logger.debug ("errorMessage " + errorMessage1);
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, errorMessage1);
resp.sendRedirect("./jsp/login.jsp");
}
}
catch (Throwable e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
protected void doSaveQuestions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.info("doSaveQuestions");
try {
// req.getSession().invalidate(); //invalid session everytime
// HttpSession session = req.getSession(true);
HttpSession session = req.getSession(false); //caDSR Password Change Station CADSRPASSW-43 Reset security questions/answers are the same
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
// Security enhancement
int paramCount = 0;
String loginID = req.getParameter("userid"); //CADSRPASSW-40
if(loginID != null) {
loginID = loginID.toUpperCase();
}
String question1 = req.getParameter("question1");
String answer1 = req.getParameter("answer1");
String question2 = req.getParameter("question2");
String answer2 = req.getParameter("answer2");
String question3 = req.getParameter("question3");
String answer3 = req.getParameter("answer3");
String status = doValidateAccountStatus(loginID, session, req, resp, "./jsp/setupPassword.jsp");
if(status.indexOf(Constants.LOCKED_STATUS) > -1) {
return;
}
//"remember" the questions selected by the user
String selectedQ[] = {question1, question2, question3};
handleQuestionsOptions(req, selectedQ);
req.getSession().setAttribute("userid", loginID); //CADSRPASSW-40
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, "");
UserBean userBean = (UserBean) session.getAttribute(UserBean.USERBEAN_SESSION_ATTRIBUTE);
// String username = req.getParameter("userid");
String password = req.getParameter("password");
if(!StringEscapeUtils.escapeHtml4(answer1).equals(answer1) ||
!StringEscapeUtils.escapeHtml4(answer2).equals(answer2) ||
!StringEscapeUtils.escapeHtml4(answer3).equals(answer3)) {
logger.debug("invalid character failed during questions/answers save");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.160"));
//req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
//DoS attack using string length overflow
if(!CommonUtil.truncate(answer1, Constants.MAX_ANSWER_LENGTH).equals(answer1) ||
!CommonUtil.truncate(answer2, Constants.MAX_ANSWER_LENGTH).equals(answer2) ||
!CommonUtil.truncate(answer3, Constants.MAX_ANSWER_LENGTH).equals(answer3) ||
!CommonUtil.truncate(question1, Constants.MAX_ANSWER_LENGTH).equals(question1) ||
!CommonUtil.truncate(question2, Constants.MAX_ANSWER_LENGTH).equals(question2) ||
!CommonUtil.truncate(question3, Constants.MAX_ANSWER_LENGTH).equals(question3)) {
logger.debug("invalid answer(s) length during questions/answers save");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.112"));
// req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
logger.debug("saveQuestions:username " + loginID);
//CADSRPASSW-54
if(ConnectionUtil.isExpiredAccount(loginID, password)) {
logger.debug("expired password status for userid " + loginID);
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.104"));
//req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
//CADSRPASSW-49
if(status.equals(Constants.EXPIRED_STATUS)) {
connect();
PasswordChangeDAO userDAO = new PasswordChangeDAO(datasource);
try {
if(!userDAO.checkValidUser(loginID)) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101"));
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
disconnect();
}
} else {
connect();
PasswordChangeDAO loginDAO = new PasswordChangeDAO(datasource);
userBean = loginDAO.checkValidUser(loginID, password);
disconnect();
session.setAttribute(UserBean.USERBEAN_SESSION_ATTRIBUTE, userBean);
logger.debug ("validUser" + userBean.isLoggedIn());
logger.debug ("resultCode " + userBean.getResult().getResultCode().toString());
if (!userBean.isLoggedIn()) {
logger.debug("auth failed during questions/answers save");
if(userBean.getResult().getResultCode() != ResultCode.LOCKED_OUT) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.102"));
} else {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.103"));
}
//req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
}
// Security enhancement
Map<String, String> userQuestions = new HashMap<String, String>();
userQuestions.put(question1,"");
userQuestions.put(question2,"");
userQuestions.put(question3,"");
if(question1 != null && !question1.equals("")) paramCount++;
if(question2 != null && !question2.equals("")) paramCount++;
if(question3 != null && !question3.equals("")) paramCount++;
if(userQuestions.size() < TOTAL_QUESTIONS && paramCount == TOTAL_QUESTIONS) {
logger.debug("security Q&A validation failed");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.135"));
//req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
userQuestions = new HashMap<String, String>();
Map<String, String> userAnswers = new HashMap<String, String>();
if(question1 != null && !question1.equals("") && answer1 != null && !answer1.equals("")) userQuestions.put(Constants.Q1, question1); userAnswers.put(Constants.A1, answer1);
if(question2 != null && !question2.equals("") && answer2 != null && !answer2.equals("")) userQuestions.put(Constants.Q2, question2); userAnswers.put(Constants.A2, answer2);
if(question3 != null && !question3.equals("") && answer3 != null && !answer3.equals("")) userQuestions.put(Constants.Q3, question3); userAnswers.put(Constants.A3, answer3);
logger.debug("saving request: " + question1 + "=" + answer1 + " " +question2 + "=" + answer2 + " " +question3 + "=" + answer3);
if(Messages.getString("PasswordChangeHelper.125").equals(PasswordChangeHelper.validateSecurityQandA(TOTAL_QUESTIONS, loginID, userQuestions, userAnswers))) {
logger.debug("security Q&A validation failed");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.125"));
//req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
if(!PasswordChangeHelper.validateQuestionsLength(TOTAL_QUESTIONS, userQuestions, userAnswers)) {
logger.debug("security Q&A validation failed");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.150"));
//req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5
req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp);
return;
}
logger.info("saving request: user provided " + userQuestions + " " + userAnswers);
saveUserStoredQna(loginID, userQuestions, userAnswers);
//TBD - retrieve all questions related to the users from dao and set them into sessions
session.setAttribute(Constants.USERNAME, loginID);
session.invalidate();
resp.sendRedirect(Constants.SETUP_SAVED_URL);
}
catch (Throwable theException) {
logger.error(theException);
}
}
protected void doRequestUserQuestions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.info("doRequestUserQuestions");
try {
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
String username = req.getParameter("userid");
if(username != null) {
username = username.toUpperCase();
}
logger.debug("username " + username);
String status = doValidateAccountStatus(username, session, req, resp, Constants.ASK_USERID_URL);
if(status.indexOf(Constants.LOCKED_STATUS) > -1) {
return;
}
connect();
PasswordChangeDAO userDAO = new PasswordChangeDAO(datasource);
try {
if(!userDAO.checkValidUser(username)) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101"));
resp.sendRedirect(Constants.ASK_USERID_URL);
return;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
disconnect();
}
// Security enhancement
Map<String, String> userQuestions = new HashMap<String, String>();
Map<String, String> userAnswers = new HashMap<String, String>();
//pull all questions related to this user
loadUserStoredQna(username, userQuestions, userAnswers);
//TBD - retrieve all questions related to the users from dao and set them into sessions
session.setAttribute(Constants.USERNAME, username);
session.removeAttribute(Constants.Q1);
session.setAttribute(Constants.Q1, userQuestions.get(Constants.Q1));
session.removeAttribute(Constants.Q2);
session.setAttribute(Constants.Q2, userQuestions.get(Constants.Q2));
session.removeAttribute(Constants.Q3);
session.setAttribute(Constants.Q3, userQuestions.get(Constants.Q3));
session.removeAttribute(Constants.ALL_QUESTIONS);
logger.debug("questions removed from session.");
session.setAttribute(Constants.ALL_QUESTIONS, userQuestions);
logger.debug("questions saved in session.");
session.removeAttribute(Constants.ALL_ANSWERS);
logger.debug("answers removed from session.");
session.setAttribute(Constants.ALL_ANSWERS, userAnswers);
logger.debug("answers saved in session.");
if(userQuestions == null || userQuestions.size() == 0) {
logger.info("no security question found");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.140"));
resp.sendRedirect(Constants.ASK_USERID_URL);
return;
}
if(doValidateAttemptedCount(session, resp, Constants.ASK_USERID_URL) == false) {
return;
}
//resp.sendRedirect(Constants.Q1_URL);
req.getRequestDispatcher("./jsp/askQuestion1.jsp").forward(req, resp);
}
catch (Throwable theException) {
logger.error(theException);
}
}
/**
* Method to detect account lock condition.
*
* @param username
* @param password
* @param session
* @param req
* @param resp
* @param redictedUrl
* @return account status
* @throws Exception
*/
private String doValidateAccountStatus(String username, HttpSession session, HttpServletRequest req, HttpServletResponse resp, String redictedUrl) throws Exception {
String retVal = "";
//check locked state here
String action = (String)session.getAttribute(Constants.ACTION_TOKEN);
if(action != null && !action.equals(Constants.UNLOCK_TOKEN)) {
//CADSRPASSW-29
connect();
PasswordChangeDAO dao = new PasswordChangeDAO(datasource);
retVal = dao.getAccountStatus(username);
if(retVal != null && retVal.indexOf(Constants.LOCKED_STATUS) > -1) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.103"));
resp.sendRedirect(redictedUrl);
}
}
return retVal;
}
//CADSRPASSW-42
private boolean doValidateAttemptedCount(HttpSession session, HttpServletResponse resp, String redictedUrl) throws Exception {
boolean retVal = true;
if(session == null) {
throw new Exception("Http session is null or empty.");
}
String userID = (String)session.getAttribute(Constants.USERNAME);
//CADSRPASSW-51
if(isAnswerLockPeriodOver(userID)) {
resetUserStoredAttemptedCount(userID);
} else {
long count = getUserStoredAttemptedCount(userID);
if(count >= 5) {
logger.info("security answers limit reached");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.111"));
resp.sendRedirect(redictedUrl);
retVal = false;
} else {
retVal = true;
}
}
return retVal;
}
private boolean isAnswerLockPeriodOver(String userID) throws Exception {
boolean retVal = false;
logger.debug("isAnswerLockExpired:entered");
connect();
PasswordChangeDAO dao = new PasswordChangeDAO(datasource);
logger.debug("isAnswerLockExpired:before dao.findByPrimaryKey userid [" + userID + "]");
UserSecurityQuestion qna = dao.findByPrimaryKey(userID);
logger.debug("isAnswerLockExpired:qna [" + qna + "]");
if(qna != null) {
logger.debug("isAnswerLockExpired:qna not null [" + qna.toString() + "]");
if(qna.getDateModified() == null) {
throw new Exception("Security questions date modified is NULL or empty.");
}
DateTime now = new DateTime();
logger.debug("isAnswerLockExpired:last modified date for user '" + userID + "' is " + qna.getDateModified());
Period period = new Period(new DateTime(qna.getDateModified()), now);
if(period.getHours() >= 1) { //CADSRPASSW-51
retVal = true;
logger.info("isAnswerLockExpired:Over 1 hour for user '" + userID + "', answer limit count reset (" + period.getMinutes() + " minutes has passed).");
} else {
logger.debug("isAnswerLockExpired:Not over 1 hour yet for user '" + userID + "', nothing is done (" + period.getMinutes() + " minutes has passed).");
}
}
logger.debug("isAnswerLockExpired:exiting ...");
return retVal;
}
protected void doValidateQuestion1(HttpServletRequest req, HttpServletResponse resp)
throws Exception {
logger.info("doValidateQuestion 1");
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
if(doValidateAttemptedCount(session, resp, "./jsp/askQuestion1.jsp") == false) {
return;
}
try {
if (validateQuestions(req, resp)) {
logger.info("answer is correct");
resetUserStoredAttemptedCount((String)req.getSession().getAttribute(Constants.USERNAME)); //CADSRPASSW-42
resp.sendRedirect("./jsp/askQuestion2.jsp");
} else {
logger.info("security question answered wrongly");
updateUserStoredAttemptedCount((String)session.getAttribute(Constants.USERNAME)); //CADSRPASSW-42
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.130"));
resp.sendRedirect("./jsp/askQuestion1.jsp");
}
}
catch (Throwable theException) {
logger.error(CommonUtil.toString(theException));
}
}
protected void doValidateQuestion2(HttpServletRequest req, HttpServletResponse resp)
throws Exception {
logger.info("doValidateQuestion 2");
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
if(doValidateAttemptedCount(session, resp, "./jsp/askQuestion2.jsp") == false) {
return;
}
try {
if (validateQuestions(req, resp)) {
logger.info("answer is correct");
resetUserStoredAttemptedCount((String)req.getSession().getAttribute(Constants.USERNAME)); //CADSRPASSW-42
resp.sendRedirect("./jsp/askQuestion3.jsp");
} else {
logger.info("security question answered wrongly");
updateUserStoredAttemptedCount((String)session.getAttribute(Constants.USERNAME)); //CADSRPASSW-42
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.130"));
resp.sendRedirect("./jsp/askQuestion2.jsp");
}
}
catch (Throwable theException) {
logger.error(CommonUtil.toString(theException));
}
}
protected void doValidateQuestion3(HttpServletRequest req, HttpServletResponse resp)
throws Exception {
logger.info("doValidateQuestion 3");
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
if(doValidateAttemptedCount(session, resp, "./jsp/askQuestion3.jsp") == false) {
return;
}
try {
if (validateQuestions(req, resp)) {
logger.info("answer is correct");
resetUserStoredAttemptedCount((String)req.getSession().getAttribute(Constants.USERNAME)); //CADSRPASSW-42
resp.sendRedirect("./jsp/resetPassword.jsp");
} else {
logger.info("security question answered wrongly");
updateUserStoredAttemptedCount((String)session.getAttribute(Constants.USERNAME)); //CADSRPASSW-42
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.130"));
resp.sendRedirect("./jsp/askQuestion3.jsp");
}
}
catch (Throwable theException) {
logger.error(CommonUtil.toString(theException));
}
}
protected boolean validateQuestions(HttpServletRequest req, HttpServletResponse resp)
throws Exception {
HttpSession session = req.getSession(false);
// Map<?, ?> userQuestions = (HashMap<?, ?>) session.getAttribute(Constants.ALL_QUESTIONS);
// Map<?, ?> userAnswers = (HashMap<?, ?>) session.getAttribute(Constants.ALL_ANSWERS);
//begin CADSRPASSW-43
Map<String, String> userQuestions = new HashMap<String, String>();
Map<String, String> userAnswers = new HashMap<String, String>();
String username = (String)session.getAttribute(Constants.USERNAME);
//pull all questions related to this user
loadUserStoredQna(username, userQuestions, userAnswers);
//end CADSRPASSW-43
logger.info("questions " + userQuestions != null?userQuestions.size():0 + " answers " + userAnswers.size());
String question1 = req.getParameter("question");
String answer1 = req.getParameter("answer");
String answerIndex = req.getParameter("answerIndex");
logger.debug("doValidateQuestions: (" + question1 + ")=" + answer1);
boolean validated = false;
//get user's stored answer related to the question selected
String expectedAnswer = (String)userAnswers.get(answerIndex); //md5 approach
// String expectedAnswer = CommonUtil.decode((String)userAnswers.get(answerIndex)); //encryption approach
// if(correctAnswer != null && correctAnswer.equals(answer1)) { //plain text
// validated = true;
// String providedAnswer = CommonUtil.pad(answer1, DAO.MAX_ANSWER_LENGTH); //encryption approach
String providedAnswer = CommonUtil.encode(answer1);
validated = expectedAnswer.equals(providedAnswer);
return validated;
}
protected void doChangePassword2(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.info("doChangePassword");
try {
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
String username = req.getParameter("userid");
if(username != null) {
username = username.toUpperCase();
}
String newPassword = req.getParameter("newpswd1");
// Security enhancement
String question1 = (String)req.getParameter("question1");
String answer1 = (String)req.getParameter("answer1");
String question2 = (String)req.getParameter("question2");
String answer2 = (String)req.getParameter("answer2");
String question3 = (String)req.getParameter("question3");
String answer3 = (String)req.getParameter("answer3");
logger.debug("changing request: " + question1 + "=" + answer1 + " " +question2 + "=" + answer2 + " " +question3 + "=" + answer3);
logger.debug("username " + username);
String status = doValidateAccountStatus(username, session, req, resp, "./jsp/resetPassword.jsp");
if(status.indexOf(Constants.LOCKED_STATUS) > -1) {
return;
}
connect();
PasswordChangeDAO changeDAO = new PasswordChangeDAO(datasource);
Result passwordChangeResult = changeDAO.resetPassword(username, newPassword);
disconnect();
if (passwordChangeResult.getResultCode() == ResultCode.PASSWORD_CHANGED) {
logger.info("password reset");
resetUserStoredAttemptedCount(username); //CADSRPASSW-42
logger.debug("answer count reset");
session.invalidate(); // they are done, log them out
resp.sendRedirect("./jsp/passwordChanged.jsp");
} else {
logger.info("password change failed");
String errorMessage = passwordChangeResult.getMessage();
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, errorMessage);
resp.sendRedirect("./jsp/resetPassword.jsp");
}
}
catch (Throwable theException) {
logger.error(CommonUtil.toString(theException));
}
}
protected void doChangePassword(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.info("doChangePassword");
try {
HttpSession session = req.getSession(false);
if (session == null) {
logger.debug("null session");
// this shouldn't happen, make the user start over
resp.sendRedirect("./jsp/loggedOut.jsp");
return;
}
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, "");
String username = req.getParameter("userid");
if(username != null) {
username = username.toUpperCase();
}
String oldPassword = req.getParameter("pswd");
String newPassword = req.getParameter("newpswd1");
String newPassword2 = req.getParameter("newpswd2");
logger.debug("passwordChange:username " + username);
String status = doValidateAccountStatus(username, session, req, resp, "./jsp/changePassword.jsp");
if(status.indexOf(Constants.LOCKED_STATUS) > -1) {
return;
}
//CADSRPASSW-50
if(status.equals(Constants.EXPIRED_STATUS)) {
connect();
PasswordChangeDAO userDAO = new PasswordChangeDAO(datasource);
try {
if(!userDAO.checkValidUser(username)) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101"));
resp.sendRedirect("./jsp/changePassword.jsp");
return;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
disconnect();
}
} else {
UserBean userBean = null;
connect();
PasswordChangeDAO loginDAO = new PasswordChangeDAO(datasource);
userBean = loginDAO.checkValidUser(username, oldPassword);
disconnect();
session.setAttribute(UserBean.USERBEAN_SESSION_ATTRIBUTE, userBean);
logger.debug ("validUser " + userBean.isLoggedIn());
logger.debug ("resultCode " + userBean.getResult().getResultCode().toString());
if (!userBean.isLoggedIn()) {
String errorMessage1 = userBean.getResult().getMessage();
logger.debug ("errorMessage " + errorMessage1);
if(userBean.getResult().getResultCode() != ResultCode.LOCKED_OUT) {
//CADSRPASSW-60
status = doValidateAccountStatus(username, session, req, resp, "./jsp/changePassword.jsp");
if(status.indexOf(Constants.LOCKED_STATUS) > -1) {
return;
}
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.102"));
} else {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.103"));
}
resp.sendRedirect("./jsp/changePassword.jsp");
return;
}
}
//begin CADSRPASSW-16
// Map<String, String> userQuestions = new HashMap<String, String>();
// Map<String, String> userAnswers = new HashMap<String, String>();
// loadUserStoredQna(username, userQuestions, userAnswers);
// if(userQuestions.size() == 0) {
// logger.info("no security question found");
// String msg = Messages.getString("PasswordChangeHelper.136");
// session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, msg);
// resp.sendRedirect("./jsp/changePassword.jsp");
// return;
//end CADSRPASSW-16
if(Messages.getString("PasswordChangeHelper.3").equals(PasswordChangeHelper.validateChangePassword(username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.3"));
resp.sendRedirect("./jsp/changePassword.jsp");
return;
}
if(Messages.getString("PasswordChangeHelper.4").equals(PasswordChangeHelper.validateChangePassword(username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.4"));
resp.sendRedirect("./jsp/changePassword.jsp");
return;
}
if(Messages.getString("PasswordChangeHelper.5").equals(PasswordChangeHelper.validateChangePassword(username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) {
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.5"));
resp.sendRedirect("./jsp/changePassword.jsp");
return;
}
// if(Messages.getString("PasswordChangeHelper.6").equals(PasswordChangeHelper.validateChangePassword(username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) {
// session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.6"));
// resp.sendRedirect("./jsp/changePassword.jsp");
// return;
if(Messages.getString("PasswordChangeHelper.7").equals(PasswordChangeHelper.validateChangePassword(username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) {
logger.debug("entered username doesn't match session " + username + " " + req.getParameter("userid").toUpperCase());
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.7"));
resp.sendRedirect("./jsp/changePassword.jsp");
return;
}
if(Messages.getString("PasswordChangeHelper.8").equals(PasswordChangeHelper.validateChangePassword(username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) {
logger.debug("new password mis-typed");
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.8"));
resp.sendRedirect("./jsp/changePassword.jsp");
return;
}
connect();
PasswordChangeDAO changeDAO = new PasswordChangeDAO(datasource);
Result passwordChangeResult = changeDAO.changePassword(username, oldPassword, newPassword);
disconnect();
if (passwordChangeResult.getResultCode() == ResultCode.PASSWORD_CHANGED) {
logger.info("password changed");
resetUserStoredAttemptedCount(username); //CADSRPASSW-42
logger.debug("answer count reset");
session.invalidate(); // they are done, log them out
resp.sendRedirect("./jsp/passwordChanged.jsp");
} else {
logger.info("password change failed");
String errorMessage = passwordChangeResult.getMessage();
session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, errorMessage);
resp.sendRedirect("./jsp/changePassword.jsp");
}
}
catch (Throwable theException) {
logger.error(theException);
}
}
private boolean loadUserStoredQna(String username, Map<String, String> userQuestions, Map<String, String> userAnswers) {
UserSecurityQuestion qna = new UserSecurityQuestion();
boolean retVal = false;
try {
connect();
PasswordChangeDAO dao = new PasswordChangeDAO(datasource);
qna = dao.findByUaName(username);
if(qna != null) {
userQuestions.put(Constants.Q1, qna.getQuestion1());
userQuestions.put(Constants.Q2, qna.getQuestion2());
userQuestions.put(Constants.Q3, qna.getQuestion3());
userAnswers.put(Constants.A1, qna.getAnswer1());
userAnswers.put(Constants.A2, qna.getAnswer2());
userAnswers.put(Constants.A3, qna.getAnswer3());
retVal = true;
}
} catch(Exception e) {
e.printStackTrace();
} finally {
disconnect();
}
return retVal;
}
public static void initProperties() {
if(HELP_LINK == null) {
connect();
PasswordChangeDAO dao = new PasswordChangeDAO(datasource);
HELP_LINK = dao.getToolProperty(Constants.TOOL_NAME, Constants.HELP_LINK_PROPERTY);
LOGO_LINK = dao.getToolProperty(Constants.TOOL_NAME, Constants.LOGO_LINK_PROPERTY);
PropertyHelper.setHELP_LINK(HELP_LINK);
PropertyHelper.setLOGO_LINK(LOGO_LINK);
PropertyHelper.setEMAIL_ID(dao.getToolProperty("SENTINEL", "EMAIL.HOST.USER"));
PropertyHelper.setEMAIL_PWD(dao.getToolProperty("SENTINEL", "EMAIL.HOST.PSWD"));
// disconnect();
}
}
@Override
public void init() throws ServletException {
super.init();
logger.debug("init");
logger.info("database property:" + PropertyHelper.getDatabaseUserID() + "/" + PropertyHelper.getDatabasePassword().substring(0, 3) + "xxxxx");
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.debug("init(ServletConfig config)");
}
} |
package ca.gc.ip346.classification.resource;
import static com.google.common.net.HttpHeaders.ACCEPT;
import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS;
import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS;
import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN;
import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.common.net.HttpHeaders.ORIGIN;
import static com.google.common.net.HttpHeaders.X_REQUESTED_WITH;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.combine;
import static com.mongodb.client.model.Updates.currentDate;
import static com.mongodb.client.model.Updates.set;
import static javax.ws.rs.HttpMethod.DELETE;
import static javax.ws.rs.HttpMethod.GET;
import static javax.ws.rs.HttpMethod.HEAD;
import static javax.ws.rs.HttpMethod.OPTIONS;
import static javax.ws.rs.HttpMethod.POST;
import static javax.ws.rs.HttpMethod.PUT;
import static org.apache.logging.log4j.Level.DEBUG;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures;
import com.google.gson.GsonBuilder;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
// import ca.gc.ip346.classification.model.Added;
import ca.gc.ip346.classification.model.CanadaFoodGuideFoodItem;
import ca.gc.ip346.classification.model.CfgFilter;
import ca.gc.ip346.classification.model.CfgTier;
import ca.gc.ip346.classification.model.ContainsAdded;
import ca.gc.ip346.classification.model.Dataset;
import ca.gc.ip346.classification.model.Missing;
import ca.gc.ip346.classification.model.PseudoBoolean;
import ca.gc.ip346.classification.model.PseudoDouble;
import ca.gc.ip346.classification.model.PseudoInteger;
import ca.gc.ip346.classification.model.PseudoString;
import ca.gc.ip346.classification.model.RecipeRolled;
import ca.gc.ip346.util.ClassificationProperties;
import ca.gc.ip346.util.DBConnection;
import ca.gc.ip346.util.MongoClientFactory;
import ca.gc.ip346.util.RequestURI;
@Path("/datasets")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class FoodsResource {
private static final Logger logger = LogManager.getLogger(FoodsResource.class);
private Connection conn = null;
private DatabaseMetaData meta = null;
private MongoClient mongoClient = null;
private MongoCollection<Document> collection = null;
@Context
private HttpServletRequest request;
public FoodsResource() {
mongoClient = MongoClientFactory.getMongoClient();
collection = mongoClient.getDatabase(MongoClientFactory.getDatabase()).getCollection(MongoClientFactory.getCollection());
try {
conn = DBConnection.getConnection();
} catch(Exception e) {
// TODO: proper response to handle exceptions
logger.debug("[01;03;31m" + e.getMessage() + "[00;00;00m");
logger.debug("[01;03;31m" + e.getMessage() + "[00;00;00m");
}
}
@OPTIONS
@Path("/search")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response getFoodListPreflight() {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "options-catch-all");
return getResponse(OPTIONS, Response.Status.OK, msg);
}
@GET
@Path("/search")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public /* List<CanadaFoodGuideFoodItem> */ Response getFoodList(@BeanParam CfgFilter search) {
String sql = ContentHandler.read("canada_food_guide_food_item.sql", getClass());
search.setSql(sql);
mongoClient.close();
return doSearchCriteria(search);
}
@OPTIONS
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response saveDatasetPreflight() {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "options-catch-all");
return getResponse(OPTIONS, Response.Status.OK, msg);
}
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public /* Map<String, Object> */ Response saveDataset(Dataset dataset) {
ResponseBuilder response = null;
Status status = null;
Map<String, Object> map = new HashMap<String, Object>();
if (dataset.getData() != null && dataset.getName() != null && dataset.getName() != null) {
Document doc = new Document()
.append("data", dataset.getData())
.append("name", dataset.getName())
.append("env", dataset.getEnv())
.append("owner", dataset.getOwner())
.append("status", dataset.getStatus())
.append("comments", dataset.getComments());
collection.insertOne(doc);
ObjectId id = (ObjectId)doc.get("_id");
collection.updateOne(
eq("_id", id),
combine(
set("name", dataset.getName()),
set("comments", dataset.getComments()),
currentDate("modifiedDate"))
);
logger.debug("[01;34mLast inserted Dataset id: " + id + "[00;00m");
logger.debug("[01;34mCurrent number of Datasets: " + collection.count() + "[00;00m");
map.put("id", id.toString());
logger.debug("[01;34m" + Response.Status.CREATED.getStatusCode() + " " + Response.Status.CREATED.toString() + "[00;00m");
status = Response.Status.CREATED;
response = Response.status(status);
} else {
List<String> list = new ArrayList<String>();
if (dataset.getData() == null) list.add("data");
if (dataset.getName() == null) list.add("name");
if (dataset.getEnv() == null) list.add("env");
if (dataset.getComments() == null) list.add("comments");
map.put("code", Response.Status.BAD_REQUEST.getStatusCode());
map.put("description", Response.Status.BAD_REQUEST.toString() + " - Unable to insert Dataset!");
map.put("fields", StringUtils.join(list, ", "));
logger.debug("[01;34m" + Response.Status.BAD_REQUEST.toString() + " - Unable to insert Dataset!" + "[00;00m");
logger.debug("[01;34m" + Response.Status.BAD_REQUEST.getStatusCode() + " " + Response.Status.BAD_REQUEST.toString() + "[00;00m");
status = Response.Status.BAD_REQUEST;
response = Response.status(status);
}
// mongoClient.close();
logger.debug("[01;31m" + "response status: " + response.build().getStatusInfo() + "[00;00m");
return getResponse(POST, status, map);
}
// @OPTIONS
// @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
// @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
// public Response getDatasetsPreflight() {
// Map<String, String> msg = new HashMap<String, String>();
// msg.put("message", "options-catch-all");
// return getResponse(OPTIONS, Response.Status.OK, msg);
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public /* List<Map<String, String>> */ Response getDatasets(@QueryParam("env") String env) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
MongoCursor<Document> cursorDocMap = collection.find(eq("env", env)).iterator();
while (cursorDocMap.hasNext()) {
Map<String, String> map = new HashMap<String, String>();
Document doc = cursorDocMap.next();
map.put("id", doc.get("_id").toString());
if (doc.get("name" ) != null) map.put("name", doc.get("name" ).toString());
if (doc.get("env" ) != null) map.put("env", doc.get("env" ).toString());
if (doc.get("owner" ) != null) map.put("owner", doc.get("owner" ).toString());
if (doc.get("status" ) != null) map.put("status", doc.get("status" ).toString());
if (doc.get("comments" ) != null) map.put("comments", doc.get("comments" ).toString());
if (doc.get("modifiedDate") != null) map.put("modifiedDate", doc.get("modifiedDate").toString());
list.add(map);
logger.debug("[01;34mDataset ID: " + doc.get("_id") + "[00;00m");
}
logger.debug("[01;31m" + "request URI : " + RequestURI.getUri() + "[00;00m");
logger.debug("[01;31m" + "request URI : " + request.getRequestURI() + "[00;00m");
logger.debug("[01;31m" + "request URL : " + request.getRequestURL() + "[00;00m");
logger.debug("[01;31m" + "request Name : " + request.getServerName() + "[00;00m");
logger.debug("[01;31m" + "request Port : " + request.getServerPort() + "[00;00m");
logger.debug("[01;31m" + "request Protocol : " + request.getProtocol() + "[00;00m");
mongoClient.close();
return getResponse(GET, Response.Status.OK, list);
}
@GET
@Path("/{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public /* List<Map<String, Object>> */ Response getDataset(@PathParam("id") String id) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
MongoCursor<Document> cursorDocMap = null;
if (ObjectId.isValid(id)) {
System.out.println("[01;31m" + "Valid hexadecimal representation of ObjectId " + id + "[00;00m");
cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator();
} else {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Invalid hexadecimal representation of ObjectId " + id + "");
System.out.println("[01;31m" + "Invalid hexadecimal representation of ObjectId " + id + "[00;00m");
mongoClient.close();
return getResponse(GET, Response.Status.BAD_REQUEST, msg);
}
if (!cursorDocMap.hasNext()) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Dataset with ID " + id + " does not exist!");
logger.debug("[01;34m" + "Dataset with ID " + id + " does not exist!" + "[00;00m");
mongoClient.close();
return getResponse(GET, Response.Status.NOT_FOUND, msg);
}
while (cursorDocMap.hasNext()) {
Map<String, Object> map = new HashMap<String, Object>();
Document doc = cursorDocMap.next();
logger.debug("[01;34mDataset ID: " + doc.get("_id") + "[00;00m");
if (doc != null) {
map.put("id", id);
map.put("data", doc.get("data"));
map.put("name", doc.get("name"));
map.put("env", doc.get("env"));
map.put("owner", doc.get("owner"));
map.put("status", doc.get("status"));
map.put("comments", doc.get("comments"));
map.put("modifiedDate", doc.get("modifiedDate"));
list.add(map);
}
}
mongoClient.close();
return getResponse(GET, Response.Status.OK, list.get(0));
}
@OPTIONS
@Path("/{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response deleteDatasetPreflight() {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "options-catch-all");
return getResponse(OPTIONS, Response.Status.OK, msg);
}
@DELETE
@Path("/{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response deleteDataset(@PathParam("id") String id) {
MongoCursor<Document> cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator();
if (!cursorDocMap.hasNext()) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Dataset with ID " + id + " does not exist!");
logger.debug("[01;34m" + "Dataset with ID " + id + " does not exist!" + "[00;00m");
mongoClient.close();
return getResponse(DELETE, Response.Status.NOT_FOUND, msg);
}
while (cursorDocMap.hasNext()) {
Document doc = cursorDocMap.next();
logger.debug("[01;34mDataset ID: " + doc.get("_id") + "[00;00m");
collection.deleteOne(doc);
}
mongoClient.close();
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Successfully deleted dataset with ID: " + id);
return getResponse(DELETE, Response.Status.OK, msg);
}
@DELETE
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response deleteAllDatasets() {
collection.deleteMany(new Document());
mongoClient.close();
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Successfully deleted all datasets");
return getResponse(DELETE, Response.Status.OK, msg);
}
@PUT
@Path("/{id}")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response updateDataset(@PathParam("id") String id, Dataset dataset) {
Map<Integer, Map<String, Object>> original_values_map = new HashMap<Integer, Map<String, Object>>();
Map<Integer, Map<String, Object>> toupdate_values_map = new HashMap<Integer, Map<String, Object>>();
List<Object> list = null;
List<Bson> firstLevelSets = new ArrayList<Bson>();
int changes = 0;
// retrive the corresponding dataset with the given id
MongoCursor<Document> cursorDocMap = null;
if (ObjectId.isValid(id)) {
System.out.println("[01;31m" + "Valid hexadecimal representation of ObjectId " + id + "[00;00m");
cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator();
} else {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Invalid hexadecimal representation of ObjectId " + id + "");
System.out.println("[01;31m" + "Invalid hexadecimal representation of ObjectId " + id + "[00;00m");
mongoClient.close();
return getResponse(PUT, Response.Status.BAD_REQUEST, msg);
}
if (!cursorDocMap.hasNext()) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Dataset with ID " + id + " does not exist!");
logger.debug("[01;34m" + "Dataset with ID " + id + " does not exist!" + "[00;00m");
mongoClient.close();
return getResponse(PUT, Response.Status.NOT_FOUND, msg);
}
while (cursorDocMap.hasNext()) {
Document doc = cursorDocMap.next();
list = castList(doc.get("data"), Object.class);
for (Object obj : list) {
Map<?, ?> mObj = (Map<?, ?>)obj;
Map<String, Object> tmp = new HashMap<String, Object>();
Iterator<?> it = mObj.keySet().iterator();
while (it.hasNext()) {
String key = (String)it.next();
tmp.put(key, mObj.get(key));
}
original_values_map.put((Integer)tmp.get("code"), tmp);
}
logger.debug("[01;31mUpdate: " + "casting property 'data' seems to have passed!" + "[00;00m");
if (dataset.getName() != null && !dataset.getName().equals(doc.get("name"))) {
firstLevelSets.add(set("name", dataset.getName()));
++changes;
}
if (dataset.getEnv() != null && !dataset.getEnv().equals(doc.get("env"))) {
firstLevelSets.add(set("env", dataset.getEnv()));
++changes;
}
if (dataset.getOwner() != null && !dataset.getOwner().equals(doc.get("owner"))) {
firstLevelSets.add(set("owner", dataset.getOwner()));
++changes;
}
if (dataset.getStatus() != null && !dataset.getStatus().equals(doc.get("status"))) {
firstLevelSets.add(set("status", dataset.getStatus()));
++changes;
}
if (dataset.getComments() != null && !dataset.getComments().equals(doc.get("comments"))) {
firstLevelSets.add(set("comments", dataset.getComments()));
++changes;
}
}
List<Map<String, Object>> updates = dataset.getData();
for (Map<String, Object> map : updates) {
toupdate_values_map.put((Integer)map.get("code"), map);
logger.debug("[01;34mDataset: " + toupdate_values_map.get(map.get("code")) + "[00;00m");
logger.debug("[01;31mname: " + toupdate_values_map.get(map.get("code")).get("name") + "[00;00m");
}
Map<String, String> updateDatePair = new HashMap<String, String>();
updateDatePair.put("cfgCode", "cfgCodeUpdateDate" );
updateDatePair.put("comments", "" );
updateDatePair.put("containsAddedFat", "containsAddedFatUpdateDate" );
updateDatePair.put("containsAddedSodium", "containsAddedSodiumUpdateDate" );
updateDatePair.put("containsAddedSugar", "containsAddedSugarUpdateDate" );
updateDatePair.put("containsAddedTransfat", "containsAddedTransfatUpdateDate" );
updateDatePair.put("containsCaffeine", "containsCaffeineUpdateDate" );
updateDatePair.put("containsFreeSugars", "containsFreeSugarsUpdateDate" );
updateDatePair.put("containsSugarSubstitutes", "containsSugarSubstitutesUpdateDate" );
updateDatePair.put("foodGuideServingG", "foodGuideUpdateDate" );
updateDatePair.put("foodGuideServingMeasure", "foodGuideUpdateDate" );
updateDatePair.put("marketedToKids", "" );
updateDatePair.put("overrideSmallRaAdjustment", "" );
updateDatePair.put("replacementCode", "" );
updateDatePair.put("rolledUp", "rolledUpUpdateDate" );
updateDatePair.put("satfatAmountPer100g", "satfatImputationDate" );
updateDatePair.put("satfatImputationReference", "satfatImputationDate" );
updateDatePair.put("sodiumAmountPer100g", "sodiumImputationDate" );
updateDatePair.put("sodiumImputationReference", "sodiumImputationDate" );
updateDatePair.put("sugarAmountPer100g", "sugarImputationDate" );
updateDatePair.put("sugarImputationReference", "sugarImputationDate" );
updateDatePair.put("tier4ServingG", "tier4ServingUpdateDate" );
updateDatePair.put("tier4ServingMeasure", "tier4ServingUpdateDate" );
updateDatePair.put("totalFatAmountPer100g", "totalFatImputationDate" );
updateDatePair.put("totalFatImputationReference", "totalFatImputationDate" );
updateDatePair.put("transfatAmountPer100g", "transfatImputationDate" );
updateDatePair.put("transfatImputationReference", "transfatImputationDate" );
logger.debug(new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(updateDatePair));
for (Map<String, Object> map : updates) {
List<Bson> sets = new ArrayList<Bson>();
logger.debug("[01;31msize: " + sets.size() + "[00;00m");
if (toupdate_values_map.get(map.get("code")).get("name") != null && !toupdate_values_map .get (map .get ("code")) .get ("name") .equals (original_values_map .get (map .get ("code")) .get ("name"))) {
sets.add(set("data.$.name", map.get("name")));
++changes;
logger.debug("[01;31mvalue changed: " + map.get("name") + "[00;00m");
}
if (toupdate_values_map .get (map .get ("code")) .get ("cnfGroupCode") != null && !toupdate_values_map .get (map .get ("code")) .get ("cnfGroupCode") .equals (original_values_map .get (map .get ("code")) .get ("cnfGroupCode"))) {
sets.add(set("data.$.cnfGroupCode", map.get("cnfGroupCode")));
++changes;
logger.debug("[01;31mvalue changed: " + map.get("cnfGroupCode") + "[00;00m");
}
for (String key : updateDatePair.keySet()) {
changes = updateIfModified(key, updateDatePair.get(key), sets, changes, original_values_map, toupdate_values_map, map);
}
if (toupdate_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("energyKcal") != null && !toupdate_values_map .get (map .get ("code")) .get ("energyKcal") .equals (original_values_map .get (map .get ("code")) .get ("energyKcal"))) {
sets.add(set("data.$.energyKcal", map.get("energyKcal")));
++changes;
logger.debug("[01;31mvalue changed: " + map.get("energyKcal") + "[00;00m");
}
logger.debug("[01;03;31m" + "before: " + original_values_map .get (map .get ("code")) .get ("validated") + " - validated" + "[00;00m");
logger.debug("[01;03;31m" + " after: " + toupdate_values_map .get (map .get ("code")) .get ("validated") + " - validated" + "[00;00m");
if (toupdate_values_map .get (map .get ("code")) .get ("validated") != null && !toupdate_values_map .get (map .get ("code")) .get ("validated") .equals (original_values_map .get (map .get ("code")) .get ("validated"))) {
sets.add(set("data.$.validated", map.get("validated")));
++changes;
logger.debug("[01;31mvalue changed: " + map.get("validated") + "[00;00m");
}
if (toupdate_values_map .get (map .get ("code")) .get ("sodiumImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("sodiumImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("sodiumImputationDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("sugarImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("sugarImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("sugarImputationDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("transfatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("transfatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("transfatImputationDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("satfatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("satfatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("satfatImputationDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("totalFatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("totalFatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("totalFatImputationDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountG") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountG") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountG"))) {
sets.add(set("data.$.referenceAmountG", map.get("referenceAmountG")));
sets.add(currentDate("data.$.referenceAmountUpdateDate"));
++changes;
logger.debug("[01;31mvalue changed: " + map.get("referenceAmountG") + "[00;00m");
}
if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountMeasure") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountMeasure") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountMeasure"))) {
sets.add(set("data.$.referenceAmountMeasure", map.get("referenceAmountMeasure")));
++changes;
logger.debug("[01;31mvalue changed: " + map.get("referenceAmountMeasure") + "[00;00m");
}
if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate"))) {
}
if (toupdate_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate"))) {
}
// if (toupdate_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment") != null && !toupdate_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment") .equals (original_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment"))) {
// sets.add(set("data.$.overrideSmallRaAdjustment", map.get("overrideSmallRaAdjustment")));
// ++changes;
// logger.debug("[01;31mvalue changed: " + map.get("overrideSmallRaAdjustment") + "[00;00m");
if (toupdate_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount") != null && !toupdate_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount") .equals (original_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount"))) {
sets.add(set("data.$.adjustedReferenceAmount", map.get("adjustedReferenceAmount")));
++changes;
logger.debug("[01;31mvalue changed: " + map.get("adjustedReferenceAmount") + "[00;00m");
}
if (toupdate_values_map .get (map .get ("code")) .get ("commitDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("commitDate") .equals (original_values_map .get (map .get ("code")) .get ("commitDate"))) {
}
logger.debug("[01;31msize: " + sets.size() + "[00;00m");
logger.debug("[01;35mcode: " + map.get("code") + "[00;00m");
if (sets.size() > 0) {
collection.updateOne(and(eq("_id", new ObjectId(id)), eq("data.code", map.get("code"))), combine(sets));
}
}
if (changes != 0) {
firstLevelSets.add(currentDate("modifiedDate"));
collection.updateOne(eq("_id", new ObjectId(id)), combine(firstLevelSets));
}
mongoClient.close();
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Successfully updated dataset");
return getResponse(PUT, Response.Status.OK, msg);
}
@OPTIONS
@Path("/classify")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response classifyDatasetPreflightOne(Dataset dataset) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "options-catch-all");
return getResponse(OPTIONS, Response.Status.OK, msg);
}
@POST
@Path("/classify")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response classifyDataset(Dataset dataset) {
Response response = null;
Map<String, String> msg = new HashMap<String, String>();
if (dataset.getEnv().equals("sandbox")) {
/**
*
* first, create a new transient dataset
*
*/
Map<?, ?> tmp = (Map<?, ?>)saveDataset(dataset).getEntity();
Map<String, String> map = new HashMap<String, String>();
for (Entry<?, ?> entry : tmp.entrySet()) {
map.put((String)entry.getKey(), (String)entry.getValue());
}
String id = map.get("id");
/**
*
* second, with newly created ID, classify dataset
*
*/
response = classifyDataset(id);
/**
*
* third, delete transient dataset
*
*/
deleteDataset(id);
return response;
} else {
msg.put("message", "Invalid environment: " + dataset.getEnv() + "");
return getResponse(POST, Response.Status.BAD_REQUEST, msg);
}
}
@OPTIONS
@Path("/{id}/classify")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response classifyDatasetPreflightTwo(String id) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "options-catch-all");
return getResponse(OPTIONS, Response.Status.OK, msg);
}
@POST
@Path("/{id}/classify")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
// @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
@SuppressWarnings("unchecked")
public Response classifyDataset(@PathParam("id") String id) {
Map<String, Object> map = null;
MongoCursor<Document> cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator();
List<Object> list = null;
List<Document> dox = new ArrayList<Document>();
if (!cursorDocMap.hasNext()) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Dataset with ID " + id + " does not exist!");
logger.debug("[01;34m" + "Dataset with ID " + id + " does not exist!" + "[00;00m");
mongoClient.close();
return getResponse(POST, Response.Status.NOT_FOUND, msg);
}
/**
*
* first server-side validation: required for classification
*
*/
List<Map<String, Object>> dataToBeValidated = new ArrayList<Map<String, Object>>();
Map<String, String> requiredForClassification = new HashMap<String, String>();
requiredForClassification.put("type", "Scalar"); // Type Y CFG Indicates if the item is a Food or Recipe --
requiredForClassification.put("code", "Scalar"); // Code Y CNF/NSS CNF Food Code or NSS Recipe Code --
requiredForClassification.put("name", "Scalar"); // Name Y CNF/NSS Food or Recipe Name --
requiredForClassification.put("cfgCode", "Object"); // CFG Code Y (at least three digits) CFG Up to four digit CFG Code (includes tier, if available) --
requiredForClassification.put("sodiumAmountPer100g", "Object"); // Sodium Amount (per 100g) Y CNF/NSS Amount of Sodium per 100 g --
requiredForClassification.put("sugarAmountPer100g", "Object"); // Sugar Amount (per 100g) Y CNF/NSS Amount of Sugar per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. --
requiredForClassification.put("satfatAmountPer100g", "Object"); // SatFat Amount (per 100g) Y CNF/NSS Amount of Saturated Fat per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. --
requiredForClassification.put("totalFatAmountPer100g", "Object"); // TotalFat Amount (per 100g) Y CNF/NSS Amount of Total Fat per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. --
// requiredForClassification.put("containsAddedSodium", "Object"); // Contains Added Sodium Y CFG Indicates if the item contains added sodium --
// requiredForClassification.put("containsAddedSugar", "Object"); // Contains Added Sugar Y CFG Indicates if the item contains added sugar --
// requiredForClassification.put("containsAddedFat", "Object"); // Contains Added Fat Y CFG Indicates if the item contains added fat --
// requiredForClassification.put("referenceAmountG", "Scalar"); // Reference Amount (g) Y CNF/NSS --
// requiredForClassification.put("toddlerItem", "Scalar"); // Toddler Item Y CFG --
// requiredForClassification.put("overrideSmallRaAdjustment", "Object"); // Override Small RA Adjustment Y CFG Overrides the Small RA Adjustment that is made for foods that have RA lower than the Small RA Threshold (ie 30g) --
while (cursorDocMap.hasNext()) {
Boolean isInvalid = false;
Document doc = cursorDocMap.next();
if (doc != null) {
list = castList(doc.get("data"), Object.class);
for (Object obj : list) {
Map<String, Object> requiredOnly = new HashMap<String, Object>();
for (String key : requiredForClassification.keySet()) {
if (requiredForClassification.get(key).equals("Object")) {
Document objectifiedValue = (Document)((Document)obj).get(key + "");
if (objectifiedValue.get("value") != null) {
requiredOnly.put(key, objectifiedValue.get("value"));
if (key.equals("cfgCode") && ((Integer)requiredOnly.get(key)).toString().length() != 3 && ((Integer)requiredOnly.get(key)).toString().length() != 4) {
isInvalid = true;
}
} else {
isInvalid = true;
}
}
if (requiredForClassification.get(key).equals("Scalar")) {
if (((Document)obj).get(key + "") != null) {
requiredOnly.put(key, ((Document)obj).get(key + ""));
} else {
isInvalid = true;
}
}
}
dataToBeValidated.add(requiredOnly);
}
}
// use validation rules on "data" property and return response if invalid
logger.debug("[01;03;31m" + "only required fields:\n" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(dataToBeValidated) + "[00;00m");
if (isInvalid) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Expected required field(s) failed to pass validation in preparation for classification.");
return getResponse(POST, Response.Status.EXPECTATION_FAILED, msg);
}
}
/**
*
* rewind dataset to do the actual classification
*
*/
cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator();
/**
*
* objectified properties
*
*/
Map<String, String> updateDatePair = new HashMap<String, String>();
updateDatePair.put("cfgCode", "cfgCodeUpdateDate" );
updateDatePair.put("comments", "" );
updateDatePair.put("containsAddedFat", "containsAddedFatUpdateDate" );
updateDatePair.put("containsAddedSodium", "containsAddedSodiumUpdateDate" );
updateDatePair.put("containsAddedSugar", "containsAddedSugarUpdateDate" );
updateDatePair.put("containsAddedTransfat", "containsAddedTransfatUpdateDate" );
updateDatePair.put("containsCaffeine", "containsCaffeineUpdateDate" );
updateDatePair.put("containsFreeSugars", "containsFreeSugarsUpdateDate" );
updateDatePair.put("containsSugarSubstitutes", "containsSugarSubstitutesUpdateDate" );
updateDatePair.put("foodGuideServingG", "foodGuideUpdateDate" );
updateDatePair.put("foodGuideServingMeasure", "foodGuideUpdateDate" );
updateDatePair.put("marketedToKids", "" );
updateDatePair.put("overrideSmallRaAdjustment", "" );
updateDatePair.put("replacementCode", "" );
updateDatePair.put("rolledUp", "rolledUpUpdateDate" );
updateDatePair.put("satfatAmountPer100g", "satfatImputationDate" );
updateDatePair.put("satfatImputationReference", "satfatImputationDate" );
updateDatePair.put("sodiumAmountPer100g", "sodiumImputationDate" );
updateDatePair.put("sodiumImputationReference", "sodiumImputationDate" );
updateDatePair.put("sugarAmountPer100g", "sugarImputationDate" );
updateDatePair.put("sugarImputationReference", "sugarImputationDate" );
updateDatePair.put("tier4ServingG", "tier4ServingUpdateDate" );
updateDatePair.put("tier4ServingMeasure", "tier4ServingUpdateDate" );
updateDatePair.put("totalFatAmountPer100g", "totalFatImputationDate" );
updateDatePair.put("totalFatImputationReference", "totalFatImputationDate" );
updateDatePair.put("transfatAmountPer100g", "transfatImputationDate" );
updateDatePair.put("transfatImputationReference", "transfatImputationDate" );
/**
*
* only transform objectified values to literal values
*
*/
while (cursorDocMap.hasNext()) {
Document doc = cursorDocMap.next();
map = new HashMap<String, Object>();
logger.debug("[01;34mDataset ID: " + doc.get("_id") + "[00;00m");
if (doc != null) {
list = castList(doc.get("data"), Object.class);
for (Object obj : list) {
for (String key : updateDatePair.keySet()) {
Document objectifiedValue = (Document)((Document)obj).get(key + "");
((Document)obj).put(key, objectifiedValue.get("value"));
}
dox.add((Document)obj);
}
map.put("data", dox);
map.put("name", doc.get("name"));
map.put("env", doc.get("env"));
map.put("owner", doc.get("owner"));
map.put("status", doc.get("status"));
map.put("comments", doc.get("comments"));
map.put("modifiedDate", doc.get("modifiedDate"));
}
}
// mongoClient.close();
String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-");
// logger.debug("[01;31m" + "request URI : " + RequestURI.getUri() + "[00;00m");
logger.debug("[01;31m" + "request URI : " + request.getRequestURI() + "[00;00m");
logger.debug("[01;31m" + "request URL : " + request.getRequestURL() + "[00;00m");
logger.debug("[01;31m" + "request target : " + request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-") + "[00;00m");
logger.debug("[01;31m" + "request Name : " + request.getServerName() + "[00;00m");
logger.debug("[01;31m" + "request Port : " + request.getServerPort() + "[00;00m");
logger.debug("[01;31m" + "request Protocol : " + request.getProtocol() + "[00;00m");
logger.debug("[01;31m" + "request target : " + target + "[00;00m");
logger.debug("[01;31m" + "adding SSL : " + target + "[00;00m");
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}
}, new java.security.SecureRandom());
} catch(NoSuchAlgorithmException nsae) {
} catch(KeyManagementException kme) {
}
Response response = ClientBuilder
.newBuilder()
.sslContext(sslContext)
.build()
.target(target)
.path("/classify")
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(map, MediaType.APPLICATION_JSON));
logger.debug("[01;31m" + "response status : " + response.getStatusInfo() + "[00;00m");
// Map<String, Object> deserialized = (Map<String, Object>)response.readEntity(Object.class);
Map<String, Object> deserialized = (Map<String, Object>)response.readEntity(new GenericType<HashMap<String, Object>>() {});
List<Object> dataArray = (List<Object>)(deserialized).get("data");
for (Object obj : dataArray) {
for (String key : updateDatePair.keySet()) {
Object value = ((Map<String, Object>)obj).get(key + "");
Map<String, Object> metadataObject = new HashMap<String, Object>();
metadataObject.put("value", value);
metadataObject.put("modified", false);
((Map<String, Object>)obj).put(key, metadataObject);
}
}
deserialized.put("id", id);
logger.debug("[01;31m" + "response status: " + ((Map<String, Object>)dataArray.get(0)).get("sodiumAmountPer100g") + "[00;00m");
logger.debug("[01;03;31m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(deserialized) + "[00;00m");
return getResponse(POST, Response.Status.OK, deserialized);
}
@POST
@Path("/{id}/flags")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response flagsDataset(@PathParam("id") String id, Dataset dataset) {
Response response = ClientBuilder
.newClient()
.target(RequestURI.getUri() + ClassificationProperties.getEndPoint())
.path("/flags")
.request()
.post(Entity.entity(dataset, MediaType.APPLICATION_JSON));
return response;
}
@POST
@Path("/{id}/init")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response initDataset(@PathParam("id") String id, Dataset dataset) {
Response response = ClientBuilder
.newClient()
.target(RequestURI.getUri() + ClassificationProperties.getEndPoint())
.path("/init")
.request()
.post(Entity.entity(dataset, MediaType.APPLICATION_JSON));
return response;
}
@POST
@Path("/{id}/adjustment")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response adjustmentDataset(@PathParam("id") String id, Dataset dataset) {
Response response = ClientBuilder
.newClient()
.target(RequestURI.getUri() + ClassificationProperties.getEndPoint())
.path("/adjustment")
.request()
.post(Entity.entity(dataset, MediaType.APPLICATION_JSON));
return response;
}
@POST
@Path("/{id}/commit")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public void commitDataset() {
}
@GET
@Path("/status")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response getStatusCodes() {
Map<Integer, String> list = new HashMap<Integer, String>();
String sql = ContentHandler.read("schema_test.sql", getClass());
Map<Integer, String> map = new HashMap<Integer, String>();
for (Response.Status obj : Response.Status.values()) {
map.put(obj.getStatusCode(), obj.name());
}
int len = 0;
for (Integer key : map.keySet()) {
String value = map.get(key);
if (value.length() > len) {
len = value.length();
}
}
String format = new StringBuffer()
.append(" %d %-")
.append(len)
.append("s")
.toString();
// String tamrof = new StringBuffer()
// .append("%-")
// .append(len + 6)
// .append("s")
// .toString();
Integer[][] arr = new Integer[6][18];
Integer[][] brr = new Integer[2][18];
Integer series = 0;
int i = 0;
int k = 0;
for (Integer key : map.keySet()) {
if (key / 100 != series) {
series = key / 100;
i = 0;
}
if (series == 4) {
brr[0][i] = key;
} else {
brr[1][k++] = key;
}
arr[series][i++] = key;
}
for (int j = 0; j < 18; ++j) {
arr[0][j] = null;
arr[1][j] = null;
}
for (int l = 0; l < 18; ++l) {
for (int m = 0; m < 2; ++m) {
Integer key = brr[m][l];
System.out.printf("[01;03;%dm" + format + "[00;00m", l % 2 == 0 ? 34 : 31, key, Response.Status.fromStatusCode(key));
}
System.out.println();
}
try {
if (conn != null) {
PreparedStatement stmt = conn.prepareStatement(sql); // Create PreparedStatement
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
list.put(rs.getInt("canada_food_guide_food_item_count"), rs.getString("canada_food_guide_food_item_desc"));
}
sql = ContentHandler.read("connectivity_test.sql", getClass());
stmt = conn.prepareStatement(sql); // Create PreparedStatement
rs = stmt.executeQuery();
while (rs.next()) {
list.put(rs.getInt("canada_food_group_id"), rs.getString("canada_food_group_desc_e"));
}
list.put(666, "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version"));
conn.close();
} else {
list.put(Response.Status.SERVICE_UNAVAILABLE.getStatusCode(), "PostgreSQL database connectivity test: failed - service unavailable");
return getResponse(GET, Response.Status.SERVICE_UNAVAILABLE, list);
}
} catch(SQLException e) {
// TODO: proper response to handle exceptions
logger.debug("[01;03;31m" + e.getMessage() + "[00;00;00m");
for (Response.Status status : Response.Status.values()) {
list.put(new Integer(status.getStatusCode()), status.getReasonPhrase());
}
list.put(666, "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version"));
}
try {
logger.debug("[01;03;31m" + "new mongo connectivity test: " + mongoClient.getAddress() + "[00;00m");
logger.debug("[01;03;31m" + "new mongo connectivity test: " + mongoClient.getConnectPoint() + "[00;00m");
logger.debug("[01;03;31m" + "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version") + "[00;00m");
} catch(Exception e) {
// TODO: proper response to handle exceptions
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", e.getMessage());
logger.debug("[01;03;31m" + e.getMessage() + "[00;00;00m");
mongoClient.close();
return getResponse(GET, Response.Status.GATEWAY_TIMEOUT, msg);
}
mongoClient.close();
// return getResponse(GET, Response.Status.OK, Response.Status.values());
return getResponse(GET, Response.Status.OK, list);
}
private /* List<CanadaFoodGuideFoodItem> */ Response doSearchCriteria(CfgFilter search) {
List<CanadaFoodGuideFoodItem> list = new ArrayList<CanadaFoodGuideFoodItem>();
if (search != null) {
StringBuffer sb = new StringBuffer(search.getSql());
logger.debug("[01;30m" + search.getDataSource() + "[00;00m");
sb.append(" WHERE length('this where-clause is an artifact') = 32").append("\n");
if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) {
sb.append(" AND type = ?").append("\n");
}
logger.debug("[01;30m" + search.getFoodRecipeName() + "[00;00m");
if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) {
sb.append(" AND LOWER(name) LIKE ?").append("\n");
}
logger.debug("[01;30m" + search.getFoodRecipeCode() + "[00;00m");
if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) {
sb.append(" AND code = ? OR CAST(code AS text) LIKE ?").append("\n");
}
logger.debug("[01;30m" + search.getCnfCode() + "[00;00m");
if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) {
sb.append(" AND cnf_group_code = ?").append("\n");
}
logger.debug("[01;30m" + search.getSubgroupCode() + "[00;00m");
if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) {
sb.append(" AND CAST(cfg_code AS text) LIKE ?").append("\n");
}
if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) {
switch (search.getCfgTier()) {
case 1:
case 2:
case 3:
case 4:
logger.debug("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 12:
case 13:
case 14:
case 23:
case 24:
case 34:
logger.debug("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 123:
case 124:
case 134:
case 234:
logger.debug("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 1234:
logger.debug("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 9:
logger.debug("[01;31mCalling all codes with missing Tier![00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) < 4").append("\n");
break;
}
}
if (search.getRecipe() != null && !search.getRecipe().equals(RecipeRolled.IGNORE.getCode())) {
logger.debug("[01;32m" + search.getRecipe() + "[00;00m");
switch (search.getRecipe()) {
case 1:
case 2:
sb.append(" AND rolled_up = ?").append("\n");
break;
case 3:
sb.append(" AND (rolled_up = 1 OR rolled_up = 2)").append("\n");
break;
}
}
boolean notIgnore = false;
if (search.getContainsAdded() != null) {
String[] arr = new String[search.getContainsAdded().size()];
arr = search.getContainsAdded().toArray(arr);
for (String i : arr) {
logger.debug("[01;32m" + i + "[00;00m");
if (!i.equals("0")) {
notIgnore = true;
}
}
}
Map<String, String> map = null;
if (search.getContainsAdded() != null && notIgnore) {
map = new HashMap<String, String>();
logger.debug("[01;32m" + search.getContainsAdded() + "[00;00m");
String[] arr = new String[search.getContainsAdded().size()];
arr = search.getContainsAdded().toArray(arr);
for (String keyValue : arr) {
StringTokenizer tokenizer = new StringTokenizer(keyValue, "=");
map.put(tokenizer.nextToken(), tokenizer.nextToken());
logger.debug("[01;32m" + keyValue + "[00;00m");
}
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
Set<String> keys = map.keySet();
for (String key : keys) {
switch (ContainsAdded.valueOf(key)) {
case sodium:
sb.append(" AND contains_added_sodium = ? ").append("\n");
break;
case sugar:
sb.append(" AND contains_added_sugar = ? ").append("\n");
break;
case fat:
sb.append(" AND contains_added_fat = ? ").append("\n");
break;
case transfat:
sb.append(" AND contains_added_transfat = ? ").append("\n");
break;
case caffeine:
sb.append(" AND contains_caffeine = ? ").append("\n");
break;
case freeSugars:
sb.append(" AND contains_free_sugars = ? ").append("\n");
break;
case sugarSubstitute:
sb.append(" AND contains_sugar_substitutes = ? ").append("\n");
break;
}
}
}
if (search.getMissingValues() != null) {
logger.debug("[01;32m" + search.getMissingValues() + "[00;00m");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(search.getMissingValues()) + "[00;00m");
for (String name : search.getMissingValues()) {
switch (Missing.valueOf(name)) {
case refAmount:
sb.append(" AND reference_amount_g IS NULL").append("\n");
break;
case cfgServing:
sb.append(" AND food_guide_serving_g IS NULL").append("\n");
break;
case tier4Serving:
sb.append(" AND tier_4_serving_g IS NULL").append("\n");
break;
case energy:
sb.append(" AND energy_kcal IS NULL").append("\n");
break;
case cnfCode:
sb.append(" AND cnf_group_code IS NULL").append("\n");
break;
case rollUp:
sb.append(" AND rolled_up IS NULL").append("\n");
break;
case sodiumPer100g:
sb.append(" AND sodium_amount_per_100g IS NULL").append("\n");
break;
case sugarPer100g:
sb.append(" AND sugar_amount_per_100g IS NULL").append("\n");
break;
case fatPer100g:
sb.append(" AND totalfat_amount_per_100g IS NULL").append("\n");
break;
case transfatPer100g:
sb.append(" AND transfat_amount_per_100g IS NULL").append("\n");
break;
case satFatPer100g:
sb.append(" AND satfat_amount_per_100g IS NULL").append("\n");
break;
case addedSodium:
sb.append(" AND contains_added_sodium IS NULL").append("\n");
break;
case addedSugar:
sb.append(" AND contains_added_sugar IS NULL").append("\n");
break;
case addedFat:
sb.append(" AND contains_added_fat IS NULL").append("\n");
break;
case addedTransfat:
sb.append(" AND contains_added_transfat IS NULL").append("\n");
break;
case caffeine:
sb.append(" AND contains_caffeine IS NULL").append("\n");
break;
case freeSugars:
sb.append(" AND contains_free_sugars IS NULL").append("\n");
break;
case sugarSubstitute:
sb.append(" AND contains_sugar_substitutes IS NULL").append("\n");
break;
}
}
}
if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
if (search.getLastUpdatedFilter() != null) {
logger.debug("[01;32m" + search.getLastUpdatedFilter() + "[00;00m");
for (String name : search.getLastUpdatedFilter()) {
switch (Missing.valueOf(name)) {
case refAmount:
sb.append(" AND reference_amount_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case cfgServing:
sb.append(" AND food_guide_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case tier4Serving:
sb.append(" AND tier_4_serving_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case energy:
case cnfCode:
break;
case rollUp:
sb.append(" AND rolled_up_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case sodiumPer100g:
sb.append(" AND sodium_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case sugarPer100g:
sb.append(" AND sugar_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case fatPer100g:
sb.append(" AND totalfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case transfatPer100g:
sb.append(" AND transfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case satFatPer100g:
sb.append(" AND satfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case addedSodium:
sb.append(" AND contains_added_sodium_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case addedSugar:
sb.append(" AND contains_added_sugar_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case addedFat:
sb.append(" AND contains_added_fat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case addedTransfat:
sb.append(" AND contains_added_transfat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case caffeine:
sb.append(" AND contains_caffeine_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case freeSugars:
sb.append(" AND contains_free_sugars_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
case sugarSubstitute:
sb.append(" AND contains_sugar_substitutes_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n");
break;
}
}
}
}
if (search.getComments() != null && !search.getComments().isEmpty()) {
sb.append(" AND LOWER(comments) LIKE ?").append("\n");
}
if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
sb.append(" AND commit_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
}
search.setSql(sb.toString());
try {
meta = conn.getMetaData(); // Create Oracle DatabaseMetaData object
logger.debug("[01;34mJDBC driver version is " + meta.getDriverVersion() + "[00;00m"); // Retrieve driver information
PreparedStatement stmt = conn.prepareStatement(search.getSql(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Create PreparedStatement
int i = 0; // keeps count of the number of placeholders
if (search != null) {
if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) {
stmt.setInt(++i, search.getDataSource().equals("food") ? 1 : 2);
}
if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) {
stmt.setString(++i, new String("%" + search.getFoodRecipeName() + "%").toLowerCase());
}
if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) {
stmt.setInt(++i, Integer.parseInt(search.getFoodRecipeCode()));
stmt.setString(++i, new String("" + search.getFoodRecipeCode() + "%"));
}
if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) {
stmt.setInt(++i, Integer.parseInt(search.getCnfCode()));
}
if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) {
stmt.setString(++i, new String("" + search.getSubgroupCode() + "%"));
}
if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) {
switch (search.getCfgTier()) {
case 1:
case 2:
case 3:
case 4:
stmt.setInt(++i, search.getCfgTier());
break;
}
}
if (search.getRecipe() != null && !search.getRecipe().equals(RecipeRolled.IGNORE.getCode())) {
switch (search.getRecipe()) {
case 1:
case 2:
stmt.setInt(++i, search.getRecipe());
break;
}
}
if (search.getContainsAdded() != null && notIgnore) {
Set<String> keys = map.keySet();
for (String key : keys) {
switch (ContainsAdded.valueOf(key)) {
case sodium:
case sugar:
case fat:
case transfat:
case caffeine:
case freeSugars:
case sugarSubstitute:
stmt.setBoolean(++i, map.get(key).equals("true"));
break;
}
}
}
if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
if (search.getLastUpdatedFilter() != null) {
logger.debug("[01;32m" + search.getLastUpdatedFilter() + "[00;00m");
for (String name : search.getLastUpdatedFilter()) {
switch (Missing.valueOf(name)) {
case refAmount:
case cfgServing:
case tier4Serving:
stmt.setString(++i, search.getLastUpdateDateFrom());
stmt.setString(++i, search.getLastUpdateDateTo());
break;
case energy:
case cnfCode:
break;
case rollUp:
case sodiumPer100g:
case sugarPer100g:
case fatPer100g:
case transfatPer100g:
case satFatPer100g:
case addedSodium:
case addedSugar:
case addedFat:
case addedTransfat:
case caffeine:
case freeSugars:
case sugarSubstitute:
stmt.setString(++i, search.getLastUpdateDateFrom());
stmt.setString(++i, search.getLastUpdateDateTo());
break;
}
}
}
}
if (search.getComments() != null && !search.getComments().isEmpty()) {
stmt.setString(++i, new String("%" + search.getComments() + "%").toLowerCase());
}
if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
stmt.setString(++i, search.getCommitDateFrom());
stmt.setString(++i, search.getCommitDateTo());
}
}
logger.debug("[01;34mSQL query to follow:\n" + stmt.toString() + "[00;00m");
ResultSet rs = stmt.executeQuery();
rs.last();
logger.debug("[01;03;31m" + rs.getRow() + " row" + (rs.getRow() == 1 ? "" : "s") + "[00;00m");
rs.beforeFirst();
while (rs.next()) {
CanadaFoodGuideFoodItem foodItem = new CanadaFoodGuideFoodItem();
foodItem.setType(rs.getInt ("type") == 1 ? "food" : "recipe" );
foodItem.setCode(rs.getInt ("code") );
foodItem.setName(rs.getString ("name") );
if (rs.getString("cnf_group_code") != null) {
foodItem.setCnfGroupCode(rs.getInt ("cnf_group_code") );
}
if (rs.getString("cfg_code") != null) {
foodItem.setCfgCode(new PseudoInteger(rs.getInt ("cfg_code")) ); // editable
} else {
foodItem.setCfgCode(new PseudoInteger() );
}
foodItem.setCommitDate(rs.getDate ("cfg_code_update_date") );
if (rs.getString("energy_kcal") != null) {
foodItem.setEnergyKcal(rs.getDouble ("energy_kcal") );
}
if (rs.getString("sodium_amount_per_100g") != null) {
foodItem.setSodiumAmountPer100g(new PseudoDouble(rs.getDouble ("sodium_amount_per_100g")) ); // editable
} else {
foodItem.setSodiumAmountPer100g(new PseudoDouble() );
}
foodItem.setSodiumImputationReference(new PseudoString(rs.getString ("sodium_imputation_reference")) );
foodItem.setSodiumImputationDate(rs.getDate ("sodium_imputation_date") );
if (rs.getString("sugar_amount_per_100g") != null) {
foodItem.setSugarAmountPer100g(new PseudoDouble(rs.getDouble ("sugar_amount_per_100g")) ); // editable
} else {
foodItem.setSugarAmountPer100g(new PseudoDouble() );
}
foodItem.setSugarImputationReference(new PseudoString(rs.getString ("sugar_imputation_reference")) );
foodItem.setSugarImputationDate(rs.getDate ("sugar_imputation_date") );
if (rs.getString("transfat_amount_per_100g") != null) {
foodItem.setTransfatAmountPer100g(new PseudoDouble(rs.getDouble ("transfat_amount_per_100g")) ); // editable
} else {
foodItem.setTransfatAmountPer100g(new PseudoDouble() );
}
foodItem.setTransfatImputationReference(new PseudoString(rs.getString ("transfat_imputation_reference")) );
foodItem.setTransfatImputationDate(rs.getDate ("transfat_imputation_date") );
if (rs.getString("satfat_amount_per_100g") != null) {
foodItem.setSatfatAmountPer100g(new PseudoDouble(rs.getDouble ("satfat_amount_per_100g")) ); // editable
} else {
foodItem.setSatfatAmountPer100g(new PseudoDouble() );
}
foodItem.setSatfatImputationReference(new PseudoString(rs.getString ("satfat_imputation_reference")) );
foodItem.setSatfatImputationDate(rs.getDate ("satfat_imputation_date") );
if (rs.getString("totalfat_amount_per_100g") != null) {
foodItem.setTotalFatAmountPer100g(new PseudoDouble(rs.getDouble ("totalfat_amount_per_100g")) ); // editable
} else {
foodItem.setTotalFatAmountPer100g(new PseudoDouble() );
}
foodItem.setTotalFatImputationReference(new PseudoString(rs.getString ("totalfat_imputation_reference")) );
foodItem.setTotalFatImputationDate(rs.getDate ("totalfat_imputation_date") );
if (rs.getString("contains_added_sodium") != null) {
foodItem.setContainsAddedSodium(new PseudoBoolean(rs.getBoolean ("contains_added_sodium")) ); // editable
} else {
foodItem.setContainsAddedSodium(new PseudoBoolean() );
}
foodItem.setContainsAddedSodiumUpdateDate(rs.getDate ("contains_added_sodium_update_date") );
if (rs.getString("contains_added_sugar") != null) {
foodItem.setContainsAddedSugar(new PseudoBoolean(rs.getBoolean ("contains_added_sugar")) ); // editable
} else {
foodItem.setContainsAddedSugar(new PseudoBoolean() );
}
foodItem.setContainsAddedSugarUpdateDate(rs.getDate ("contains_added_sugar_update_date") );
if (rs.getString("contains_free_sugars") != null) {
foodItem.setContainsFreeSugars(new PseudoBoolean(rs.getBoolean ("contains_free_sugars")) ); // editable
} else {
foodItem.setContainsFreeSugars(new PseudoBoolean() );
}
foodItem.setContainsFreeSugarsUpdateDate(rs.getDate ("contains_free_sugars_update_date") );
if (rs.getString("contains_added_fat") != null) {
foodItem.setContainsAddedFat(new PseudoBoolean(rs.getBoolean ("contains_added_fat")) ); // editable
} else {
foodItem.setContainsAddedFat(new PseudoBoolean() );
}
foodItem.setContainsAddedFatUpdateDate(rs.getDate ("contains_added_fat_update_date") );
if (rs.getString("contains_added_transfat") != null) {
foodItem.setContainsAddedTransfat(new PseudoBoolean(rs.getBoolean ("contains_added_transfat")) ); // editable
} else {
foodItem.setContainsAddedTransfat(new PseudoBoolean() );
}
foodItem.setContainsAddedTransfatUpdateDate(rs.getDate ("contains_added_transfat_update_date") );
if (rs.getString("contains_caffeine") != null) {
foodItem.setContainsCaffeine(new PseudoBoolean(rs.getBoolean ("contains_caffeine")) ); // editable
} else {
foodItem.setContainsCaffeine(new PseudoBoolean() );
}
foodItem.setContainsCaffeineUpdateDate(rs.getDate ("contains_caffeine_update_date") );
if (rs.getString("contains_sugar_substitutes") != null) {
foodItem.setContainsSugarSubstitutes(new PseudoBoolean(rs.getBoolean ("contains_sugar_substitutes")) ); // editable
} else {
foodItem.setContainsSugarSubstitutes(new PseudoBoolean() );
}
foodItem.setContainsSugarSubstitutesUpdateDate(rs.getDate ("contains_sugar_substitutes_update_date") );
if (rs.getString("reference_amount_g") != null) {
foodItem.setReferenceAmountG(rs.getDouble ("reference_amount_g") ); // editable
}
foodItem.setReferenceAmountMeasure(rs.getString ("reference_amount_measure") );
// foodItem.setReferenceAmountUpdateDate(rs.getDate ("reference_amount_update_date") );
if (rs.getString("food_guide_serving_g") != null) {
foodItem.setFoodGuideServingG(new PseudoDouble(rs.getDouble ("food_guide_serving_g")) ); // editable
} else {
foodItem.setFoodGuideServingG(new PseudoDouble() );
}
foodItem.setFoodGuideServingMeasure(new PseudoString(rs.getString ("food_guide_serving_measure")) );
foodItem.setFoodGuideUpdateDate(rs.getDate ("food_guide_update_date") );
if (rs.getString("tier_4_serving_g") != null) {
foodItem.setTier4ServingG(new PseudoDouble(rs.getDouble ("tier_4_serving_g")) ); // editable
} else {
foodItem.setTier4ServingG(new PseudoDouble() );
}
foodItem.setTier4ServingMeasure(new PseudoString(rs.getString ("tier_4_serving_measure")) );
foodItem.setTier4ServingUpdateDate(rs.getDate ("tier_4_serving_update_date") );
if (rs.getString("rolled_up") != null) {
foodItem.setRolledUp(new PseudoBoolean(rs.getBoolean ("rolled_up")) ); // editable
} else {
foodItem.setRolledUp(new PseudoBoolean() );
}
foodItem.setRolledUpUpdateDate(rs.getDate ("rolled_up_update_date") );
if (rs.getString("override_small_ra_adjustment") != null) {
foodItem.setOverrideSmallRaAdjustment(new PseudoBoolean(rs.getBoolean ("override_small_ra_adjustment")) );
} else {
foodItem.setOverrideSmallRaAdjustment(new PseudoBoolean() );
}
if (rs.getString("replacement_code") != null) {
foodItem.setReplacementCode(new PseudoInteger(rs.getInt ("replacement_code")) ); // editable
} else {
foodItem.setReplacementCode(new PseudoInteger() );
}
foodItem.setCommitDate(rs.getDate ("commit_date") );
foodItem.setComments(new PseudoString(rs.getString ("comments")) ); // editable
foodItem.setValidated( false );
list.add(foodItem);
}
conn.close();
} catch(SQLException e) {
// TODO: proper response to handle exceptions
logger.debug("[01;03;31m" + "" + e.getMessage() + "[00;00m");
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", e.getMessage());
return getResponse(GET, Response.Status.SERVICE_UNAVAILABLE, msg);
}
}
return getResponse(GET, Response.Status.OK, list);
}
public static Response getResponse(String method, Response.Status status, Object obj) {
List<String> allowedHttpOrigins = null;
List<String> allowedHttpHeaders = null;
List<String> allowedHttpMethods = null;
List<String> requestHttpMethods = null;
allowedHttpOrigins = new ArrayList<String>();
allowedHttpOrigins.add("*");
allowedHttpHeaders = new ArrayList<String>();
allowedHttpHeaders.add(ORIGIN);
allowedHttpHeaders.add(CONTENT_TYPE);
allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_HEADERS);
allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_METHODS);
allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN);
allowedHttpHeaders.add(X_REQUESTED_WITH);
allowedHttpHeaders.add(ACCEPT);
allowedHttpHeaders.add(AUTHORIZATION);
allowedHttpMethods = new ArrayList<String>();
allowedHttpMethods.add(GET);
allowedHttpMethods.add(POST);
allowedHttpMethods.add(OPTIONS);
allowedHttpMethods.add(DELETE);
allowedHttpMethods.add(PUT);
allowedHttpMethods.add(HEAD);
requestHttpMethods = new ArrayList<String>();
requestHttpMethods.add(GET);
requestHttpMethods.add(POST);
requestHttpMethods.add(OPTIONS);
requestHttpMethods.add(DELETE);
logger.printf(DEBUG, "%s%-29s: %s%s", "[01;03;31m", ACCESS_CONTROL_ALLOW_ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", "), "[00;00m");
logger.printf(DEBUG, "%s%-29s: %s%s", "[01;03;31m", ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", "), "[00;00m");
logger.printf(DEBUG, "%s%-29s: %s%s", "[01;03;31m", ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(allowedHttpMethods.toArray(), ", "), "[00;00m");
ResponseBuilder rb = Response.status(status);
// rb.header( ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", "));
// rb.header(ACCESS_CONTROL_ALLOW_ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", "));
// rb.header(ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", "));
// rb.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
// rb.header(ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(allowedHttpMethods.toArray(), ", "));
// if (method.equals(OPTIONS)) {
// rb.header(ACCESS_CONTROL_REQUEST_METHOD, StringUtils.join(requestHttpMethods.toArray(), ", "));
// rb.header(ACCESS_CONTROL_REQUEST_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", "));
// rb.header(CONTENT_TYPE, MediaType.APPLICATION_JSON);
// rb.header(ACCESS_CONTROL_MAX_AGE, "1209600");
return rb.entity(obj).build();
}
private static <T> List<T> castList(Object obj, Class<T> clazz) {
List<T> result = new ArrayList<T>();
if (obj instanceof List<?>) {
for (Object o : (List<?>)obj) {
result.add(clazz.cast(o));
}
return result;
}
return null;
}
@SuppressWarnings("unchecked")
private int updateIfModified(String key, String value, List<Bson> sets, int changes, Map<Integer, Map<String, Object>> original_values_map, Map<Integer, Map<String, Object>> toupdate_values_map, Map<String, Object> map) {
logger.debug("[01;34m" + "key/value - " + key + ": " + ((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value") + "[00;00m");
if (((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value") != null && !((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value").equals(((Map<String, Object>)original_values_map.get(map.get("code")).get(key)).get("value"))) {
sets.add(set("data.$." + key + ".value", ((Map<String, Object>)map.get(key)).get("value")));
if (!value.isEmpty()) {
sets.add(currentDate("data.$." + value));
}
++changes;
logger.debug("[01;31mvalue changed: " + ((Map<String, Object>)map.get(key)).get("value") + "[00;00m");
}
if (((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("modified") != null && !((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("modified").equals(((Map<String, Object>)original_values_map.get(map.get("code")).get(key)).get("modified"))) {
sets.add(set("data.$." + key + ".modified", ((Map<String, Object>)map.get(key)).get("modified")));
}
return changes;
}
} |
package ca.gc.ip346.classification.resource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.naming.NamingException;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;
import org.bson.types.ObjectId;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures;
// import com.google.common.base.CaseFormat;
import com.google.gson.GsonBuilder;
// import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import static com.mongodb.client.model.Filters.*;
// import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Updates.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
// import com.mongodb.util.JSON;
// import ca.gc.ip346.classification.model.Added;
import ca.gc.ip346.classification.model.CanadaFoodGuideDataset;
import ca.gc.ip346.classification.model.CfgTier;
import ca.gc.ip346.classification.model.ContainsAdded;
import ca.gc.ip346.classification.model.Dataset;
import ca.gc.ip346.classification.model.FoodItem;
import ca.gc.ip346.classification.model.Missing;
import ca.gc.ip346.classification.model.RecipeRolled;
// import ca.gc.ip346.classification.model.NewAndImprovedFoodItem;
import ca.gc.ip346.classification.model.CfgFilter;
import ca.gc.ip346.util.DBConnection;
@Path("/datasets")
// @Produces(MediaType.APPLICATION_JSON)
public class FoodsResource {
private static final Logger logger = LogManager.getLogger(FoodsResource.class);
Connection conn = null;
DatabaseMetaData meta = null;
public FoodsResource() {
try {
// Context initCtx = new InitialContext();
// Context envCtx = (Context)initCtx.lookup("java:comp/env");
// DataSource ds = (DataSource)envCtx.lookup("jdbc/FoodDB");
// conn = ds.getConnection();
conn = DBConnection.getConnections();
} catch(NamingException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
@GET
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public List<CanadaFoodGuideDataset> getFoodList(@BeanParam CfgFilter search) {
String sql = ContentHandler.read("canada_food_guide_dataset.sql", getClass());
search.setSql(sql);
return doSearchCriteria(search);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> saveDataset(Dataset dataset) {
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("cfgDb");
MongoCollection<Document> collection = database.getCollection("master");
// String sql = ContentHandler.read("canada_food_guide_dataset.sql", getClass());
// CfgFilter search = new CfgFilter();
// search.setSql(sql);
// List<CanadaFoodGuideDataset> list = doSearchCriteria(search);
// String json = ContentHandler.read("search.json", getClass());
// DBObject dbObject = (DBObject)JSON.parse(json);
// DBObject dbObject = (DBObject)JSON.parse(dataset.getData());
Document doc = new Document()
// .append("data", dbObject)
.append("data", dataset.getData())
.append("name", dataset.getName())
.append("owner", dataset.getOwner())
.append("status", dataset.getStatus())
.append("comments", dataset.getComments());
collection.insertOne(doc);
ObjectId id = (ObjectId)doc.get("_id");
collection.updateOne(eq("_id", id),
combine(set("name", dataset.getName()), set("comments", dataset.getComments()), currentDate("modifiedDate")));
logger.error("[01;34mCurrent number of Datasets: " + collection.count() + "[00;00m");
logger.error("[01;34mLast inserted Datasets _id: " + id + "[00;00m");
mongoClient.close();
Map<String, String> map = new HashMap<String, String>();
map.put("id", id.toString());
return map;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public List<Map<String, String>> getDatasets() {
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("cfgDb");
MongoCollection<Document> collection = database.getCollection("master");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
MongoCursor<Document> cursorDocMap = collection.find().iterator();
while (cursorDocMap.hasNext()) {
Map<String, String> map = new HashMap<String, String>();
Document doc = cursorDocMap.next();
map.put("id", doc.get("_id").toString());
if (doc.get("name") != null) map.put("name", doc.get("name") .toString());
if (doc.get("owner") != null) map.put("owner", doc.get("owner") .toString());
if (doc.get("status") != null) map.put("status", doc.get("status") .toString());
if (doc.get("comments") != null) map.put("comments", doc.get("comments") .toString());
if (doc.get("modifiedDate") != null) map.put("modifiedDate", doc.get("modifiedDate") .toString());
list.add(map);
logger.error("[01;34mDataset ID: " + doc.get("_id") + "[00;00m");
}
mongoClient.close();
return list;
}
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public void deleteDataset() {
}
@PUT
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public void updateDataset() {
}
@POST
@Path("/{id}/classify")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public void classifyDataset() {
}
@POST
@Path("/{id}/commit")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public void commitDataset() {
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public List<Map<String, Object>> getDataset(@PathParam("id") String id) {
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("cfgDb");
MongoCollection<Document> collection = database.getCollection("master");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
MongoCursor<Document> cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator();
while (cursorDocMap.hasNext()) {
Map<String, Object> map = new HashMap<String, Object>();
Document doc = cursorDocMap.next();
logger.error("[01;34mDataset ID: " + doc.get("_id") + "[00;00m");
if (doc != null) {
map.put("data", doc.get("data"));
map.put("name", doc.get("name"));
map.put("owner", doc.get("owner"));
map.put("status", doc.get("status"));
map.put("comments", doc.get("comments"));
map.put("modifiedDate", doc.get("modifiedDate").toString());
list.add(map);
}
}
mongoClient.close();
return list;
}
public List<FoodItem> getFoodItem(@PathParam("id") Integer id) {
List<FoodItem> list = new ArrayList<FoodItem>(); // Create list
try {
meta = conn.getMetaData(); // Create Oracle DatabaseMetaData object
logger.error("[01;34mJDBC driver version is " + meta.getDriverVersion() + "[00;00m"); // Retrieve driver information
String sql = ContentHandler.read("food_item_cnf.sql", getClass());
PreparedStatement stmt = conn.prepareStatement(sql); // Create PreparedStatement
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
FoodItem food = new FoodItem();
food.setId(rs.getInt("food_c"));
food.setName(rs.getString("eng_name"));
food.setLabel(rs.getString("food_desc"));
food.setGroup(rs.getString("group_c"));
food.setSubGroup(rs.getString("canada_food_subgroup_id"));
food.setCountryCode(rs.getString("country_c"));
list.add(food);
}
} catch(SQLException e) {
e.printStackTrace();
}
logger.error(new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(list));
return list;
}
@GET
@Path("/group/{groupId}")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public List<FoodItem> getFoodListForGroup(@PathParam("groupId") Integer groupId) {
List<FoodItem> list = new ArrayList<FoodItem>(); // Create list
try {
meta = conn.getMetaData(); // Create Oracle DatabaseMetaData object
logger.error("[01;34mJDBC driver version is " + meta.getDriverVersion() + "[00;00m"); // Retrieve driver information
String sql = ContentHandler.read("food_table_group_cnf.sql", getClass());
PreparedStatement stmt = conn.prepareStatement(sql); // Create PreparedStatement
stmt.setInt(1, groupId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
FoodItem food = new FoodItem();
food.setId(rs.getInt("food_c"));
food.setName(rs.getString("eng_name"));
food.setLabel(rs.getString("food_desc"));
food.setGroup(rs.getString("group_c"));
food.setSubGroup(rs.getString("canada_food_subgroup_id"));
food.setCountryCode(rs.getString("country_c"));
list.add(food);
}
} catch(SQLException e) {
e.printStackTrace();
}
// logger.error(new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(list));
return list;
}
@GET
@Path("/subgroup/{subgroupId}")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public List<FoodItem> getFoodListForsubGroup(@PathParam("subgroupId") Integer subgroupId) {
List<FoodItem> list = new ArrayList<FoodItem>(); // Create list
try {
meta = conn.getMetaData(); // Create Oracle DatabaseMetaData object
logger.error("[01;34mJDBC driver version is " + meta.getDriverVersion() + "[00;00m"); // Retrieve driver information
String sql = ContentHandler.read("food_table_subgroup_cnf.sql", getClass());
PreparedStatement stmt = conn.prepareStatement(sql); // Create PreparedStatement
stmt.setInt(1, subgroupId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
FoodItem food = new FoodItem();
food.setId(rs.getInt("food_c"));
food.setName(rs.getString("eng_name"));
food.setLabel(rs.getString("food_desc"));
food.setGroup(rs.getString("group_c"));
food.setSubGroup(rs.getString("canada_food_subgroup_id"));
food.setCountryCode(rs.getString("country_c"));
list.add(food);
}
} catch(SQLException e) {
e.printStackTrace();
}
// logger.error(new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(list));
return list;
}
private List<CanadaFoodGuideDataset> doSearchCriteria(CfgFilter search) {
List<CanadaFoodGuideDataset> list = new ArrayList<CanadaFoodGuideDataset>();
if (search != null) {
StringBuffer sb = new StringBuffer(search.getSql());
logger.error("[01;30m" + search.getDataSource() + "[00;00m");
sb.append(" WHERE length('this where-clause is an artifact') = 32 ").append("\n");
if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) {
sb.append(" AND type = ?").append("\n");
}
logger.error("[01;30m" + search.getFoodRecipeName() + "[00;00m");
if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) {
sb.append(" AND LOWER(name) LIKE ?").append("\n");
}
logger.error("[01;30m" + search.getFoodRecipeCode() + "[00;00m");
if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) {
sb.append(" AND code = ? OR CAST(code AS text) LIKE ?").append("\n");
}
logger.error("[01;30m" + search.getCnfCode() + "[00;00m");
if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) {
sb.append(" AND cnf_group_code = ?").append("\n");
}
logger.error("[01;30m" + search.getSubgroupCode() + "[00;00m");
if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) {
sb.append(" AND CAST(cfg_code AS text) LIKE ?").append("\n");
}
if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) {
switch (search.getCfgTier()) {
case 1:
case 2:
case 3:
case 4:
logger.error("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 12:
case 13:
case 14:
case 23:
case 24:
case 34:
logger.error("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 123:
case 124:
case 134:
case 234:
logger.error("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 1234:
logger.error("[01;31mCalling all codes with Tier " + search.getCfgTier() + "[00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n");
sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n");
break;
case 9:
logger.error("[01;31mCalling all codes with missing Tier![00;00m");
sb.append(" AND LENGTH(CAST(cfg_code AS text)) < 4").append("\n");
break;
}
}
if (search.getRecipe() != null && !search.getRecipe().equals(RecipeRolled.IGNORE.getCode())) {
logger.error("[01;32m" + search.getRecipe() + "[00;00m");
sb.append(" AND rolled_up = ?").append("\n");
}
boolean notIgnore = false;
if (search.getContainsAdded() != null) {
String[] arr = new String[search.getContainsAdded().size()];
arr = search.getContainsAdded().toArray(arr);
for (String i : arr) {
logger.error("[01;32m" + i + "[00;00m");
if (!i.equals("0")) {
notIgnore = true;
}
}
}
Map<String, String> map = null;
if (search.getContainsAdded() != null && notIgnore) {
map = new HashMap<String, String>();
logger.error("[01;32m" + search.getContainsAdded() + "[00;00m");
String[] arr = new String[search.getContainsAdded().size()];
arr = search.getContainsAdded().toArray(arr);
for (String keyValue : arr) {
StringTokenizer tokenizer = new StringTokenizer(keyValue, "=");
// map.put(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, tokenizer.nextToken()),tokenizer.nextToken());
map.put(tokenizer.nextToken(), tokenizer.nextToken());
logger.error("[01;32m" + keyValue + "[00;00m");
}
logger.error("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
Set<String> keys = map.keySet();
for (String key : keys) {
switch (ContainsAdded.valueOf(key)) {
case sodium:
sb.append(" AND contains_added_sodium = ? ").append("\n");
break;
case sugar:
sb.append(" AND contains_added_sugar = ? ").append("\n");
break;
case fat:
sb.append(" AND contains_added_fat = ? ").append("\n");
break;
case transfat:
sb.append(" AND contains_added_transfat = ? ").append("\n");
break;
case caffeine:
sb.append(" AND contains_caffeine = ? ").append("\n");
break;
case freeSugars:
sb.append(" AND contains_free_sugars = ? ").append("\n");
break;
case sugarSubstitute:
sb.append(" AND contains_sugar_substitutes = ? ").append("\n");
break;
}
}
}
if (search.getMissingValues() != null) {
logger.error("[01;32m" + search.getMissingValues() + "[00;00m");
logger.error("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(search.getMissingValues()) + "[00;00m");
for (String name : search.getMissingValues()) {
// switch (Missing.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name))) {
switch (Missing.valueOf(name)) {
case refAmount:
sb.append(" AND (reference_amount_g = NULL OR reference_amount_g = 0)") .append("\n");
break;
case cfgServing:
sb.append(" AND (food_guide_serving_g = NULL OR food_guide_serving_g = 0)") .append("\n");
break;
case tier4Serving:
sb.append(" AND (tier_4_serving_g = NULL OR tier_4_serving_g = 0)") .append("\n");
break;
case energy:
sb.append(" AND (energy_kcal = NULL OR energy_kcal = 0)") .append("\n");
break;
case cnfCode:
sb.append(" AND (cnf_group_code = NULL OR cnf_group_code = 0)") .append("\n");
break;
case rollUp:
sb.append(" AND (rolled_up = NULL OR rolled_up = 0)") .append("\n");
break;
case sodiumPer100g:
sb.append(" AND (sodium_amount_per_100g = NULL OR sodium_amount_per_100g = 0)") .append("\n");
break;
case sugarPer100g:
sb.append(" AND (sugar_amount_per_100g = NULL OR sugar_amount_per_100g = 0)") .append("\n");
break;
case fatPer100g:
sb.append(" AND (totalfat_amount_per_100g = NULL OR totalfat_amount_per_100g = 0)") .append("\n");
break;
case transfatPer100g:
sb.append(" AND (transfat_amount_per_100g = NULL OR transfat_amount_per_100g = 0)") .append("\n");
break;
case satFatPer100g:
sb.append(" AND (satfat_amount_per_100g = NULL OR satfat_amount_per_100g = 0)") .append("\n");
break;
case addedSodium:
sb.append(" AND (contains_added_sodium = NULL OR contains_added_sodium = 0)") .append("\n");
break;
case addedSugar:
sb.append(" AND (contains_added_sugar = NULL OR contains_added_sugar = 0)") .append("\n");
break;
case addedFat:
sb.append(" AND (contains_added_fat = NULL OR contains_added_fat = 0)") .append("\n");
break;
case addedTransfat:
sb.append(" AND (contains_added_transfat = NULL OR contains_added_transfat = 0)") .append("\n");
break;
case caffeine:
sb.append(" AND (contains_caffeine = NULL OR contains_caffeine = 0)") .append("\n");
break;
case freeSugars:
sb.append(" AND (contains_free_sugars = NULL OR contains_free_sugars = 0)") .append("\n");
break;
case sugarSubstitute:
sb.append(" AND (contains_sugar_substitutes = NULL OR contains_sugar_substitutes = 0)") .append("\n");
break;
}
}
}
if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
if (search.getLastUpdatedFilter() != null) {
logger.error("[01;32m" + search.getLastUpdatedFilter() + "[00;00m");
for (String name : search.getLastUpdatedFilter()) {
// switch (Missing.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name))) {
switch (Missing.valueOf(name)) {
case refAmount:
sb.append(" AND reference_amount_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case cfgServing:
sb.append(" AND food_guide_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case tier4Serving:
sb.append(" AND tier_4_serving_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case energy:
case cnfCode:
break;
case rollUp:
sb.append(" AND rolled_up_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case sodiumPer100g:
sb.append(" AND sodium_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case sugarPer100g:
sb.append(" AND sugar_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case fatPer100g:
sb.append(" AND totalfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case transfatPer100g:
sb.append(" AND transfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case satFatPer100g:
sb.append(" AND satfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case addedSodium:
sb.append(" AND contains_added_sodium_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case addedSugar:
sb.append(" AND contains_added_sugar_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case addedFat:
sb.append(" AND contains_added_fat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case addedTransfat:
sb.append(" AND contains_added_transfat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case caffeine:
sb.append(" AND contains_caffeine_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case freeSugars:
sb.append(" AND contains_free_sugars_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
case sugarSubstitute:
sb.append(" AND contains_sugar_substitutes_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
break;
}
}
}
}
if (search.getComments() != null && !search.getComments().isEmpty()) {
sb.append(" AND LOWER(comments) LIKE ?").append("\n");
}
if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
sb.append(" AND commit_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n");
}
search.setSql(sb.toString());
try {
meta = conn.getMetaData(); // Create Oracle DatabaseMetaData object
logger.error("[01;34mJDBC driver version is " + meta.getDriverVersion() + "[00;00m"); // Retrieve driver information
PreparedStatement stmt = conn.prepareStatement(search.getSql()); // Create PreparedStatement
int i = 0; // keeps count of the number of placeholders
if (search != null) {
if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) {
stmt.setInt(++i, search.getDataSource().equals("food") ? 1 : 2);
}
if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) {
stmt.setString(++i, new String("%" + search.getFoodRecipeName() + "%").toLowerCase());
}
if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) {
stmt.setInt(++i, Integer.parseInt(search.getFoodRecipeCode()));
stmt.setString(++i, new String("" + search.getFoodRecipeCode() + "%"));
}
if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) {
stmt.setInt(++i, Integer.parseInt(search.getCnfCode()));
}
if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) {
stmt.setString(++i, new String("" + search.getSubgroupCode() + "%"));
}
if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) {
switch (search.getCfgTier()) {
case 1:
case 2:
case 3:
case 4:
stmt.setInt(++i, search.getCfgTier());
break;
}
}
if (search.getRecipe() != null && !search.getRecipe(). equals (RecipeRolled.IGNORE.getCode())) {
stmt.setInt(++i, search.getRecipe());
}
if (search.getContainsAdded() != null && notIgnore) {
Set<String> keys = map.keySet();
for (String key : keys) {
switch (ContainsAdded.valueOf(key)) {
case sodium:
case sugar:
case fat:
case transfat:
case caffeine:
case freeSugars:
case sugarSubstitute:
stmt.setInt(++i, map.get(key).equals("true") ? 1 : 2);
break;
}
}
}
if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
if (search.getLastUpdatedFilter() != null) {
logger.error("[01;32m" + search.getLastUpdatedFilter() + "[00;00m");
for (String name : search.getLastUpdatedFilter()) {
// switch (Missing.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name))) {
switch (Missing.valueOf(name)) {
case refAmount:
case cfgServing:
case tier4Serving:
stmt.setString(++i, search.getLastUpdateDateFrom());
stmt.setString(++i, search.getLastUpdateDateTo());
break;
case energy:
case cnfCode:
break;
case rollUp:
case sodiumPer100g:
case sugarPer100g:
case fatPer100g:
case transfatPer100g:
case satFatPer100g:
case addedSodium:
case addedSugar:
case addedFat:
case addedTransfat:
case caffeine:
case freeSugars:
case sugarSubstitute:
stmt.setString(++i, search.getLastUpdateDateFrom());
stmt.setString(++i, search.getLastUpdateDateTo());
break;
}
}
}
}
if (search.getComments() != null && !search.getComments().isEmpty()) {
stmt.setString(++i, new String("%" + search.getComments() + "%").toLowerCase());
}
if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) {
stmt.setString(++i, search.getCommitDateFrom());
stmt.setString(++i, search.getCommitDateTo());
}
}
logger.error("[01;34mSQL query to follow:\n" + stmt.toString() + "[00;00m");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
CanadaFoodGuideDataset foodItem = new CanadaFoodGuideDataset();
foodItem.setType(rs.getInt("type") == 1 ? "food" : "recipe");
foodItem.setCode(Integer.parseInt(rs.getString("code")));
foodItem.setName(rs.getString("name"));
foodItem.setCnfGroupCode(rs.getInt("cnf_group_code"));
foodItem.setCfgCode(rs.getInt("cfg_code"));
foodItem.setCommitDate(rs.getDate("commit_date"));
foodItem.setEnergyKcal(rs.getDouble("energy_kcal"));
foodItem.setSodiumAmountPer100g(rs.getDouble("sodium_amount_per_100g"));
foodItem.setSodiumImputationReference(rs.getString("sodium_imputation_reference"));
foodItem.setSodiumImputationDate(rs.getDate("sodium_imputation_date"));
foodItem.setSugarAmountPer100g(rs.getDouble("sugar_amount_per_100g"));
foodItem.setSugarImputationReference(rs.getString("sugar_imputation_reference"));
foodItem.setSugarImputationDate(rs.getDate("sugar_imputation_date"));
foodItem.setTransfatAmountPer100g(rs.getDouble("transfat_amount_per_100g"));
foodItem.setTransfatImputationReference(rs.getString("transfat_imputation_reference"));
foodItem.setTransfatImputationDate(rs.getDate("transfat_imputation_date"));
foodItem.setSatfatAmountPer100g(rs.getDouble("satfat_amount_per_100g"));
foodItem.setSatfatImputationReference(rs.getString("satfat_imputation_reference"));
foodItem.setSatfatImputationDate(rs.getDate("satfat_imputation_date"));
foodItem.setTotalfatAmountPer100g(rs.getDouble("totalfat_amount_per_100g"));
foodItem.setTotalfatImputationReference(rs.getString("totalfat_imputation_reference"));
foodItem.setTotalfatImputationDate(rs.getDate("totalfat_imputation_date"));
foodItem.setContainsAddedSodium(rs.getInt("contains_added_sodium"));
foodItem.setContainsAddedSodiumUpdateDate(rs.getDate("contains_added_sodium_update_date"));
foodItem.setContainsAddedSugar(rs.getInt("contains_added_sugar"));
foodItem.setContainsAddedSugarUpdateDate(rs.getDate("contains_added_sugar_update_date"));
foodItem.setContainsFreeSugars(rs.getInt("contains_free_sugars"));
foodItem.setContainsFreeSugarsUpdateDate(rs.getDate("contains_free_sugars_update_date"));
foodItem.setContainsAddedFat(rs.getInt("contains_added_fat"));
foodItem.setContainsAddedFatUpdateDate(rs.getDate("contains_added_fat_update_date"));
foodItem.setContainsAddedTransfat(rs.getInt("contains_added_transfat"));
foodItem.setContainsAddedTransfatUpdateDate(rs.getDate("contains_added_transfat_update_date"));
foodItem.setContainsCaffeine(rs.getInt("contains_caffeine"));
foodItem.setContainsCaffeineUpdateDate(rs.getDate("contains_caffeine_update_date"));
foodItem.setContainsSugarSubstitutes(rs.getInt("contains_sugar_substitutes"));
foodItem.setContainsSugarSubstitutesUpdateDate(rs.getDate("contains_sugar_substitutes_update_date"));
foodItem.setReferenceAmountG(rs.getDouble("reference_amount_g"));
foodItem.setReferenceAmountMeasure(rs.getString("reference_amount_measure"));
foodItem.setReferenceAmountUpdateDate(rs.getDate("reference_amount_update_date"));
foodItem.setFoodGuideServingG(rs.getDouble("food_guide_serving_g"));
foodItem.setFoodGuideServingMeasure(rs.getString("food_guide_serving_measure"));
foodItem.setFoodGuideUpdateDate(rs.getDate("food_guide_update_date"));
foodItem.setTier4ServingG(rs.getDouble("tier_4_serving_g"));
foodItem.setTier4ServingMeasure(rs.getString("tier_4_serving_measure"));
foodItem.setTier4ServingUpdateDate(rs.getDate("tier_4_serving_update_date"));
foodItem.setRolledUp(rs.getInt("rolled_up"));
foodItem.setRolledUpUpdateDate(rs.getDate("rolled_up_update_date"));
foodItem.setApplySmallRaAdjustment(rs.getInt("apply_small_ra_adjustment"));
foodItem.setComments(rs.getString("comments"));
list.add(foodItem);
}
} catch(SQLException e) {
e.printStackTrace();
}
// logger.error(new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(list));
}
return list;
}
} |
package com.celements.lastChanged;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.bridge.event.DocumentCreatedEvent;
import org.xwiki.bridge.event.DocumentDeletedEvent;
import org.xwiki.bridge.event.DocumentUpdatedEvent;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.event.Event;
import com.xpn.xwiki.doc.XWikiDocument;
@Component("lastChange-DocumentChangesListener")
public class DocumentChangesListener implements EventListener {
private static Logger _LOGGER = LoggerFactory.getLogger(DocumentChangesListener.class);
@Requirement
ILastChangedRole lastChangedSrv;
@Override
public String getName() {
return "lastChange-DocumentChangesListener";
}
@Override
public List<Event> getEvents() {
return Arrays.<Event>asList(new DocumentCreatedEvent(), new DocumentUpdatedEvent(),
new DocumentDeletedEvent());
}
@Override
public void onEvent(Event event, Object source, Object data) {
if ((source != null) && (source instanceof XWikiDocument)) {
XWikiDocument doc = (XWikiDocument) source;
DocumentReference docRef = doc.getDocumentReference();
((LastChangedService)lastChangedSrv).invalidateCacheForSpaceRef(
docRef.getLastSpaceReference());
} else {
_LOGGER.error("onEvent failed docref '{}'", source);
}
}
} |
package com.conveyal.datatools.manager.models;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.conveyal.datatools.manager.DataManager;
import com.conveyal.datatools.manager.controllers.api.GtfsApiController;
import com.conveyal.datatools.manager.persistence.DataStore;
import com.conveyal.datatools.manager.persistence.FeedStore;
import com.conveyal.datatools.manager.utils.HashUtils;
import com.conveyal.gtfs.GTFSFeed;
import com.conveyal.gtfs.validator.json.LoadStatus;
import com.conveyal.gtfs.stats.FeedStats;
import com.conveyal.r5.common.R5Version;
import com.conveyal.r5.point_to_point.builder.TNBuilderConfig;
import com.conveyal.r5.transit.TransportNetwork;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.eventbus.EventBus;
import com.vividsolutions.jts.geom.Geometry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.geotools.geojson.geom.GeometryJSON;
import org.mapdb.Fun.Tuple2;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.conveyal.datatools.manager.models.Deployment.getOsmExtract;
import static com.conveyal.datatools.manager.utils.StringUtils.getCleanName;
import static spark.Spark.halt;
/**
* Represents a version of a feed.
* @author mattwigway
*
*/
@JsonInclude(Include.ALWAYS)
@JsonIgnoreProperties(ignoreUnknown = true)
public class FeedVersion extends Model implements Serializable {
private static final long serialVersionUID = 1L;
private static ObjectMapper mapper = new ObjectMapper();
public static final Logger LOG = LoggerFactory.getLogger(FeedVersion.class);
public static final String validationSubdir = "validation/";
static DataStore<FeedVersion> versionStore = new DataStore<>("feedversions");
private static FeedStore feedStore = new FeedStore();
static {
// set up indexing on feed versions by feed source, indexed by <FeedSource ID, version>
versionStore.secondaryKey("version", (key, fv) -> new Tuple2(fv.feedSourceId, fv.version));
}
/**
* We generate IDs manually, but we need a bit of information to do so
*/
public FeedVersion(FeedSource source) {
this.updated = new Date();
this.feedSourceId = source.id;
// ISO time
DateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmssX");
// since we store directly on the file system, this lets users look at the DB directly
this.id = getCleanName(source.name) + "-" + df.format(this.updated) + "-" + source.id + ".zip";
// infer the version
// FeedVersion prev = source.getLatest();
// if (prev != null) {
// this.version = prev.version + 1;
// else {
// this.version = 1;
int count = source.getFeedVersionCount();
this.version = count + 1;
}
/**
* Create an uninitialized feed version. This should only be used for dump/restore.
*/
public FeedVersion() {
// do nothing
}
/**
* The feed source this is associated with
*/
@JsonView(JsonViews.DataDump.class)
public String feedSourceId;
@JsonIgnore
public transient TransportNetwork transportNetwork;
@JsonView(JsonViews.UserInterface.class)
public FeedSource getFeedSource() {
return FeedSource.get(feedSourceId);
}
@JsonIgnore
public FeedVersion getPreviousVersion() {
return versionStore.find("version", new Tuple2(this.feedSourceId, this.version - 1));
}
@JsonView(JsonViews.UserInterface.class)
public String getPreviousVersionId() {
FeedVersion p = getPreviousVersion();
return p != null ? p.id : null;
}
@JsonIgnore
public FeedVersion getNextVersion() {
return versionStore.find("version", new Tuple2(this.feedSourceId, this.version + 1));
}
@JsonView(JsonViews.UserInterface.class)
public String getNextVersionId() {
FeedVersion p = getNextVersion();
return p != null ? p.id : null;
}
/**
* The hash of the feed file, for quick checking if the file has been updated
*/
@JsonView(JsonViews.DataDump.class)
public String hash;
@JsonIgnore
public File getGtfsFile() {
return feedStore.getFeed(id);
}
public File newGtfsFile(InputStream inputStream) {
File file = feedStore.newFeed(id, inputStream, getFeedSource());
this.fileSize = file.length();
LOG.info("New GTFS file saved: {}", id);
return file;
}
public File newGtfsFile(InputStream inputStream, Long lastModified) {
File file = newGtfsFile(inputStream);
if (lastModified != null) {
this.fileTimestamp = lastModified;
file.setLastModified(lastModified);
}
else {
this.fileTimestamp = file.lastModified();
}
this.save();
return file;
}
@JsonIgnore
public GTFSFeed getGtfsFeed() {
String apiId = id.replace(".zip", "");
// return DataManager.gtfsCache.get(apiId);
return GtfsApiController.gtfsApi.getFeedSource(apiId).feed;
}
/** The results of validating this feed */
@JsonView(JsonViews.DataDump.class)
public FeedValidationResult validationResult;
@JsonView(JsonViews.UserInterface.class)
public FeedValidationResultSummary getValidationSummary() {
return new FeedValidationResultSummary(validationResult);
}
/** When this version was uploaded/fetched */
public Date updated;
/** The version of the feed, starting with 0 for the first and so on */
public int version;
/** A name for this version. Defaults to creation date if not specified by user */
public String name;
public Long fileSize;
public Long fileTimestamp;
public String getName() {
return name != null ? name : (getFormattedTimestamp() + " Version");
}
@JsonIgnore
public String getFormattedTimestamp() {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy H:mm");
return format.format(this.updated);
}
public static FeedVersion get(String id) {
return versionStore.getById(id);
}
public static Collection<FeedVersion> getAll() {
return versionStore.getAll();
}
public void validate(EventBus eventBus) {
if (eventBus == null) {
eventBus = new EventBus();
}
Map<String, Object> statusMap = new HashMap<>();
GTFSFeed gtfsFeed;
try {
statusMap.put("message", "Unpacking feed...");
statusMap.put("percentComplete", 15.0);
statusMap.put("error", false);
eventBus.post(statusMap);
/* First getGtfsFeed() call triggers feed load from zip file into gtfsCache
This may take a while for large feeds */
gtfsFeed = getGtfsFeed();
} catch (Exception e) {
String errorString = String.format("No GTFS feed exists for version: %s", this.id);
LOG.warn(errorString);
statusMap.put("message", errorString);
statusMap.put("percentComplete", 0.0);
statusMap.put("error", true);
eventBus.post(statusMap);
return;
}
if(gtfsFeed == null) {
String errorString = String.format("Could not get GTFSFeed object for FeedVersion %s", id);
LOG.warn(errorString);
// eventBus.post(new StatusEvent(errorString, 0, true));
statusMap.put("message", errorString);
statusMap.put("percentComplete", 0.0);
statusMap.put("error", true);
eventBus.post(statusMap);
return;
}
Map<LocalDate, Integer> tripsPerDate;
try {
// make feed public... this shouldn't take very long
FeedSource fs = this.getFeedSource();
if (fs.isPublic) {
fs.makePublic();
}
// eventBus.post(new StatusEvent("Validating feed...", 30, false));
statusMap.put("message", "Validating feed...");
statusMap.put("percentComplete", 30.0);
statusMap.put("error", false);
eventBus.post(statusMap);
LOG.info("Beginning validation...");
gtfsFeed.validate();
LOG.info("Calculating stats...");
FeedStats stats = gtfsFeed.calculateStats();
validationResult = new FeedValidationResult(gtfsFeed, stats);
LOG.info("Total errors after validation: {}", validationResult.errorCount);
try {
// This may take a while for very large feeds.
LOG.info("Calculating # of trips per date of service");
tripsPerDate = stats.getTripCountPerDateOfService();
// get revenue time in seconds for Tuesdays in feed
stats.getAverageDailyRevenueTime(2);
}catch (Exception e) {
e.printStackTrace();
statusMap.put("message", "Unable to validate feed.");
statusMap.put("percentComplete", 0.0);
statusMap.put("error", true);
eventBus.post(statusMap);
e.printStackTrace();
// this.validationResult = null;
validationResult.loadStatus = LoadStatus.OTHER_FAILURE;
return;
}
} catch (Exception e) {
LOG.error("Unable to validate feed {}", this.id);
// eventBus.post(new StatusEvent("Unable to validate feed.", 0, true));
statusMap.put("message", "Unable to validate feed.");
statusMap.put("percentComplete", 0.0);
statusMap.put("error", true);
eventBus.post(statusMap);
e.printStackTrace();
// this.validationResult = null;
validationResult.loadStatus = LoadStatus.OTHER_FAILURE;
// halt(400, "Error validating feed...");
return;
}
File tempFile = null;
try {
// eventBus.post(new StatusEvent("Saving validation results...", 80, false));
statusMap.put("message", "Saving validation results...");
statusMap.put("percentComplete", 80.0);
statusMap.put("error", false);
eventBus.post(statusMap);
// Use tempfile
tempFile = File.createTempFile(this.id, ".json");
tempFile.deleteOnExit();
Map<String, Object> validation = new HashMap<>();
validation.put("errors", gtfsFeed.errors);
validation.put("tripsPerDate", tripsPerDate);
GeometryJSON g = new GeometryJSON();
Geometry buffers = gtfsFeed.getMergedBuffers();
validation.put("mergedBuffers", buffers != null ? g.toString(buffers) : null);
mapper.writeValue(tempFile, validation);
} catch (IOException e) {
e.printStackTrace();
}
saveValidationResult(tempFile);
}
@JsonIgnore
public JsonNode getValidationResult(boolean revalidate) {
if (revalidate) {
LOG.warn("Revalidation requested. Validating feed.");
this.validate();
this.save();
halt(503, "Try again later. Validating feed");
}
String keyName = validationSubdir + this.id + ".json";
InputStream objectData = null;
if (DataManager.feedBucket != null && DataManager.useS3) {
try {
LOG.info("Getting validation results from s3");
S3Object object = FeedStore.s3Client.getObject(new GetObjectRequest(DataManager.feedBucket, keyName));
objectData = object.getObjectContent();
} catch (AmazonS3Exception e) {
// if json file does not exist, validate feed.
this.validate();
this.save();
halt(503, "Try again later. Validating feed");
} catch (AmazonServiceException ase) {
LOG.error("Error downloading from s3");
ase.printStackTrace();
}
}
// if s3 upload set to false
else {
File file = new File(FeedStore.basePath + "/" + keyName);
try {
objectData = new FileInputStream(file);
} catch (Exception e) {
LOG.warn("Validation does not exist. Validating feed.");
this.validate();
this.save();
halt(503, "Try again later. Validating feed");
}
}
return ensureValidationIsCurrent(objectData);
}
private JsonNode ensureValidationIsCurrent(InputStream objectData) {
JsonNode n;
// Process the objectData stream.
try {
n = mapper.readTree(objectData);
if (!n.has("errors") || !n.has("tripsPerDate")) {
throw new Exception("Validation for feed version not up to date");
}
return n;
} catch (IOException e) {
// if json file does not exist, validate feed.
this.validate();
this.save();
halt(503, "Try again later. Validating feed");
} catch (Exception e) {
e.printStackTrace();
this.validate();
this.save();
halt(503, "Try again later. Validating feed");
}
return null;
}
private void saveValidationResult(File file) {
String keyName = validationSubdir + this.id + ".json";
// upload to S3, if we have bucket name and use s3 storage
if(DataManager.feedBucket != null && DataManager.useS3) {
try {
LOG.info("Uploading validation json to S3");
FeedStore.s3Client.putObject(new PutObjectRequest(
DataManager.feedBucket, keyName, file));
} catch (AmazonServiceException ase) {
LOG.error("Error uploading validation json to S3", ase);
}
}
// save to validation directory in gtfs folder
else {
File validationDir = new File(FeedStore.basePath + "/" + validationSubdir);
// ensure directory exists
validationDir.mkdir();
try {
FileUtils.copyFile(file, new File(FeedStore.basePath + "/" + keyName));
} catch (IOException e) {
LOG.error("Error saving validation json to local disk", e);
}
}
}
public void validate() {
validate(null);
}
public void save () {
save(true);
}
public void save(boolean commit) {
if (commit)
versionStore.save(this.id, this);
else
versionStore.saveWithoutCommit(this.id, this);
}
public void hash () {
this.hash = HashUtils.hashFile(getGtfsFile());
}
public static void commit() {
versionStore.commit();
}
public TransportNetwork buildTransportNetwork(EventBus eventBus) {
// return null if validation result is null (probably means something went wrong with validation, plus we won't have feed bounds).
if (this.validationResult == null) {
return null;
}
if (eventBus == null) {
eventBus = new EventBus();
}
// Fetch OSM extract
Map<String, Object> statusMap = new HashMap<>();
statusMap.put("message", "Fetching OSM extract...");
statusMap.put("percentComplete", 10.0);
statusMap.put("error", false);
eventBus.post(statusMap);
Rectangle2D bounds = this.validationResult.bounds;
if (bounds == null) {
String message = String.format("Could not build network for %s because feed bounds are unknown.", this.id);
LOG.warn(message);
statusMap.put("message", message);
statusMap.put("percentComplete", 10.0);
statusMap.put("error", true);
eventBus.post(statusMap);
return null;
}
File osmExtract = getOSMFile(bounds);
if (!osmExtract.exists()) {
InputStream is = getOsmExtract(this.validationResult.bounds);
OutputStream out;
try {
out = new FileOutputStream(osmExtract);
IOUtils.copy(is, out);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Create/save r5 network
statusMap.put("message", "Creating transport network...");
statusMap.put("percentComplete", 50.0);
statusMap.put("error", false);
eventBus.post(statusMap);
List<GTFSFeed> feedList = new ArrayList<>();
feedList.add(getGtfsFeed());
TransportNetwork tn;
try {
tn = TransportNetwork.fromFeeds(osmExtract.getAbsolutePath(), feedList, TNBuilderConfig.defaultConfig());
} catch (Exception e) {
String message = String.format("Unknown error encountered while building network for %s.", this.id);
LOG.warn(message);
statusMap.put("message", message);
statusMap.put("percentComplete", 100.0);
statusMap.put("error", true);
eventBus.post(statusMap);
e.printStackTrace();
return null;
}
this.transportNetwork = tn;
this.transportNetwork.transitLayer.buildDistanceTables(null);
File tnFile = getTransportNetworkPath();
try {
tn.write(tnFile);
return transportNetwork;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@JsonIgnore
public static File getOSMFile(Rectangle2D bounds) {
if (bounds != null) {
String baseDir = FeedStore.basePath.getAbsolutePath() + File.separator + "osm";
File osmPath = new File(String.format("%s/%.6f_%.6f_%.6f_%.6f", baseDir, bounds.getMaxX(), bounds.getMaxY(), bounds.getMinX(), bounds.getMinY()));
if (!osmPath.exists()) {
osmPath.mkdirs();
}
File osmFile = new File(osmPath.getAbsolutePath() + "/data.osm.pbf");
return osmFile;
}
else {
return null;
}
}
public TransportNetwork buildTransportNetwork() {
return buildTransportNetwork(null);
}
/**
* Does this feed version have any critical errors that would prevent it being loaded to OTP?
* @return
*/
public boolean hasCriticalErrors() {
if (hasCriticalErrorsExceptingDate() || (LocalDate.now()).isAfter(validationResult.endDate))
return true;
else
return false;
}
/**
* Does this feed have any critical errors other than possibly being expired?
*/
public boolean hasCriticalErrorsExceptingDate () {
if (validationResult == null)
return true;
if (validationResult.loadStatus != LoadStatus.SUCCESS)
return true;
if (validationResult.stopTimesCount == 0 || validationResult.tripCount == 0 || validationResult.agencyCount == 0)
return true;
return false;
}
@JsonView(JsonViews.UserInterface.class)
public int getNoteCount() {
return this.noteIds != null ? this.noteIds.size() : 0;
}
@JsonInclude(Include.NON_NULL)
@JsonView(JsonViews.UserInterface.class)
public Long getFileTimestamp() {
if (fileTimestamp != null) {
return fileTimestamp;
}
this.fileTimestamp = feedStore.getFeedLastModified(id);
this.save();
return this.fileTimestamp;
}
@JsonInclude(Include.NON_NULL)
@JsonView(JsonViews.UserInterface.class)
public Long getFileSize() {
if (fileSize != null) {
return fileSize;
}
this.fileSize = feedStore.getFeedSize(id);
this.save();
return fileSize;
}
/**
* Delete this feed version.
*/
public void delete() {
try {
// reset lastModified if feed is latest version
System.out.println("deleting version");
String id = this.id;
FeedSource fs = getFeedSource();
FeedVersion latest = fs.getLatest();
if (latest != null && latest.id.equals(this.id)) {
fs.lastFetched = null;
fs.save();
}
feedStore.deleteFeed(id);
for (Deployment d : Deployment.getAll()) {
d.feedVersionIds.remove(this.id);
}
getTransportNetworkPath().delete();
versionStore.delete(this.id);
LOG.info("Version {} deleted", id);
} catch (Exception e) {
LOG.warn("Error deleting version", e);
}
}
@JsonIgnore
public String getR5Path () {
// r5 networks MUST be stored in separate directories (in this case under feed source ID
// because of shared osm.mapdb used by r5 networks placed in same dir
File r5 = new File(String.join(File.separator, FeedStore.basePath.getAbsolutePath(), this.feedSourceId));
if (!r5.exists()) {
r5.mkdirs();
}
return r5.getAbsolutePath();
}
@JsonIgnore
public File getTransportNetworkPath () {
return new File(String.join(File.separator, getR5Path(), id + "_" + R5Version.describe + "_network.dat"));
}
} |
package com.conveyal.datatools.manager.models;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.conveyal.datatools.manager.DataManager;
import com.conveyal.datatools.manager.controllers.api.GtfsApiController;
import com.conveyal.datatools.manager.persistence.DataStore;
import com.conveyal.datatools.manager.persistence.FeedStore;
import com.conveyal.datatools.manager.utils.HashUtils;
import com.conveyal.gtfs.GTFSFeed;
import com.conveyal.gtfs.api.ApiMain;
import com.conveyal.gtfs.validator.json.LoadStatus;
import com.conveyal.gtfs.validator.service.impl.FeedStats;
import com.conveyal.r5.point_to_point.builder.TNBuilderConfig;
import com.conveyal.r5.transit.TransportNetwork;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.mapdb.Fun.Function2;
import org.mapdb.Fun.Tuple2;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.conveyal.datatools.manager.models.Deployment.getOsmExtract;
import static com.conveyal.datatools.manager.utils.StringUtils.getCleanName;
import static spark.Spark.halt;
/**
* Represents a version of a feed.
* @author mattwigway
*
*/
@JsonInclude(Include.ALWAYS)
public class FeedVersion extends Model implements Serializable {
private static final long serialVersionUID = 1L;
public static final Logger LOG = LoggerFactory.getLogger(FeedVersion.class);
static DataStore<FeedVersion> versionStore = new DataStore<FeedVersion>("feedversions");
private static FeedStore feedStore = new FeedStore();
static {
// set up indexing on feed versions by feed source, indexed by <FeedSource ID, version>
versionStore.secondaryKey("version", new Function2<Tuple2<String, Integer>, String, FeedVersion> () {
@Override
public Tuple2<String, Integer> run(String key, FeedVersion fv) {
return new Tuple2(fv.feedSourceId, fv.version);
}
});
}
/**
* We generate IDs manually, but we need a bit of information to do so
*/
public FeedVersion (FeedSource source) {
this.updated = new Date();
this.feedSourceId = source.id;
// ISO time
DateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmssX");
// since we store directly on the file system, this lets users look at the DB directly
this.id = getCleanName(source.name) + "_" + df.format(this.updated) + "_" + source.id + ".zip";
// infer the version
// FeedVersion prev = source.getLatest();
// if (prev != null) {
// this.version = prev.version + 1;
// else {
// this.version = 1;
int count = source.getFeedVersionCount();
this.version = count + 1;
}
/**
* Create an uninitialized feed version. This should only be used for dump/restore.
*/
public FeedVersion () {
// do nothing
}
/** The feed source this is associated with */
@JsonView(JsonViews.DataDump.class)
public String feedSourceId;
@JsonIgnore
public transient TransportNetwork transportNetwork;
@JsonView(JsonViews.UserInterface.class)
public FeedSource getFeedSource () {
return FeedSource.get(feedSourceId);
}
@JsonIgnore
public FeedVersion getPreviousVersion () {
return versionStore.find("version", new Tuple2(this.feedSourceId, this.version - 1));
}
@JsonView(JsonViews.UserInterface.class)
public String getPreviousVersionId () {
FeedVersion p = getPreviousVersion();
return p != null ? p.id : null;
}
@JsonIgnore
public FeedVersion getNextVersion () {
return versionStore.find("version", new Tuple2(this.feedSourceId, this.version + 1));
}
@JsonView(JsonViews.UserInterface.class)
public String getNextVersionId () {
FeedVersion p = getNextVersion();
return p != null ? p.id : null;
}
/** The hash of the feed file, for quick checking if the file has been updated */
@JsonView(JsonViews.DataDump.class)
public String hash;
@JsonIgnore
public File getFeed() {
return feedStore.getFeed(id);
}
public File newFeed(InputStream inputStream) {
return feedStore.newFeed(id, inputStream, getFeedSource());
}
/** The results of validating this feed */
@JsonView(JsonViews.DataDump.class)
public FeedValidationResult validationResult;
// @JsonIgnore
// public List<GTFSError> errors;
@JsonView(JsonViews.UserInterface.class)
public FeedValidationResultSummary getValidationSummary() {
return new FeedValidationResultSummary(validationResult);
}
/** When this feed was uploaded to or fetched by GTFS Data Manager */
public Date updated;
/** The version of the feed, starting with 0 for the first and so on */
public int version;
public static FeedVersion get(String id) {
// TODO Auto-generated method stub
return versionStore.getById(id);
}
public static Collection<FeedVersion> getAll() {
return versionStore.getAll();
}
public void validate() {
File feed = null;
try {
feed = getFeed();
} catch (Exception e) {
// halt(400, "No GTFS feed exists for this version.");
LOG.warn("No GTFS feed exists for version: {}", this.id);
return;
}
// FeedProcessor fp = new FeedProcessor(feed);
GTFSFeed f = null;
try {
f = GTFSFeed.fromFile(feed.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
return;
}
Map<LocalDate, Integer> tripsPerDate;
// load feed into GTFS api
if (DataManager.config.get("modules").get("gtfsapi").get("load_on_fetch").asBoolean()) {
LOG.info("Loading feed into GTFS api");
String md5 = ApiMain.loadFeedFromFile(feed, this.feedSourceId);
if (GtfsApiController.feedUpdater != null) {
GtfsApiController.feedUpdater.addFeedETag(md5);
}
}
try {
f.validate();
FeedStats stats = f.calculateStats();
validationResult = new FeedValidationResult();
validationResult.agencies = stats.getAllAgencies().stream().map(agency -> agency.agency_id).collect(Collectors.toList());
validationResult.agencyCount = stats.getAgencyCount();
validationResult.routeCount = stats.getRouteCount();
validationResult.bounds = stats.getBounds();
LocalDate calDateStart = stats.getCalendarDateStart();
LocalDate calSvcStart = stats.getCalendarServiceRangeStart();
LocalDate calDateEnd = stats.getCalendarDateEnd();
LocalDate calSvcEnd = stats.getCalendarServiceRangeEnd();
if (calDateStart == null && calSvcStart == null)
// no service . . . this is bad
validationResult.startDate = null;
else if (calDateStart == null)
validationResult.startDate = calSvcStart;
else if (calSvcStart == null)
validationResult.startDate = calDateStart;
else
validationResult.startDate = calDateStart.isBefore(calSvcStart) ? calDateStart : calSvcStart;
if (calDateEnd == null && calSvcEnd == null)
// no service . . . this is bad
validationResult.endDate = null;
else if (calDateEnd == null)
validationResult.endDate = calSvcEnd;
else if (calSvcEnd == null)
validationResult.endDate = calDateEnd;
else
validationResult.endDate = calDateEnd.isAfter(calSvcEnd) ? calDateEnd : calSvcEnd;
validationResult.loadStatus = LoadStatus.SUCCESS;
validationResult.tripCount = stats.getTripCount();
validationResult.stopTimesCount = stats.getStopTimesCount();
validationResult.errorCount = f.errors.size();
tripsPerDate = stats.getTripsPerDateOfService();
} catch (Exception e) {
LOG.error("Unable to validate feed {}", this);
e.printStackTrace();
this.validationResult = null;
return;
}
String s3Bucket = DataManager.config.get("application").get("data").get("gtfs_s3_bucket").asText();
// upload to S3, if we have bucket name
if(s3Bucket != null) {
AWSCredentials creds;
// default credentials providers, e.g. IAM role
creds = new DefaultAWSCredentialsProviderChain().getCredentials();
String keyName = "validation/" + this.id + ".json";
ObjectMapper mapper = new ObjectMapper();
try {
// Use tempfile
File tempFile = File.createTempFile(this.id, ".json");
tempFile.deleteOnExit();
Map<String, Object> validation = new HashMap<>();
validation.put("errors", f.errors);
validation.put("tripsPerDate", tripsPerDate
// .entrySet()
// .stream()
// .map(entry -> entry.getKey().format(DateTimeFormatter.BASIC_ISO_DATE))
// .collect(Collectors.toList())
);
mapper.writeValue(tempFile, validation);
LOG.info("Uploading validation json to S3");
AmazonS3 s3client = new AmazonS3Client(creds);
s3client.putObject(new PutObjectRequest(
s3Bucket, keyName, tempFile));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (AmazonServiceException ase) {
LOG.error("Error uploading feed to S3");
}
}
// this.validationResult = fp.getOutput();
}
public void save () {
save(true);
}
public void save(boolean commit) {
if (commit)
versionStore.save(this.id, this);
else
versionStore.saveWithoutCommit(this.id, this);
}
public void hash () {
this.hash = HashUtils.hashFile(getFeed());
}
public static void commit() {
versionStore.commit();
}
public TransportNetwork buildTransportNetwork() {
String gtfsDir = DataManager.config.get("application").get("data").get("gtfs").asText() + "/";
String feedSourceDir = gtfsDir + feedSourceId + "/";
File fsPath = new File(feedSourceDir);
if (!fsPath.isDirectory()) {
fsPath.mkdir();
}
// Fetch OSM extract
Rectangle2D bounds = this.validationResult.bounds;
String osmFileName = String.format("%s%.6f_%.6f_%.6f_%.6f.osm.pbf",feedSourceDir, bounds.getMaxX(), bounds.getMaxY(), bounds.getMinX(), bounds.getMinY());
File osmExtract = new File(osmFileName);
if (!osmExtract.exists()) {
InputStream is = getOsmExtract(this.validationResult.bounds);
OutputStream out = null;
try {
out = new FileOutputStream(osmExtract);
IOUtils.copy(is, out);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Create/save r5 network
TransportNetwork tn = TransportNetwork.fromFiles(osmExtract.getAbsolutePath(), gtfsDir + this.id, TNBuilderConfig.defaultConfig());
this.transportNetwork = tn;
File tnFile = new File(feedSourceDir + this.id + "_network.dat");
OutputStream tnOut = null;
try {
tnOut = new FileOutputStream(tnFile);
tn.write(tnOut);
return transportNetwork;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Does this feed version have any critical errors that would prevent it being loaded to OTP?
* @return
*/
public boolean hasCriticalErrors() {
if (hasCriticalErrorsExceptingDate() || (LocalDate.now()).isAfter(validationResult.endDate))
return true;
else
return false;
}
/**
* Does this feed have any critical errors other than possibly being expired?
*/
public boolean hasCriticalErrorsExceptingDate () {
if (validationResult == null)
return true;
if (validationResult.loadStatus != LoadStatus.SUCCESS)
return true;
if (validationResult.stopTimesCount == 0 || validationResult.tripCount == 0 || validationResult.agencyCount == 0)
return true;
return false;
}
@JsonView(JsonViews.UserInterface.class)
public int getNoteCount() {
return this.noteIds != null ? this.noteIds.size() : 0;
}
@JsonInclude(Include.NON_NULL)
@JsonView(JsonViews.UserInterface.class)
public Long getFileTimestamp() {
File file = getFeed();
if(file == null) return null;
return file.lastModified();
}
@JsonInclude(Include.NON_NULL)
@JsonView(JsonViews.UserInterface.class)
public Long getFileSize() {
File file = getFeed();
if(file == null) return null;
return file.length();
}
/**
* Delete this feed version.
*/
public void delete() {
File feed = getFeed();
if (feed != null && feed.exists())
feed.delete();
/*for (Deployment d : Deployment.getAll()) {
d.feedVersionIds.remove(this.id);
}*/
versionStore.delete(this.id);
}
} |
package com.elmakers.mine.bukkit.spell.builtin;
import java.util.Collection;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.spell.UndoableSpell;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.api.spell.SpellEventType;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.spell.TargetingSpell;
public class FlingSpell extends UndoableSpell implements Listener
{
private final long safetyLength = 20000;
private long lastFling = 0;
protected int defaultMaxSpeedAtElevation = 64;
protected double defaultMinMagnitude = 1.5;
protected double defaultMaxMagnitude = 4;
private final static int effectSpeed = 1;
private final static int effectPeriod = 3;
private final static int minRingEffectRange = 2;
private final static int maxRingEffectRange = 15;
private final static int maxDamageAmount = 200;
@Override
public SpellResult onCast(ConfigurationSection parameters)
{
int height = 0;
Block playerBlock = getLocation().getBlock();
LivingEntity entity = mage.getLivingEntity();
if (entity == null) {
return SpellResult.LIVING_ENTITY_REQUIRED;
}
int maxSpeedAtElevation = parameters.getInt("cruising_altitude", defaultMaxSpeedAtElevation);
double minMagnitude = parameters.getDouble("min_speed", defaultMinMagnitude);
double maxMagnitude = parameters.getDouble("max_speed", defaultMaxMagnitude);
while (height < maxSpeedAtElevation && playerBlock.getType() == Material.AIR)
{
playerBlock = playerBlock.getRelative(BlockFace.DOWN);
height++;
}
double heightModifier = maxSpeedAtElevation > 0 ? ((double)height / maxSpeedAtElevation) : 1;
double magnitude = (minMagnitude + (((double)maxMagnitude - minMagnitude) * heightModifier));
Vector velocity = getDirection();
if (mage.getLocation().getBlockY() >= 256)
{
velocity.setY(0);
}
velocity.multiply(magnitude);
registerVelocity(entity);
entity.setVelocity(velocity);
mage.registerEvent(SpellEventType.PLAYER_DAMAGE, this);
lastFling = System.currentTimeMillis();
registerForUndo();
return SpellResult.CAST;
}
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerDamage(EntityDamageEvent event)
{
if (event.getCause() != DamageCause.FALL) return;
mage.unregisterEvent(SpellEventType.PLAYER_DAMAGE, this);
if (lastFling == 0) return;
if (lastFling + safetyLength > System.currentTimeMillis())
{
event.setCancelled(true);
lastFling = 0;
// Visual effect
int ringEffectRange = (int)Math.ceil(((double)maxRingEffectRange - minRingEffectRange) * event.getDamage() / maxDamageAmount + minRingEffectRange);
ringEffectRange = Math.min(maxRingEffectRange, ringEffectRange);
playEffects("land", ringEffectRange);
}
}
@Override
public void getParameters(Collection<String> parameters)
{
super.getParameters(parameters);
parameters.add("cruising_altitude");
parameters.add("min_speed");
parameters.add("max_speed");
}
@Override
public com.elmakers.mine.bukkit.api.block.MaterialAndData getEffectMaterial()
{
Block block = mage.getEntity().getLocation().getBlock();
block = block.getRelative(BlockFace.DOWN);
return new MaterialAndData(block);
}
} |
package com.epimorphics.dclib.templates;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.apache.jena.atlas.json.JsonObject;
import org.apache.jena.atlas.json.JsonValue;
import org.apache.jena.riot.system.StreamRDF;
import com.epimorphics.dclib.framework.BindingEnv;
import com.epimorphics.dclib.framework.ConverterProcess;
import com.epimorphics.dclib.framework.DataContext;
import com.epimorphics.dclib.framework.NullResult;
import com.epimorphics.dclib.framework.Template;
import com.epimorphics.dclib.values.Value;
import com.epimorphics.dclib.values.ValueFactory;
import com.epimorphics.util.EpiException;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.NodeFactory;
import com.hp.hpl.jena.graph.Triple;
public class CompositeTemplate extends ParameterizedTemplate implements Template {
protected List<Template> templates;
/**
* Test if a json object specifies on of these templates
*/
public static boolean isSpec(JsonObject spec) {
if (spec.hasKey(JSONConstants.TYPE)) {
return spec.get(JSONConstants.TYPE).getAsString().value().equals(JSONConstants.COMPOSITE);
} else {
return spec.hasKey( JSONConstants.ONE_OFFS ) && spec.hasKey( JSONConstants.TEMPLATES );
}
}
public CompositeTemplate(JsonObject spec, DataContext dc) {
super(spec, dc);
// Extract any prefixes
if (spec.get(JSONConstants.PREFIXES) != null) {
try {
JsonObject prefixes = spec.get(JSONConstants.PREFIXES).getAsObject();
for (Entry<String, JsonValue> pentry : prefixes.entrySet()) {
dc.setPrefix(pentry.getKey(), pentry.getValue().getAsString().value());
}
} catch (Exception e) {
throw new EpiException("Couldn't parse prefix declaration in composite template", e);
}
}
// Extract the list of to level templates to run
templates = getTemplates(spec.get(JSONConstants.TEMPLATES), dc);
// Extract any reference templates
for (Template t : getTemplates(spec.get(JSONConstants.REFERENCED), dc)) {
dc.registerTemplate(t);
}
}
@Override
public Node convertRow(ConverterProcess proc, BindingEnv row, int rowNumber) {
super.convertRow(proc, row, rowNumber);
BindingEnv env = bindParameters(proc, row, rowNumber);
Node result = null;
for (Template template : templates) {
if (template.isApplicableTo(env)) {
if (proc.isDebugging()) {
proc.getMessageReporter().report("Debug: trying template " + template.getName());
}
try {
Node n = template.convertRow(proc, env, rowNumber);
if (result == null && n != null) {
result = n;
}
} catch (NullResult e) {
// Silently ignore null results
} catch (Exception e) {
proc.getMessageReporter().report("Warning: template " + template.getName() + " applied but failed: " + e, rowNumber);
}
} else {
if (proc.isDebugging()) {
proc.getMessageReporter().report("Debug: template " + template.getName() + " not applicable");
}
}
}
processRawColumns(result, proc, env, rowNumber);
return result;
}
/**
* Check for any columns of form "<url>" and extract those directly.
*/
private void processRawColumns(Node resource, ConverterProcess proc, BindingEnv row, int rowNumber) {
StreamRDF out = proc.getOutputStream();
for (Iterator<String> i = row.allKeys(); i.hasNext(); ) {
String col = i.next();
if (isURI(col)) {
String p = proc.getDataContext().expandURI( asURI(col) );
Node predicate = NodeFactory.createURI(p);
Object v = row.get(col);
Node obj = null;
if (v instanceof Value) {
Value val = (Value)v;
Object o = val.getValue();
if (o instanceof String) {
String s = (String)o;
if ( isURI(s) ) {
obj = NodeFactory.createURI( asURI(s) );
}
}
if (obj == null) {
obj = val.asNode();
}
} else if (v instanceof String) {
String s = (String)v;
if ( isURI(s) ) {
obj = NodeFactory.createURI( asURI(s) );
} else {
obj = ValueFactory.asValue(s, proc).asNode();
}
} else if (v instanceof Node) {
obj = (Node) v;
} else {
proc.getMessageReporter().report("Warning: could not interpret raw column value: " + v, rowNumber);
}
out.triple( new Triple(resource, predicate, obj) );
}
}
}
private boolean isURI(String s) {
return s.startsWith("<") && s.endsWith(">");
}
private String asURI(String s) {
return s.substring(1, s.length() - 1);
}
@Override
public void preamble(ConverterProcess proc) {
super.preamble(proc);
DataContext dc = proc.getDataContext();
BindingEnv env = proc.getEnv();
// Instantiate any global bindings
if (spec.hasKey(JSONConstants.BIND)) {
env = bindParameters(proc, env, -1);
}
// Process any one-offs
for (Template t : getTemplates(spec.get(JSONConstants.ONE_OFFS), dc)) {
t.preamble(proc);
t.convertRow(proc, env, 0);
}
}
} |
package com.epimorphics.dclib.templates;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.apache.jena.atlas.json.JsonObject;
import org.apache.jena.atlas.json.JsonValue;
import org.apache.jena.riot.system.StreamRDF;
import com.epimorphics.dclib.framework.BindingEnv;
import com.epimorphics.dclib.framework.ConverterProcess;
import com.epimorphics.dclib.framework.DataContext;
import com.epimorphics.dclib.framework.NullResult;
import com.epimorphics.dclib.framework.Pattern;
import com.epimorphics.dclib.framework.Template;
import com.epimorphics.dclib.values.Value;
import com.epimorphics.dclib.values.ValueFactory;
import com.epimorphics.util.EpiException;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.NodeFactory;
import com.hp.hpl.jena.graph.Triple;
public class CompositeTemplate extends ParameterizedTemplate implements Template {
protected List<Template> templates;
protected Pattern guard;
/**
* Test if a json object specifies on of these templates
*/
public static boolean isSpec(JsonObject spec) {
if (spec.hasKey(JSONConstants.TYPE)) {
return spec.get(JSONConstants.TYPE).getAsString().value().equals(JSONConstants.COMPOSITE);
} else {
return spec.hasKey( JSONConstants.ONE_OFFS ) && spec.hasKey( JSONConstants.TEMPLATES );
}
}
public CompositeTemplate(JsonObject spec, DataContext dc) {
super(spec, dc);
// Extract any prefixes
if (spec.get(JSONConstants.PREFIXES) != null) {
try {
JsonObject prefixes = spec.get(JSONConstants.PREFIXES).getAsObject();
for (Entry<String, JsonValue> pentry : prefixes.entrySet()) {
dc.setPrefix(pentry.getKey(), pentry.getValue().getAsString().value());
}
} catch (Exception e) {
throw new EpiException("Couldn't parse prefix declaration in composite template", e);
}
}
if (spec.get(JSONConstants.GUARD) != null) {
guard = new Pattern( spec.get(JSONConstants.GUARD).getAsString().value(), dc);
}
// Extract the list of to level templates to run
templates = getTemplates(spec.get(JSONConstants.TEMPLATES), dc);
// Extract any reference templates
for (Template t : getTemplates(spec.get(JSONConstants.REFERENCED), dc)) {
dc.registerTemplate(t);
}
}
@Override
public boolean isApplicableTo(ConverterProcess config, BindingEnv row, int rowNumber) {
if ( ! super.isApplicableTo(config, row, rowNumber) ) return false;
if (guard != null) {
Object result = guard.evaluate(row, config, rowNumber);
if (result instanceof Boolean && ((Boolean)result)) {
return true;
}
return false;
}
return true;
}
@Override
public Node convertRow(ConverterProcess proc, BindingEnv row, int rowNumber) {
Node result = super.convertRow(proc, row, rowNumber);
BindingEnv env = bindParameters(proc, row, rowNumber);
if (proc.isDebugging()) {
proc.getMessageReporter().report("Bindings for " + getName() + ": " + env);
}
for (Template template : templates) {
template = template.deref();
if (template.isApplicableTo(proc.getHeaders()) && template.isApplicableTo(proc, env, rowNumber)) {
reportApplying(proc, template, rowNumber);
try {
Node n = template.convertRow(proc, env, rowNumber);
if (result == null && n != null) {
result = n;
}
} catch (NullResult e) {
// Silently ignore null results
} catch (Exception e) {
proc.getMessageReporter().report("Warning: template " + template.getName() + " applied but failed: " + e, rowNumber);
}
} else {
if (proc.isDebugging()) {
proc.getMessageReporter().report("Debug: template " + template.getName() + " not applicable", rowNumber);
}
}
}
processRawColumns(result, proc, env, rowNumber);
return result;
}
/**
* Check for any columns of form "<url>" and extract those directly.
*/
private void processRawColumns(Node resource, ConverterProcess proc, BindingEnv row, int rowNumber) {
StreamRDF out = proc.getOutputStream();
for (Iterator<String> i = row.allKeys(); i.hasNext(); ) {
String col = i.next();
if (isURI(col)) {
String p = proc.getDataContext().expandURI( asURI(col) );
Node predicate = NodeFactory.createURI(p);
Object v = row.get(col);
Node obj = null;
if (v instanceof Value) {
Value val = (Value)v;
Object o = val.getValue();
if (o instanceof String) {
String s = (String)o;
if ( isURI(s) ) {
obj = NodeFactory.createURI( asURI(s) );
}
}
if (obj == null) {
obj = val.asNode();
}
} else if (v instanceof String) {
String s = (String)v;
if ( isURI(s) ) {
obj = NodeFactory.createURI( asURI(s) );
} else {
obj = ValueFactory.asValue(s).asNode();
}
} else if (v instanceof Node) {
obj = (Node) v;
} else {
proc.getMessageReporter().report("Warning: could not interpret raw column value: " + v, rowNumber);
}
out.triple( new Triple(resource, predicate, obj) );
}
}
}
private boolean isURI(String s) {
return s.startsWith("<") && s.endsWith(">");
}
private String asURI(String s) {
return s.substring(1, s.length() - 1);
}
@Override
public void preamble(ConverterProcess proc, BindingEnv env) {
super.preamble(proc, env);
DataContext dc = proc.getDataContext();
// Instantiate any global bindings
if (spec.hasKey(JSONConstants.BIND)) {
env = bindParameters(proc, env, -1);
}
// Process any one-offs
for (Template t : getTemplates(spec.get(JSONConstants.ONE_OFFS), dc)) {
reportApplying(proc, t, -1);
t.preamble(proc, env);
t.convertRow(proc, env, 0);
}
for (Template t : templates) {
if (t.isApplicableTo(proc, env, 0)) {
t.preamble(proc, env);
}
}
}
private void reportApplying(ConverterProcess proc, Template t, int rowNumber) {
if (proc.isDebugging()) {
if (rowNumber == -1) {
proc.getMessageReporter().report("Debug: applying template " + t.getName() + " as one-off");
} else {
proc.getMessageReporter().report("Debug: applying template " + t.getName(), rowNumber);
}
}
}
} |
package com.github.dockerjava.api.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.github.dockerjava.core.RemoteApiVersion;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import javax.annotation.CheckForNull;
import java.io.Serializable;
/**
* @since {@link RemoteApiVersion#VERSION_1_24}
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceModeConfig implements Serializable {
public static final long serialVersionUID = 1L;
/**
* @since 1.24
*/
@JsonProperty("Replicated")
private ServiceReplicatedModeOptions replicated;
/**
* @since 1.24
*/
@JsonProperty("Global")
private ServiceGlobalModeOptions global;
/**
* @since 1.24
*/
@CheckForNull
public ServiceMode getMode() {
if (replicated != null) {
return ServiceMode.REPLICATED;
}
if (global != null) {
return ServiceMode.GLOBAL;
}
return null;
}
/**
* @since 1.24
*/
@CheckForNull
public ServiceReplicatedModeOptions getReplicated() {
return replicated;
}
/**
* @since 1.24
*/
public ServiceModeConfig withReplicated(ServiceReplicatedModeOptions replicated) {
if (replicated != null && this.global != null) {
throw new IllegalStateException("Cannot set both replicated and global mode");
}
this.replicated = replicated;
return this;
}
/**
* @since 1.24
*/
@CheckForNull
public ServiceGlobalModeOptions getGlobal() {
return global;
}
/**
* @since 1.24
*/
public ServiceModeConfig withGlobal(ServiceGlobalModeOptions global) {
if (global != null && this.replicated != null) {
throw new IllegalStateException("Cannot set both global and replicated mode");
}
this.global = global;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
} |
package com.github.kory33.specificworldlogin;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.Location;
import java.io.File;
import java.util.ArrayList;
public class DataHandling {
private final SpecificWorldLogin plugin;
private ArrayList<World> permittedLoginWorld;
private Location teleportLocation;
//when this variable is false, this plugin does not attempt to teleport players
public boolean isFunctioning;
public DataHandling(SpecificWorldLogin plugin) {
this.plugin = plugin;
if(!(new File("config.yml")).exists()){
plugin.saveResource("config.yml", false);
}
//read all the required data
this.readPermittedLoginWorld();
}
private void readPermittedLoginWorld(){
YamlConfiguration ymlData = YamlConfiguration.loadConfiguration(new File(this.plugin.getDataFolder(), "config.yml"));
this.isFunctioning = true;
//for the each world under permittedWorldName section
permittedLoginWorld = new ArrayList<World>();
for(String worldName: ymlData.getStringList("permittedWorlds")){
World w = plugin.getServer().getWorld(worldName);
//in case the world is not found
if(w == null){
plugin.getServer().getLogger().warning("World " + worldName + " is not found! Check the configuartion file.");
}else{
//otherwise add to the list
permittedLoginWorld.add(w);
}
}
if(permittedLoginWorld.isEmpty()){
this.isFunctioning = false;
}
//get the teleportations destination
String tpWorldName = ymlData.getString("teleportDest.world");
this.teleportLocation = null;
if(tpWorldName != null){
World tpWorld = plugin.getServer().getWorld(tpWorldName);
if(tpWorld == null){
this.isFunctioning = false;
plugin.getServer().getLogger().warning("Teleport destination is not found! Check the configuraation file.");
}else{
//by default teleport to the spawn locaiton
Location tpDest = tpWorld.getSpawnLocation();
//if the location is defined
if(ymlData.contains("teleportDest.x") && ymlData.contains("teleportDest.y") && ymlData.contains("teleportDest.z")){
//get coordinates
double x, y, z;
x = ymlData.getDouble("teleportDest.x");
y = ymlData.getDouble("teleportDest.y");
z = ymlData.getDouble("teleportDest.z");
tpDest = new Location(tpWorld, x, y, z);
}else{
plugin.getServer().getLogger().warning("Teleport coordinates not found. setting them to the spawn location...");
}
this.teleportLocation = tpDest;
}
}
if(this.isFunctioning == false){
plugin.getServer().getLogger().warning("The settings are invalid. Plugin no longer works!");
}
}
public boolean isPermitted(World w){
return this.permittedLoginWorld.contains(w);
}
public Location getTpDest(){
return this.teleportLocation;
}
} |
package com.github.onsdigital.configuration;
import org.apache.commons.lang3.StringUtils;
public class Configuration
{
private static final String DEFAULT_TAXONOMY_ROOT = "./../nightingale/taxonomy";
public static String getTaxonomyPath() {
return StringUtils.defaultIfBlank(getValue("TAXONOMY_DIR"), DEFAULT_TAXONOMY_ROOT);
}
/**
* Gets a configured value for the given key from either the system
* properties or an environment variable.
* <p>
* Copied from {@link com.github.davidcarboni.restolino.Configuration}.
*
* @param key
* The name of the configuration value.
* @return The system property corresponding to the given key (e.g.
* -Dkey=value). If that is blank, the environment variable
* corresponding to the given key (e.g. EXPORT key=value). If that
* is blank, {@link StringUtils#EMPTY}.
*/
static String getValue(String key) {
return StringUtils.defaultIfBlank(System.getProperty(key), System.getenv(key));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.