answer
stringlengths
17
10.2M
package dr.inference.model; import dr.util.NumberFormatter; import dr.xml.*; import java.util.ArrayList; import java.util.List; /** * A likelihood function which is simply the product of a set of likelihood functions. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $ */ public class ThreadedCompoundLikelihood implements Likelihood { public static final String THREADED_COMPOUND_LIKELIHOOD = "threadedCompoundLikelihood"; public ThreadedCompoundLikelihood() { } public void addLikelihood(Likelihood likelihood) { if (!likelihoods.contains(likelihood)) { likelihoods.add(likelihood); if (likelihood.getModel() != null) { compoundModel.addModel(likelihood.getModel()); } likelihoodCallers.add(new LikelihoodCaller(likelihood)); } } public int getLikelihoodCount() { return likelihoods.size(); } public final Likelihood getLikelihood(int i) { return likelihoods.get(i); } // Likelihood IMPLEMENTATION public Model getModel() { return compoundModel; } public double getLogLikelihood() { double logLikelihood = 0.0; if (threads == null) { // first call so setup a thread for each likelihood... threads = new LikelihoodThread[likelihoodCallers.size()]; for (int i = 0; i < threads.length; i++) { // and start them running... threads[i] = new LikelihoodThread(); threads[i].start(); } } for (int i = 0; i < threads.length; i++) { // set the caller which will be called in each thread threads[i].setCaller(likelihoodCallers.get(i)); } for (LikelihoodThread thread : threads) { // now wait for the results to be set... Double result = thread.getResult(); while (result == null) { result = thread.getResult(); } logLikelihood += result; } return logLikelihood; } public void makeDirty() { for (Likelihood likelihood : likelihoods) { likelihood.makeDirty(); } } public String getDiagnosis() { String message = ""; boolean first = true; for (Likelihood lik : likelihoods) { if (!first) { message += ", "; } else { first = false; } String id = lik.getId(); if (id == null || id.trim().length() == 0) { String[] parts = lik.getClass().getName().split("\\."); id = parts[parts.length - 1]; } message += id + "="; if (lik instanceof ThreadedCompoundLikelihood) { String d = ((ThreadedCompoundLikelihood) lik).getDiagnosis(); if (d != null && d.length() > 0) { message += "(" + d + ")"; } } else { if (lik.getLogLikelihood() == Double.NEGATIVE_INFINITY) { message += "-Inf"; } else if (Double.isNaN(lik.getLogLikelihood())) { message += "NaN"; } else { NumberFormatter nf = new NumberFormatter(6); message += nf.formatDecimal(lik.getLogLikelihood(), 4); } } } return message; } public String toString() { return Double.toString(getLogLikelihood()); } // Loggable IMPLEMENTATION /** * @return the log columns. */ public dr.inference.loggers.LogColumn[] getColumns() { return new dr.inference.loggers.LogColumn[]{ new LikelihoodColumn(getId()) }; } private class LikelihoodColumn extends dr.inference.loggers.NumberColumn { public LikelihoodColumn(String label) { super(label); } public double getDoubleValue() { return getLogLikelihood(); } } // Identifiable IMPLEMENTATION private String id = null; public void setId(String id) { this.id = id; } public String getId() { return id; } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return THREADED_COMPOUND_LIKELIHOOD; } public String[] getParserNames() { return new String[]{getParserName()}; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { ThreadedCompoundLikelihood compoundLikelihood = new ThreadedCompoundLikelihood(); for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof Likelihood) { compoundLikelihood.addLikelihood((Likelihood) xo.getChild(i)); } else { Object rogueElement = xo.getChild(i); throw new XMLParseException("An element (" + rogueElement + ") which is not a likelihood has been added to a " + THREADED_COMPOUND_LIKELIHOOD + " element"); } } return compoundLikelihood; } /** * Main run loop */ public void run() { while (true) { if (caller != null) { synchronized (result) { result = caller.call(); resultAvailable = true; caller = null; } } } } public Double getResult() { if (resultAvailable) { resultAvailable = false; return result; } return null; } private LikelihoodCaller caller = null; private Double result = Double.NaN; private boolean resultAvailable = false; } }
package dr.inference.operators.hmc; import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import cern.colt.matrix.linalg.Algebra; import dr.inference.hmc.GradientWrtParameterProvider; import dr.inference.hmc.HessianWrtParameterProvider; import dr.math.AdaptableCovariance; import dr.math.MathUtils; import dr.math.distributions.MultivariateNormalDistribution; import dr.math.matrixAlgebra.*; import dr.util.Transform; /** * @author Marc A. Suchard * @author Xiang Ji */ public interface MassPreconditioner { WrappedVector drawInitialMomentum(); double getVelocity(int index, ReadableVector momentum); void storeSecant(ReadableVector gradient, ReadableVector position); void updateMass(); enum Type { NONE("none") { @Override public MassPreconditioner factory(GradientWrtParameterProvider gradient, Transform transform) { return new NoPreconditioning(gradient.getDimension()); } }, DIAGONAL("diagonal") { @Override public MassPreconditioner factory(GradientWrtParameterProvider gradient, Transform transform) { return new DiagonalPreconditioning((HessianWrtParameterProvider) gradient, transform); } }, FULL("full") { @Override public MassPreconditioner factory(GradientWrtParameterProvider gradient, Transform transform) { return new FullPreconditioning((HessianWrtParameterProvider) gradient, transform); } }, SECANT("secant") { @Override public MassPreconditioner factory(GradientWrtParameterProvider gradient, Transform transform) { SecantHessian secantHessian = new SecantHessian(gradient, 3); // TODO make size an option return new Secant(secantHessian, transform); } }, ADAPTIVE("adaptive") { @Override public MassPreconditioner factory(GradientWrtParameterProvider gradient, Transform transform) { AdaptableCovariance adaptableCovariance = new AdaptableCovariance(gradient.getDimension()); return new AdaptivePreconditioning(gradient, adaptableCovariance, transform, gradient.getDimension()); } }; private final String name; Type(String name) { this.name = name; } public abstract MassPreconditioner factory(GradientWrtParameterProvider gradient, Transform transform); public String getName() { return name; } public static Type parseFromString(String text) { for (Type type : Type.values()) { if (type.name.toLowerCase().compareToIgnoreCase(text) == 0) { return type; } } return Type.NONE; } } class NoPreconditioning implements MassPreconditioner { final int dim; NoPreconditioning(int dim) { this.dim = dim; } @Override public WrappedVector drawInitialMomentum() { double[] momentum = new double[dim]; for (int i = 0; i < dim; ++i) { momentum[i] = MathUtils.nextGaussian(); } return new WrappedVector.Raw(momentum); } @Override public double getVelocity(int i, ReadableVector momentum) { return momentum.get(i); } @Override public void storeSecant(ReadableVector gradient, ReadableVector position) { } @Override public void updateMass() { // Do nothing } } abstract class HessianBased implements MassPreconditioner { final protected int dim; final protected HessianWrtParameterProvider hessian; final protected Transform transform; double[] inverseMass; // TODO Should probably make a TransformedHessian so that this class does not need to know about transformations HessianBased(HessianWrtParameterProvider hessian, Transform transform) { this(hessian, transform, hessian.getDimension()); } HessianBased(HessianWrtParameterProvider hessian, Transform transform, int dim) { this.dim = dim; this.hessian = hessian; this.transform = transform; initializeMass(); } public void storeSecant(ReadableVector gradient, ReadableVector position) { // Do nothing } abstract protected void initializeMass(); abstract protected double[] computeInverseMass(); public void updateMass() { this.inverseMass = computeInverseMass(); } } class DiagonalPreconditioning extends HessianBased { AdaptableCovariance adaptableCovariance; //TODO: make an AdaptableVector class DiagonalPreconditioning(HessianWrtParameterProvider hessian, Transform transform) { super(hessian, transform); this.adaptableCovariance = new AdaptableCovariance(hessian.getDimension()); } @Override protected void initializeMass() { double[] result = new double[dim]; for (int i = 0; i < dim; i++) { result[i] = 1.0; } inverseMass = result; } @Override public WrappedVector drawInitialMomentum() { double[] momentum = new double[dim]; for (int i = 0; i < dim; i++) { momentum[i] = MathUtils.nextGaussian() * Math.sqrt(1.0 / inverseMass[i]); } return new WrappedVector.Raw(momentum); } @Override protected double[] computeInverseMass() { double[] newDiagonalHessian = hessian.getDiagonalHessianLogDensity(); if (transform != null) { double[] untransformedValues = hessian.getParameter().getParameterValues(); double[] gradient = hessian.getGradientLogDensity(); newDiagonalHessian = transform.updateDiagonalHessianLogDensity( newDiagonalHessian, gradient, untransformedValues, 0, dim ); } adaptableCovariance.update(new WrappedVector.Raw(newDiagonalHessian)); return boundMassInverse(((WrappedVector)adaptableCovariance.getMean()).getBuffer()); } private double[] boundMassInverse(double[] diagonalHessian) { double sum = 0.0; final double lowerBound = 1E-2; //TODO bad magic numbers final double upperBound = 1E2; double[] boundedMassInverse = new double[dim]; for (int i = 0; i < dim; i++) { boundedMassInverse[i] = -1.0 / diagonalHessian[i]; if (boundedMassInverse[i] < lowerBound) { boundedMassInverse[i] = lowerBound; } else if (boundedMassInverse[i] > upperBound) { boundedMassInverse[i] = upperBound; } sum += 1.0 / boundedMassInverse[i]; } final double mean = sum / dim; for (int i = 0; i < dim; i++) { boundedMassInverse[i] = boundedMassInverse[i] * mean; } return boundedMassInverse; } @Override public double getVelocity(int i, ReadableVector momentum) { return momentum.get(i) * inverseMass[i]; } } class FullPreconditioning extends HessianBased { FullPreconditioning(HessianWrtParameterProvider hessian, Transform transform) { super(hessian, transform); } FullPreconditioning(HessianWrtParameterProvider hessian, Transform transform, int dim) { super(hessian, transform, dim); } @Override protected void initializeMass() { double[] result = new double[dim * dim]; for (int i = 0; i < dim; i++) { result[i * dim + i] = 1.0; } inverseMass = result; } enum PDTransformMatrix{ Invert("Transform inverse matrix into a PD matrix") { @Override protected void transformEigenvalues(DoubleMatrix1D eigenvalues) { inverseNegateEigenvalues(eigenvalues); } }, Default("Transform matrix into a PD matrix") { @Override protected void transformEigenvalues(DoubleMatrix1D eigenvalues) { negateEigenvalues(eigenvalues); } }; String desc; PDTransformMatrix(String s) { desc = s; } public String toString() { return desc; } private static final double MIN_EIGENVALUE = -10.0; // TODO Bad magic number private static final double MAX_EIGENVALUE = -0.5; // TODO Bad magic number private void boundEigenvalues(DoubleMatrix1D eigenvalues) { for (int i = 0; i < eigenvalues.cardinality(); ++i) { if (eigenvalues.get(i) > MAX_EIGENVALUE) { eigenvalues.set(i, MAX_EIGENVALUE); } else if (eigenvalues.get(i) < MIN_EIGENVALUE) { eigenvalues.set(i, MIN_EIGENVALUE); } } } private void scaleEigenvalues(DoubleMatrix1D eigenvalues) { double sum = 0.0; for (int i = 0; i < eigenvalues.cardinality(); ++i) { sum += eigenvalues.get(i); } double mean = -sum / eigenvalues.cardinality(); for (int i = 0; i < eigenvalues.cardinality(); ++i) { eigenvalues.set(i, eigenvalues.get(i) / mean); } } protected void normalizeEigenvalues(DoubleMatrix1D eigenvalues) { boundEigenvalues(eigenvalues); scaleEigenvalues(eigenvalues); } protected void inverseNegateEigenvalues(DoubleMatrix1D eigenvalues) { for (int i = 0; i < eigenvalues.cardinality(); i++) { eigenvalues.set(i, -1.0 / eigenvalues.get(i)); } } protected void negateEigenvalues(DoubleMatrix1D eigenvalues) { for (int i = 0; i < eigenvalues.cardinality(); i++) { eigenvalues.set(i, -eigenvalues.get(i)); } } public double[] transformMatrix(double[][] inputMatrix, int dim) { Algebra algebra = new Algebra(); DoubleMatrix2D H = new DenseDoubleMatrix2D(inputMatrix); RobustEigenDecomposition decomposition = new RobustEigenDecomposition(H); DoubleMatrix1D eigenvalues = decomposition.getRealEigenvalues(); normalizeEigenvalues(eigenvalues); DoubleMatrix2D V = decomposition.getV(); transformEigenvalues(eigenvalues); double[][] negativeHessianInverse = algebra.mult( algebra.mult(V, DoubleFactory2D.dense.diagonal(eigenvalues)), algebra.inverse(V) ).toArray(); double[] massArray = new double[dim * dim]; for (int i = 0; i < dim; i++) { System.arraycopy(negativeHessianInverse[i], 0, massArray, i * dim, dim); } return massArray; } abstract protected void transformEigenvalues(DoubleMatrix1D eigenvalues); } private double[] computeInverseMass(WrappedMatrix.ArrayOfArray hessianMatrix, GradientWrtParameterProvider gradientProvider, PDTransformMatrix pdTransformMatrix) { double[][] transformedHessian = hessianMatrix.getArrays(); if (transform != null) { // TODO: change 0 matrix into general TransformationHessian transformedHessian = transform.updateHessianLogDensity(transformedHessian, new double[dim][dim], gradientProvider.getGradientLogDensity(), gradientProvider.getParameter().getParameterValues(), 0, dim); } return pdTransformMatrix.transformMatrix(transformedHessian, dim); } @Override protected double[] computeInverseMass() { //TODO: change to ReadableMatrix WrappedMatrix.ArrayOfArray hessianMatrix = new WrappedMatrix.ArrayOfArray(hessian.getHessianLogDensity()); return computeInverseMass(hessianMatrix, hessian, PDTransformMatrix.Invert); } @Override public WrappedVector drawInitialMomentum() { MultivariateNormalDistribution mvn = new MultivariateNormalDistribution( new double[dim], toArray(inverseMass, dim, dim) ); return new WrappedVector.Raw(mvn.nextMultivariateNormal()); } @Override public double getVelocity(int i, ReadableVector momentum) { double velocity = 0.0; for (int j = 0; j < dim; ++j) { velocity += inverseMass[i * dim + j] * momentum.get(j); } return velocity; } private static double[][] toArray(double[] vector, int rowDim, int colDim) { double[][] array = new double[rowDim][]; for (int row = 0; row < rowDim; ++row) { array[row] = new double[colDim]; System.arraycopy(vector, colDim * row, array[row], 0, colDim); } return array; } } class Secant extends FullPreconditioning { private final SecantHessian secantHessian; Secant(SecantHessian secantHessian, Transform transform) { super(secantHessian, transform); this.secantHessian = secantHessian; } @Override public void storeSecant(ReadableVector gradient, ReadableVector position) { secantHessian.storeSecant(gradient, position); } } class AdaptivePreconditioning extends FullPreconditioning { private final AdaptableCovariance adaptableCovariance; private final GradientWrtParameterProvider gradientProvider; AdaptivePreconditioning(GradientWrtParameterProvider gradientProvider, AdaptableCovariance adaptableCovariance, Transform transform, int dim) { super(null, transform, dim); this.adaptableCovariance = adaptableCovariance; this.gradientProvider = gradientProvider; } @Override protected double[] computeInverseMass() { WrappedMatrix.ArrayOfArray covariance = (WrappedMatrix.ArrayOfArray) adaptableCovariance.getCovariance(); return super.computeInverseMass(covariance, gradientProvider, PDTransformMatrix.Default); } @Override public void storeSecant(ReadableVector gradient, ReadableVector position) { // adaptableCovariance.update(gradient); adaptableCovariance.update(position); } } }
package edu.dynamic.dynamiz.controller; import static org.junit.Assert.*; import org.junit.Test; import edu.dynamic.dynamiz.structure.ErrorFeedback; import edu.dynamic.dynamiz.structure.Feedback; import edu.dynamic.dynamiz.structure.SuccessFeedback; import edu.dynamic.dynamiz.structure.ToDoItem; public class ControllerTest { @Test public void testExecuteCommand() throws Exception{ Feedback feedback; Controller controller = new Controller(); //Adds a ToDoItem feedback = controller.executeCommand("add Buy newspaper"); assertEquals("add", feedback.getCommandType()); assertEquals("add Buy newspaper", feedback.getOriginalCommand()); //Adds an event feedback = controller.executeCommand("add Meeting priority 2 from 7/10/2014"); feedback = controller.executeCommand("add CS2103T Tutorial from 8/10/2014 13:00 to 8/10/2014 14:00"); //Deletes and item feedback = controller.executeCommand("delete A2"); assertEquals("delete", feedback.getCommandType()); assertEquals("delete A2", feedback.getOriginalCommand()); //Updates an event feedback = controller.executeCommand("update A1 from 27/9/2014 17:30"); assertEquals("update", feedback.getCommandType()); assertEquals("update A1 from 27/9/2014 17:30", feedback.getOriginalCommand()); feedback = controller.executeCommand("update A1 to 27/9/2014 20:00"); assertEquals("update", feedback.getCommandType()); assertEquals("update A1 to 27/9/2014 20:00", feedback.getOriginalCommand()); //Adds a deadline to ToDoItem. feedback = controller.executeCommand("update A4 by 6/10/2014"); assertTrue(feedback instanceof SuccessFeedback); //Item does not get changed due to error. feedback= controller.executeCommand("update A4 Go shopping"); assertTrue(feedback instanceof SuccessFeedback); //Tests program's handling of invalid options. feedback = controller.executeCommand("update A4 from to"); assertFalse(feedback instanceof SuccessFeedback); //System.out.println(((SuccessFeedback)feedback).getAffectedItems()[0]); //System.out.println(((SuccessFeedback)feedback).getAffectedItems()[1]); //Lists the items in storage feedback = controller.executeCommand("list"); assertEquals("list", feedback.getCommandType()); ToDoItem[] list = ((SuccessFeedback)feedback).getAffectedItems(); for(ToDoItem item: list){ System.out.println(item); } System.out.println(); feedback = controller.executeCommand("search CS"); list = ((SuccessFeedback)feedback).getAffectedItems(); for(ToDoItem item: list){ System.out.println(item); } System.out.println(); //Erroneous test case. To be dealt with in later stages. //feedback = controller.executeCommand("add"); } }
package edu.washington.escience.myria.api; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; 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 javax.ws.rs.core.UriInfo; import edu.washington.escience.myria.CsvTupleWriter; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.MyriaConstants; import edu.washington.escience.myria.RelationKey; import edu.washington.escience.myria.Schema; import edu.washington.escience.myria.TupleWriter; import edu.washington.escience.myria.parallel.Server; /** * Class that handles logs. */ @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/logs") public final class LogResource { /** The Myria server running on the master. */ @Context private Server server; /** * Get profiling logs of a query. * * @param queryId query id. * @param fragmentId the fragment id. < 0 means all * @param uriInfo the URL of the current request. * @return the profiling logs of the query across all workers * @throws DbException if there is an error in the database. */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("profiling") public Response getProfileLogs(@QueryParam("queryId") final Long queryId, @DefaultValue("-1") @QueryParam("fragmentId") final long fragmentId, @Context final UriInfo uriInfo) throws DbException { if (queryId == null) { throw new MyriaApiException(Status.BAD_REQUEST, "Query ID missing."); } return getLogs(queryId, fragmentId, MyriaConstants.PROFILING_RELATION, MyriaConstants.PROFILING_SCHEMA); } /** * Get sent logs of a query. * * @param queryId query id. * @param fragmentId the fragment id. < 0 means all * @param uriInfo the URL of the current request. * @return the profiling logs of the query across all workers * @throws DbException if there is an error in the database. */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("sent") public Response getSentLogs(@QueryParam("queryId") final Long queryId, @DefaultValue("-1") @QueryParam("fragmentId") final long fragmentId, @Context final UriInfo uriInfo) throws DbException { if (queryId == null) { throw new MyriaApiException(Status.BAD_REQUEST, "Query ID missing."); } return getLogs(queryId, fragmentId, MyriaConstants.LOG_SENT_RELATION, MyriaConstants.LOG_SENT_SCHEMA); } /** * @param queryId query id * @param fragmentId the fragment id to return data for. All fragments, if < 0. * @param relationKey the relation to stream from * @param schema the schema of the relation to stream from * @return the profiling logs of the query across all workers * @throws DbException if there is an error in the database. */ private Response getLogs(final long queryId, final long fragmentId, final RelationKey relationKey, final Schema schema) throws DbException { ResponseBuilder response = Response.ok(); response.type(MediaType.TEXT_PLAIN); PipedOutputStream writerOutput = new PipedOutputStream(); PipedInputStream input; try { input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE); } catch (IOException e) { throw new DbException(e); } PipedStreamingOutput entity = new PipedStreamingOutput(input); response.entity(entity); TupleWriter writer = new CsvTupleWriter(writerOutput); try { server.startLogDataStream(queryId, fragmentId, writer, relationKey, schema); } catch (IllegalArgumentException e) { throw new MyriaApiException(Status.BAD_REQUEST, e); } return response.build(); } /** * Get the number of workers working on a fragment based on profiling logs of a query for the root operators. * * @param queryId query id. * @param fragmentId the fragment id. * @param uriInfo the URL of the current request. * @return the profiling logs of the query across all workers * @throws DbException if there is an error in the database. */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("histogram") public Response getHistogram(@QueryParam("queryId") final Long queryId, @QueryParam("fragmentId") final Long fragmentId, @Context final UriInfo uriInfo) throws DbException { if (queryId == null) { throw new MyriaApiException(Status.BAD_REQUEST, "Query ID missing."); } if (fragmentId == null) { throw new MyriaApiException(Status.BAD_REQUEST, "Fragment ID missing."); } ResponseBuilder response = Response.ok(); response.type(MediaType.TEXT_PLAIN); PipedOutputStream writerOutput = new PipedOutputStream(); PipedInputStream input; try { input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE); } catch (IOException e) { throw new DbException(e); } PipedStreamingOutput entity = new PipedStreamingOutput(input); response.entity(entity); TupleWriter writer = new CsvTupleWriter(writerOutput); try { server.startHistogramDataStream(queryId, fragmentId, writer); } catch (IllegalArgumentException e) { throw new MyriaApiException(Status.BAD_REQUEST, e); } return response.build(); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotTemplate extends IterativeRobot { NetworkTable server = NetworkTable.getTable("smartDashboard"); SmartDashboard smart; Gyro gyro; Joystick xBox; Jaguar jagleft1, jagright1 /* * , jagleft2, jagright2 */; Solenoid /* * gear1, gear2, */ fireOn, fireOff; //963-2568 Connor Phone Number Relay light, compressor; double speed, turn, leftspeed, rightspeed, conf; int i = 0, endTimer = 0, noWait = 0, e = 0, gyroTimer = 0; boolean shooting = false, atShoot, afterShoot, checkGyro; Drive drive; AnalogChannel ultrasonic; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { xBox = new Joystick(1); jagleft1 = new Jaguar(2, 1); jagright1 = new Jaguar(2, 2); //jagleft2 = new Jaguar(3); //jagright2 = new Jaguar(4); //gear1 = new Solenoid(1); //gear2 = new Solenoid(2); fireOff = new Solenoid(1); fireOn = new Solenoid(2); gyro = new Gyro(1); ultrasonic = new AnalogChannel(2); light = new Relay(2, 1); compressor = new Relay(2, 2); drive = new Drive(xBox, jagleft1, jagright1 //, jagleft2, jagright2, gear1, gear2 ); } /** * This function is called periodically during autonomous */ public void autonomousInit() { compressor.set(Relay.Value.kOn); gyro.reset(); endTimer = 0; conf = 0; light.set(Relay.Value.kOn); noWait = 0; gyroTimer = 0; fireOff.set(true); fireOn.set(false); atShoot = false; afterShoot = false; checkGyro = false; } public void autonomousPeriodic() { compressor.set(Relay.Value.kOn); light.set(Relay.Value.kOn); System.out.println(conf); if (!checkGyro && !atShoot) { //if program does not know it's in range, do the following if (ultrasonic.getVoltage() > 0.43) { //if not in range, do the following conf = conf + SmartDashboard.getNumber("Confidence") - 70; //add to the total confidence jagleft1.set(-0.348); //move towards the goal jagright1.set(0.3); System.out.println("Driving forwards."); } else { //once in range, do the follwing jagleft1.set(0); //stop moving forwards jagright1.set(0); checkGyro = true; // tell the program to check the gyro System.out.println("Checking gyro."); } } if (checkGyro) { gyroTimer++; if (gyro.getAngle() < -2) { //if the robot is pointed to the left, do the following jagleft1.set(-0.108); //turn right jagright1.set(-0.1); System.out.println("Orienting right."); } if (gyro.getAngle() > 2) { //if the robot is pointed to the right, do the following jagleft1.set(0.108); //turn left jagright1.set(0.1); System.out.println("Orienting left."); } if (gyro.getAngle() > -2 && gyro.getAngle() < 2) { // if the robot is pointed towards the goal, do the following jagleft1.set(0); //stop the motion of the robot jagright1.set(0); checkGyro = false; //stop looking at the gyro atShoot = true; //tell the program that the robot is in position System.out.println("Oriented."); } if (gyroTimer == 30) { //after three fifths second of checking the gyro, do the following jagleft1.set(0); //stop the motion of the robot jagright1.set(0); checkGyro = false; //stop looking at the gyro atShoot = true; //tell the program that the robot is in position System.out.println("Gyro check timed out."); } } /* * if (atShoot && ultrasonic.getVoltage()<30){ * jagleft1.set(0.106); * jagright1.set(-0.106); * } * if (atShoot && ultrasonic.getVoltage()>30 && ultrasonic.getVoltage()<50){ * jagleft1.set(0); * jagright1.set(0); * if (atShoot && ultrasonic.getVoltage()>50){ * jagleft1.set(-0.106); * jagright1.set(0.106); * } */ if (atShoot && !afterShoot) { //once in position, do the following if (conf >= 40) { //if the target has been seen, do the following System.out.println("Saw Target."); fireOff.set(false); fireOn.set(true); afterShoot = true; //tell the program it has fired System.out.println("Launching."); } if (conf < 40) { //if the target has not been seen, do the following if (noWait == 0) { //reset the timer for this occasion System.out.println("Did not see target."); } noWait++; //count the timer up if (noWait == 200) { //once the rimer reaches 4 seconds, do the following fireOff.set(false); //launch the catapult fireOn.set(true); afterShoot = true; //tell the program it has fired System.out.println("Launching."); } } } if (afterShoot) { //once the program knows it has fired, do the following if (endTimer < 100) { // for two seconds after firing, do the following endTimer++; //run the ending timer jagleft1.set(0); //stop any motion of the robot jagright1.set(0); if (endTimer == 100) { //at end of autonomous, do the following System.out.println("Autonomous Complete."); } } } } /** * This function is called periodically during operator control */ public void teleopInit() { compressor.set(Relay.Value.kOn); light.set(Relay.Value.kOff); drive.start(); drive.setRun(true); fireOff.set(true); fireOn.set(false); } public void teleopPeriodic() { light.set(Relay.Value.kOff); compressor.set(Relay.Value.kOn); light.set(Relay.Value.kOff); if (xBox.getRawAxis(3) <= -0.9 && !shooting) { shooting = true; } if (shooting) { i++; fireOff.set(false); fireOn.set(true); if (i >= 100) { fireOff.set(true); fireOn.set(false); i = 0; shooting = false; } } } public void disabledInit() { //drive.setRun(false); } /** * This function is called periodically during test mode */ public void testPeriodic() { compressor.set(Relay.Value.kOn); fireOff.set(true); fireOn.set(false); } }
package edu.wpi.first.wpilibj.templates; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.CounterBase; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.image.BinaryImage; import edu.wpi.first.wpilibj.image.ColorImage; import edu.wpi.first.wpilibj.image.CriteriaCollection; import edu.wpi.first.wpilibj.image.NIVision; import edu.wpi.first.wpilibj.image.NIVisionException; import edu.wpi.first.wpilibj.image.ParticleAnalysisReport; public class RobotTemplate extends SimpleRobot { /* * Declaring the objects */ //Drivers Station output box declaration DriverStationLCD robot = DriverStationLCD.getInstance(); /* * Joysticks */ Timer timer = new Timer(); Joystick chassis1 = new Joystick(1); Joystick chassis2 = new Joystick(2); Joystick climbing1 = new Joystick(3); Joystick climbing2 = new Joystick(4); /* * This is used for chassis (the wheels) * drives the robot arround */ RobotDrive chassis = new RobotDrive(1, 2); //climbing motors declarations RobotDrive climb = new RobotDrive(3, 4); /* * used for camera control */ Servo servoHorizontal = new Servo(7); Servo servoVertical = new Servo(8); /* * used for climbing */ Encoder firstEncoder = new Encoder(6, 7, false, CounterBase.EncodingType.k1X); Encoder secondEncoder = new Encoder(9, 10, false, CounterBase.EncodingType.k1X); /* * used for climbing */ DigitalInput limitSwitch1 = new DigitalInput(12); DigitalInput limitSwitch2 = new DigitalInput(13); /* * The motors that will throw the frisbee */ RobotDrive shooter = new RobotDrive(10, 9); /* * Controls the window motor that will be used to load the frisbees into the shooter */ Victor loader = new Victor(6); Compressor compressor1 = new Compressor(14,1); DoubleSolenoid DS = new DoubleSolenoid (2, 3); /* * Sonar declaration * *Note* sonar is declared as an AnalogChannel because the sonar * can not go through the digital sidecar * (it can, it just requires more soldering) */ //private AnalogChannel sonar = new AnalogChannel(5); /* * These variables are used with the Camera */ private double vert = 90; private double hori = 90; private double UIVert = 90; private double UIHori = 90; /* * This is the declaration of the variables that will be used in the print * Function */ double sonarDistance; double encoder1; double encoder2; /* * This is the declaration of the all the variabels that are used with the * spike relay */ Relay relay = new Relay(2); public boolean driveMode = true; //this counter will prevent the printing screen from flashing as much private int counter = 0; private boolean shoot = false; private final int climbingHeight1=-692; private final int climbingHeight2=-3530; private final int loadingHeight1=6863; private final int loadingHeight2=11369; private final int shootingHeight1=-3904; private final int shootingHeight2=-4981; private final int blockingHeight1=-22600; private final int blockingHeight2=-11100; /* * Camera's final variabels */ private final int cameraMaxAngle=179; private final int cameraMinAngle=1; int climbingCounter=0; boolean encoder1Stop=false; boolean encoder2Stop=false; boolean adjustLoading=false; boolean adjustShooting=false; boolean adjustClimbing=false; boolean adjustZero=false; final int encoderTreshold=100; int autonomousBuffer=0; boolean isShooterEnabled=false; boolean isLoaderEnabled=false; boolean isShooting=false; final double pixelsT = 640; final double visionR = 47*Math.PI/180; final double lengthG = 36/2; final double desiredDistance = 60; AxisCamera camera = AxisCamera.getInstance(); CriteriaCollection cc; /* * This is automatically called at the beginning of the competition */ protected void robotInit() { getWatchdog().kill(); firstEncoder.setDistancePerPulse(.004); firstEncoder.start(); secondEncoder.setDistancePerPulse(.004); secondEncoder.start(); cc = new CriteriaCollection(); cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, 30, 400, false); cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, 40, 400, false); timer.start(); } /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { getWatchdog().kill(); timer.reset(); timer.start(); chassis.setSafetyEnabled(false); climb.setSafetyEnabled(false); shooter.setSafetyEnabled(false); loader.setSafetyEnabled(false); loader.set(0); //move(-1,-1,100); while (isAutonomous() && isEnabled()) { encoder1 = firstEncoder.get(); encoder2 = secondEncoder.get(); // shooter.tankDrive(-1, 1); // shootHeight(); // if(timer.get() > 4.0) // loader.set(.3); // isLoaderEnabled=true; /*else{ loader.set(0); isLoaderEnabled=false; }*/ relay.set(Relay.Value.kForward); centerCalculate(); print(); } shooter.tankDrive(0, 0); } /* * Called durring autonomous to control the robot */ public void move(double left, double right, double time) { chassis.tankDrive(left, right); Timer.delay(time); chassis.tankDrive(0.0, 0.0); } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { climb.setSafetyEnabled(true); chassis.setSafetyEnabled(true); loader.setSafetyEnabled(true); relay.set(Relay.Value.kForward); while (isOperatorControl() && isEnabled()) { compressor1.start(); if (climbing1.getTrigger()){ DS.set(DoubleSolenoid.Value.kForward); } else { DS.set(DoubleSolenoid.Value.kReverse); } if (climbing1.getRawButton(8)){ relay.set(Relay.Value.kForward); } else if (climbing1.getRawButton(9)){ relay.set(Relay.Value.kOff); } chassis.tankDrive((-1) * chassis1.getAxis(Joystick.AxisType.kY), (-1) * chassis2.getAxis(Joystick.AxisType.kY)); // compressor1.start(); limitSwitchCheck(); cameraControl(); encoder(); /* * Shooting */ shooting(); loader(); handleEncoderPresets(); print(); Timer.delay(0.01); //Pauses for .01 seconds before starting the loop again }//end of the while loop for OpperatorControl } /** * This function is called once each time the robot enters test mode. */ public void test() { } /* * * Camera Controls: * Button 5 for pan right * Button 4 for pan left * Button 3 for pan up * Button 2 for pan down * Trigger pan center * * Takes 2 Servos * *Note* Verify that each servo has a power relay * Currently wired to 7 and 8 * * */ public void cameraControl() { if (chassis2.getRawButton(3) || climbing2.getRawButton(3) && vert < cameraMaxAngle) { vert += .5; servoVertical.setAngle(vert); } else if (chassis2.getRawButton(2) || climbing2.getRawButton(2) && vert > cameraMinAngle) { vert -= .5; servoVertical.setAngle(vert); } if (chassis2.getRawButton(4) || climbing2.getRawButton(4) && hori > cameraMinAngle) { hori -= .5; servoHorizontal.setAngle(hori); } else if (chassis2.getRawButton(5) || climbing2.getRawButton(5) && hori < cameraMaxAngle) { hori += .5; servoHorizontal.setAngle(hori); }/* * if the camera gets bumped in any direction, it will automatically reset */ if (servoVertical.getAngle() <= (vert - .1) || servoVertical.getAngle() >= (vert + .1)) { servoVertical.setAngle(vert); } if (servoHorizontal.getAngle() <= (hori - .1) || servoHorizontal.getAngle() >= (hori + .1)) { servoHorizontal.setAngle(hori); } /* * used for camera presets * Hypothetically used to quickly check certain parts of the robot */ if (chassis2.getRawButton(1) || climbing2.getRawButton(1)) { vert = 90; hori = 90; } if (chassis1.getRawButton(3) || climbing1.getRawButton(3) && vert < cameraMaxAngle) { vert = 135; hori = 90; servoVertical.setAngle(vert); } else if (chassis1.getRawButton(2) || climbing1.getRawButton(2) && vert > cameraMinAngle) { vert = 45; hori = 90; servoVertical.setAngle(vert); } if (chassis1.getRawButton(4) || climbing1.getRawButton(4) && hori > cameraMinAngle) { vert = 90; hori = 45; servoHorizontal.setAngle(hori); } else if (chassis1.getRawButton(5) || climbing1.getRawButton(5) && hori < cameraMaxAngle) { vert = 90; hori = 135; servoHorizontal.setAngle(hori); } /* * UI controls * used to catch values that the user wants to save for the camera's location and direction */ if (chassis1.getRawButton(8)) { UIHori = hori; UIVert = vert; } if (chassis1.getRawButton(9)) { hori = UIHori; vert = UIVert; } } public void limitSwitchCheck() { //if (limitSwitch1.get()) { //if (climbing2.getMagnitude() > 0) { // climb.tankDrive(0, 0); //} else { climb.tankDrive(climbing1.getAxis(Joystick.AxisType.kY)*2, (-2) * climbing2.getAxis(Joystick.AxisType.kY)); //climb.setLeftRightMotorOutputs(climbing1.getAxis(Joystick.AxisType.kY), (-1) * climbing2.getAxis(Joystick.AxisType.kY)); //if (limitSwitch2.get()) { //if (climbing1.getMagnitude() < 0) { // climb.tankDrive(0, 0); //} else { // climb.tankDrive(climbing1.getAxis(Joystick.AxisType.kY), (-1) * climbing2.getAxis(Joystick.AxisType.kY)); } public void shooting() { if (climbing1.getRawButton(11)) { isShooting=true; } else if(climbing1.getRawButton(10)){ isShooting=false; } if(isShooting) { shooter.tankDrive(-1, 1); } else { shooter.tankDrive(0,0); } } public void loader() { // if(climbing1.getRawButton(7)){ // relay.set(Relay.Value.kOn); // else{ // relay.set(Relay.Value.kOff); } public void encoder() { /* * This should check to see if the user is pressing the reset button * if they are then the encoder values will reset * otherwise, the encoder values will update */ if (chassis1.getRawButton(8) && chassis2.getRawButton(8)) { encoder1 = 0; encoder2 = 0; firstEncoder.free(); secondEncoder.free(); firstEncoder.start(); secondEncoder.start(); } else { encoder1 = firstEncoder.get(); encoder2 = secondEncoder.get(); } } public void print() { counter++; if (counter == 100) { //this will prevent the print screen from getting cluttered clearPrint(); counter = 0; } robot.println(DriverStationLCD.Line.kUser1, 1, "Solenoid: " + DS.get()); robot.println(DriverStationLCD.Line.kUser2, 1, "pv: "+compressor1.getPressureSwitchValue()); robot.println(DriverStationLCD.Line.kUser3, 1, "Loading: " + isLoaderEnabled); robot.println(DriverStationLCD.Line.kUser4, 1, "Shooting: "+shooter.isAlive()); robot.println(DriverStationLCD.Line.kUser5, 1, "Timer: "+timer.get()); // robot.println(DriverStationLCD.Line.kUser6, 1, ""); robot.updateLCD(); } /* * By calling this function, you clear the output for the drivers station * This function does not require any parameters */ public void clearPrint() { //this prints out a bunch of blank lines in order to clear the drivers station output screen robot.println(DriverStationLCD.Line.kUser1, 1, " "); robot.println(DriverStationLCD.Line.kUser2, 1, " "); robot.println(DriverStationLCD.Line.kUser3, 1, " "); robot.println(DriverStationLCD.Line.kUser4, 1, " "); robot.println(DriverStationLCD.Line.kUser5, 1, " "); robot.println(DriverStationLCD.Line.kUser6, 1, " "); robot.updateLCD(); //this updates the drivers station output screen, allowing everything to show up correctly } public void handleEncoderPresets() { // if(climbing2.getRawButton(6)||chassis2.getRawButton(6)) { // loadHeight(); // else if(climbing2.getRawButton(7)||chassis2.getRawButton(7)) { // shootHeight(); // else if(climbing2.getRawButton(11)||chassis2.getRawButton(11)) { // climbHeight(); // else if((climbing1.getRawButton(8)&&climbing2.getRawButton(8)) || (chassis1.getRawButton(8)&&chassis2.getRawButton(8))) { // adjustZero=true; // moveToZero(); // else if(climbing2.getRawButton(10)||chassis2.getRawButton(10)) { // blockingHeight(); } public boolean moveToZero() { double pos1=0; double pos2=0; pos1 = calculateThrottle(encoder1, 0); pos2 = calculateThrottle(encoder2, 0); climb.tankDrive(pos1, (-1)*pos2); boolean atPosition = false; if (Math.abs(pos1) < 0.01 && Math.abs(pos2) < 0.01) { atPosition = true; } return atPosition; } public boolean blockingHeight() { double pos1=0; double pos2=0; pos1 = calculateThrottle(encoder1, blockingHeight1); pos2 = calculateThrottle(encoder2, blockingHeight2); climb.tankDrive(pos1, (-1)*pos2); boolean atPosition = false; if (Math.abs(pos1) < 0.01 && Math.abs(pos2) < 0.01) { atPosition = true; } return atPosition; } public boolean shootHeight() { climbingCounter++; double pos1=0; double pos2=0; pos1 = calculateThrottle(encoder1, shootingHeight1); pos2 = calculateThrottle(encoder2, shootingHeight2); climb.tankDrive(pos1, (-1)*pos2); boolean atPosition = false; if (Math.abs(pos1) < 0.01 && Math.abs(pos2) < 0.01) { atPosition = true; } return atPosition; } public boolean loadHeight() { double pos1=0; double pos2=0; pos1 = calculateThrottle(encoder1, loadingHeight1); pos2 = calculateThrottle(encoder2, loadingHeight2); climb.tankDrive(pos1, (-1)*pos2); boolean atPosition = false; if (Math.abs(pos1) < 0.01 && Math.abs(pos2) < 0.01) { atPosition = true; } return atPosition; } private double calculateThrottle(double currPos, double commandedPos) { double throttle = 0.0; double delta = Math.abs(currPos - commandedPos); if (delta > 150) { throttle = 1.0; } else if (delta > 100) { throttle = 0.5; } else if (delta > 50) { throttle = 0.275; } else { throttle = 0; } if (currPos > commandedPos) { throttle *= -1; } return throttle; } public void climbHeight() { double pos1=0; double pos2=0; pos1 = calculateThrottle(encoder1, climbingHeight1); pos2 = calculateThrottle(encoder2, climbingHeight2); climb.tankDrive(pos1, (-1)*pos2); boolean atPosition = false; if (Math.abs(pos1) < 0.01 && Math.abs(pos2) < 0.01) { atPosition = true; } } private void centerCalculate() { ColorImage image = null; //BinaryImage thresholdRGBImage = null; BinaryImage thresholdHSIImage = null; BinaryImage bigObjectsImage= null; BinaryImage convexHullImage=null; BinaryImage filteredImage = null; try { image = camera.getImage(); camera.writeBrightness(50); //image.write("originalImage.jpg"); //thresholdRGBImage = image.thresholdRGB(0, 45, 25, 255, 0, 47); //thresholdRGBImage.write("thresholdRGBImage.bmp"); thresholdHSIImage = image.thresholdHSI(0, 255, 0, 255, 200, 255); //thresholdHSIImage.write("thresholdHSIImage.bmp"); bigObjectsImage = thresholdHSIImage.removeSmallObjects(false, 2); //bigObjectsImage.write("bigObjectsImage.bmp"); convexHullImage = bigObjectsImage.convexHull(false); //convexHullImage.write("convexHullImage.bmp"); filteredImage = convexHullImage.particleFilter(cc); //filteredImage.write("filteredImage.bmp"); ParticleAnalysisReport[] reports = filteredImage.getOrderedParticleAnalysisReports(); String output; // for(int i = 0; i<reports.length+1; i++) { // robot.println(DriverStationLCD.Line.kUser6, 1, ""+reports[i].center_mass_x); // System.out.println(reports[i].center_mass_x); double pixelsM = reports[0].boundingRectWidth; double angle = pixelsM/pixelsT*visionR; double distance = lengthG/Math.tan(angle/2); robot.println(DriverStationLCD.Line.kUser6, 1, ""+distance); if(Math.abs(distance-desiredDistance)>6){ if(distance < desiredDistance){ chassis.tankDrive(-.5, -.5); } else if(distance>desiredDistance){ chassis.tankDrive(.5, .5); } } else chassis.tankDrive(0, 0); }catch (Exception ex) { }finally{ } try { filteredImage.free(); convexHullImage.free(); bigObjectsImage.free(); //thresholdRGBImage.free(); thresholdHSIImage.free(); image.free(); } catch (NIVisionException ex) { ex.printStackTrace(); } } } /* * ChangeLog * added in a camera position logger * chassis1 button 8 * * Organized * organized everything into functions * this should make parts of the code much easier to find * it will also make it easier for other people to understand the code * * Encoder Info * shooting position: * encoder1: -18000 * encoder2: 0 * * down * servohorizontal: 90 * servovertical: 25 * * left * * * encoder2 * 13268 * * when joystick 4 is pushed forward it increases encoder1 positivly? * backwards on 4 = encoder2 negative * forward on 3=encoder 1 negative * * encoder1: * -29229 * */ /* * autonomous notes * have the robot move using the encoders * then reset the encoders to 0 * then move again */ /* * cool things for next year * a camera on the robot that can save the mach video */ /* * Buttons needed: * Button for aiming height * Button for loading height * Button for climbing height */ /* * Buttons used * chassis2 || climbing2 .getRawButton(3) * Moves the camera UP * chassis2 || climbing2 .getRawButton(2) * Moves the camera DOWN * chassis2 || climbing2 .getRawButton(4) * Moves camera to the LEFT * chassis2 || climbing2 .getRawButton(5) * Moves camera to the RIGHT * chassis2 || climbing2 .getRawButton(1) * Resets the camera to the STARTING POSITION * chassis1 || climbing1 .getRawButton(3) * Moves the camera to the UP preset * chassis1 || climbing1 .getRawButton(2) * Moves the camera to the DOWN preset * chassis1 || climbing1 .getRawButton(4) * Moves the camera to the LEFT preset * chassis1 || climbing1 .getRawButton(5) * Moves the camera to the RIGHT preset * climbing1.getRawButton(11) * turnes the shooter ON * climbing1.getRawButton(10) * turnes the shooter OFF * climbing1.getRawButton(6) * turnes the loader ON only while this button is being pressed * chassis1 && chassis2 .getRawButton(8) * * * */ //4 3 5 //loading controler4 button6 //shooting controler4 button7 //climbing controler4 button11 //add things to the print function that will tell if the loader and the shooter are spinning //-4000 //-5000
package com.google.job.data; import com.google.common.collect.ImmutableMap; import javax.annotation.Nullable; import java.util.*; /** Class for a job post. */ public final class Job { private final String jobId; // TODO(issue/25): merge the account stuff into job post. private final JobStatus jobStatus; private final String jobTitle; private final Location jobLocation; private final String jobDescription; private final JobPayment jobPay; private final Map<String, Boolean> requirements; // requirement stable id : true/false private final long postExpiryTimestamp; private final JobDuration jobDuration; private volatile int hashCode; private Job(JobBuilder jobBuilder) { this.jobId = jobBuilder.jobId; this.jobStatus = jobBuilder.jobStatus; this.jobTitle = jobBuilder.jobTitle; this.jobLocation = jobBuilder.location; this.jobDescription = jobBuilder.jobDescription; this.jobPay = jobBuilder.jobPay; this.requirements = jobBuilder.requirements; this.postExpiryTimestamp = jobBuilder.postExpiryTimestamp; this.jobDuration = jobBuilder.jobDuration; } // No-argument constructor is needed to deserialize object when interacting with cloud firestore. public Job() { this.jobId = ""; this.jobStatus = JobStatus.ACTIVE; this.jobTitle = ""; this.jobLocation = new Location(); this.jobDescription = ""; this.jobPay = new JobPayment(); this.requirements = ImmutableMap.of(); this.postExpiryTimestamp = 0; this.jobDuration = JobDuration.OTHER; } /** Returns a builder by copying all the fields of an existing Job. */ public JobBuilder toBuilder() { JobBuilder jobBuilder = new JobBuilder(); jobBuilder.jobId = this.jobId; jobBuilder.jobStatus = this.jobStatus; jobBuilder.jobTitle = this.jobTitle; jobBuilder.location = this.jobLocation; jobBuilder.jobDescription = this.jobDescription; jobBuilder.jobPay = this.jobPay; jobBuilder.requirements = this.requirements; jobBuilder.postExpiryTimestamp = this.postExpiryTimestamp; jobBuilder.jobDuration = this.jobDuration; return jobBuilder; } /** Returns a builder. */ public static JobBuilder newBuilder() { return new JobBuilder(); } public static final class JobBuilder { // Optional parameters - initialized to default values private String jobId = ""; private Map<String, Boolean> requirements = ImmutableMap.of(); private JobDuration jobDuration = JobDuration.OTHER; // TODO(issue/25): merge the account stuff into job post. // Required parameters private long postExpiryTimestamp; @Nullable private JobStatus jobStatus; @Nullable private String jobTitle; @Nullable private Location location; @Nullable private String jobDescription; @Nullable private JobPayment jobPay; private JobBuilder() {} public JobBuilder setJobId(String jobId) { this.jobId = jobId; return this; } public JobBuilder setJobStatus(JobStatus jobStatus) { this.jobStatus = jobStatus; return this; } public JobBuilder setJobTitle(String jobTitle) throws IllegalArgumentException { this.jobTitle = jobTitle; return this; } public JobBuilder setLocation(Location location) { this.location = location; return this; } public JobBuilder setJobDescription(String jobDescription) throws IllegalArgumentException { if (jobDescription.isEmpty()) { throw new IllegalArgumentException("Empty job description provided"); } this.jobDescription = jobDescription; return this; } public JobBuilder setJobPay(JobPayment jobPay) { this.jobPay = jobPay; return this; } public JobBuilder setRequirements(Map<String, Boolean> requirements) { Map<String, Boolean> inputRequirementsMap = new HashMap<>(requirements); Set<String> requirementsSet = new HashSet<>(Requirement.getAllRequirementIds()); // Removes redundant requirement inputRequirementsMap.entrySet().removeIf(entry -> !requirementsSet.contains(entry.getKey())); // Checks if requirement missing and adds accordingly for (String requirement: requirementsSet) { if (inputRequirementsMap.containsKey(requirement)) { continue; } inputRequirementsMap.put(requirement, false); } this.requirements = ImmutableMap.copyOf(inputRequirementsMap); return this; } public JobBuilder setPostExpiry(long postExpiryTimestamp) { this.postExpiryTimestamp = postExpiryTimestamp; return this; } public JobBuilder setJobDuration(JobDuration jobDuration) { this.jobDuration = jobDuration; return this; } public Job build() { if (jobStatus == null) { throw new IllegalArgumentException("Job Status cannot be null. Please set it explicitly"); } if (jobTitle == null || jobTitle.isEmpty()) { throw new IllegalArgumentException("Job Title should be an non-empty string"); } if (location == null) { throw new IllegalArgumentException("Location cannot be null"); } if (jobDescription == null || jobDescription.isEmpty()) { throw new IllegalArgumentException("Job Description should be an non-empty string"); } if (jobPay == null) { throw new IllegalArgumentException("Job Payment cannot be null"); } if (postExpiryTimestamp == 0) { throw new IllegalArgumentException("Timestamp cannot be 0. Please provide a valid timestamp"); } return new Job(this); } } /** Returns the id for the job post. */ public String getJobId() { return jobId; } /** Returns the status of the job post, either ACTIVE, DELETED, or EXPIRED. */ public JobStatus getJobStatus() { return jobStatus; } /** Returns the job title of that post. Job title cannot be empty. */ public String getJobTitle() { return jobTitle; } /** Returns the location details of the job post. */ public Location getJobLocation() { return jobLocation; } /** Returns the job description of that post. Job description cannot be empty. */ public String getJobDescription() { return jobDescription; } /** Returns the payment details of the job post. */ public JobPayment getJobPay() { return jobPay; } /** Returns a map of requirements (stable ids) of the job post. */ public Map<String, Boolean> getRequirements() { return requirements; } /** Returns the date when the job post will expire. */ public long getPostExpiryTimestamp() { return postExpiryTimestamp; } /** Returns the duration of the job itself. */ public JobDuration getJobDuration() { return jobDuration; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Job job = (Job) o; return postExpiryTimestamp == job.postExpiryTimestamp && jobId.equals(job.jobId) && jobStatus == job.jobStatus && jobTitle.equals(job.jobTitle) && jobLocation.equals(job.jobLocation) && jobDescription.equals(job.jobDescription) && jobPay.equals(job.jobPay) && requirements.equals(job.requirements) && jobDuration.equals(job.jobDuration); } @Override public int hashCode() { if (this.hashCode != 0) { return this.hashCode; } int result = 0; int c = jobId.hashCode(); result = 31 * result + c; c = jobStatus.hashCode(); result = 31 * result + c; c = jobTitle.hashCode(); result = 31 * result + c; c = jobLocation.hashCode(); result = 31 * result + c; c = jobDescription.hashCode(); result = 31 * result + c; c = jobPay.hashCode(); result = 31 * result + c; c = requirements.hashCode(); result = 31 * result + c; c = ((Long)postExpiryTimestamp).hashCode(); result = 31 * result + c; c = jobDuration == null ? 0 : jobDuration.hashCode(); result = 31 * result + c; this.hashCode = result; return hashCode; } @Override public String toString() { return String.format("Job{jobId=%s, jobStatus=%s, jobTitle=%s, jobLocation=%s, " + "jobDescription=%s, jobPay=%s, requirements=%s, postExpiryTimestamp=%d, jobDuration=%s}", jobId, jobStatus, jobTitle, jobLocation, jobDescription, jobPay, requirements, postExpiryTimestamp, jobDuration); } }
package ru.dionisius; import java.util.LinkedList; import java.util.List; public class SimpleBinaryTree<E extends Comparable> implements ISimpleTree<E>, ISimpleTreeSearch<E> { private Node<E> root; private List<E> childrens = new LinkedList<E>(); public SimpleBinaryTree() {} @Override public void addChild(E value) { this. root = this.addValue(this.root, value, null); } @Override public List<E> getChildren() { this.childrens.clear(); this.getChilds(this.root); return this.childrens; } private void getChilds(Node<E> root) { if (root != null) { if (root.getValue() != null) { this.childrens.add(root.getValue()); } else { if (root.getLeft() != null) { this.getChilds(root.getLeft()); } if (root.getRight() != null) { this.getChilds(root.getRight()); } } } } private Node<E> addValue(Node current, E value, Node parent) { if (current == null) { current = new Node(value, null, null, parent); } else { int compareResult = current.getValue().compareTo(value); if (compareResult < 0) { this.addValue(current.getLeft(), value, current); } else { this.addValue(current.getRight(), value, current); } } return current; } @Override public boolean consists(E value) { return this.consists(this.root, value); } private boolean consists(Node<E> root, E value) { if(root == null) { return false; } if (root.getValue().compareTo(value) == 0) { return true; } this.consists(root.getLeft(), value); this.consists(root.getRight(), value); return false; } private class Node<E extends Comparable> { private E value; private Node parent; private Node left; private Node right; public Node(E value, Node<E> left, Node<E> right, Node<E> parent){ this.value = value; this.left = left; this.right = right; this.parent = parent; } public E getValue() { return value; } public void setValue(E value) { this.value = value; } public Node getParent() { return parent; } public void setParent(Node parant) { this.parent = parant; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } } }
package org.pentaho.cdf; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.URLDecoder; import java.security.InvalidParameterException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.DefaultValue; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.cdf.context.ContextEngine; import org.pentaho.cdf.environment.CdfEngine; import org.pentaho.cdf.render.CdfHtmlRenderer; import org.pentaho.cdf.render.XcdfRenderer; import org.pentaho.cdf.util.Parameter; import org.pentaho.platform.api.engine.IParameterProvider; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.engine.core.system.PentahoSystem; import pt.webdetails.cpf.SimpleContentGenerator; import pt.webdetails.cpf.Util; import pt.webdetails.cpf.audit.CpfAuditHelper; import pt.webdetails.cpf.utils.CharsetHelper; import pt.webdetails.cpf.utils.MimeTypes; public class CdfContentGenerator extends SimpleContentGenerator { private static final long serialVersionUID = 319509966121604058L; private static final Log logger = LogFactory.getLog( CdfContentGenerator.class ); private static final String PLUGIN_ID = CdfEngine.getEnvironment().getPluginId(); public String RELATIVE_URL; private boolean cdfResource; // legacy resource feching support @Override public void createContent() throws Exception { String filePath = ""; String template = ""; logger.info( "[Timing] CDF content generator took over: " + ( new SimpleDateFormat( "HH:mm:ss.SSS" ) ).format( new Date() ) ); try { if ( getPathParameters() != null ) { // legacy resource feching support if( isCdfResource() ){ new CdfApi().getResource( getPathParameterAsString( "cmd", null ), null, getResponse() ); return; } filePath = getPathParameterAsString( Parameter.PATH, null ); template = getRequestParameterAsString( Parameter.TEMPLATE, null ); Object parameter = getRequest(); if ( parameter != null && ( (HttpServletRequest) parameter ).getContextPath() != null ) { RELATIVE_URL = ( (HttpServletRequest) parameter ).getContextPath(); } } else { RELATIVE_URL = CdfEngine.getEnvironment().getApplicationBaseUrl(); /* * If we detect an empty string, things will break. If we detect an absolute url, things will *probably* break. * In either of these cases, we'll resort to Catalina's context, and its getContextPath() method for better * results. */ if ( "".equals( RELATIVE_URL ) || RELATIVE_URL.matches( "^http: Object context = PentahoSystem.getApplicationContext().getContext(); Method getContextPath = context.getClass().getMethod( "getContextPath", null ); if ( getContextPath != null ) { RELATIVE_URL = getContextPath.invoke( context, null ).toString(); } } } if ( RELATIVE_URL.endsWith( "/" ) ) { RELATIVE_URL = RELATIVE_URL.substring( 0, RELATIVE_URL.length() - 1 ); } OutputStream out = getResponseOutputStream( MimeTypes.HTML ); // If callbacks is properly setup, we assume we're being called from another plugin if ( this.callbacks != null && callbacks.size() > 0 && HashMap.class.isInstance( callbacks.get( 0 ) ) ) { HashMap<String, Object> iface = (HashMap<String, Object>) callbacks.get( 0 ); out = (OutputStream) iface.get( "output" ); filePath = "/" + (String) iface.get( "method" ); this.userSession = this.userSession != null ? this.userSession : (IPentahoSession) iface.get( "usersession" ); } // make sure we have a workable state if ( outputHandler == null ) { error( Messages.getErrorString( "CdfContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER" ) ); //$NON-NLS-1$ throw new InvalidParameterException( Messages.getString( "CdfContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER" ) ); //$NON-NLS-1$ } else if ( out == null ) { error( Messages.getErrorString( "CdfContentGenerator.ERROR_0003_NO_OUTPUT_STREAM" ) ); //$NON-NLS-1$ throw new InvalidParameterException( Messages.getString( "CdfContentGenerator.ERROR_0003_NO_OUTPUT_STREAM" ) ); //$NON-NLS-1$ } if ( filePath.isEmpty() ) { logger.error( "Calling cdf with an empty method" ); } if ( getRequestParameters() != null ) { renderXcdfDashboard( out, getRequestParameters(), FilenameUtils.separatorsToUnix( filePath ), template ); } } catch ( Exception e ) { logger.error( "Error creating cdf content: ", e ); } } public void renderXcdfDashboard( final OutputStream out, final IParameterProvider requestParams, String xcdfFilePath, String defaultTemplate ) throws Exception { long start = System.currentTimeMillis(); UUID uuid = CpfAuditHelper.startAudit( PLUGIN_ID, xcdfFilePath, getObjectName(), this.userSession, this, requestParams ); try { XcdfRenderer renderer = new XcdfRenderer(); boolean success = renderer.determineDashboardTemplating( xcdfFilePath, defaultTemplate ); if ( success ) { String templatePath = Util.joinPath( FilenameUtils.getPath( xcdfFilePath ), renderer.getTemplate() ); if ( !StringUtils.isEmpty( defaultTemplate ) ) { // If style defined in URL parameter 'template' renderHtmlDashboard( out, xcdfFilePath, templatePath, defaultTemplate, renderer.getMessagesBaseFilename() ); } else { // use style provided via .xcdf or default renderHtmlDashboard( out, xcdfFilePath, templatePath, renderer.getStyle(), renderer.getMessagesBaseFilename() ); } setResponseHeaders( MimeTypes.HTML, 0, null ); } else { out.write( "Unable to render dashboard".getBytes( CharsetHelper.getEncoding() ) ); //$NON-NLS-1$ //$NON-NLS-2$ } long end = System.currentTimeMillis(); CpfAuditHelper.endAudit( PLUGIN_ID, xcdfFilePath, getObjectName(), this.userSession, this, start, uuid, end ); } catch ( Exception e ) { e.printStackTrace(); long end = System.currentTimeMillis(); CpfAuditHelper.endAudit( PLUGIN_ID, xcdfFilePath, getObjectName(), this.userSession, this, start, uuid, end ); throw e; } } public void renderHtmlDashboard( final OutputStream out, final String xcdfFilePath, final String templatePath, String defaultTemplate, String dashboardsMessagesBaseFilename ) throws Exception { HttpServletRequest request = getRequest(); CdfHtmlRenderer renderer = new CdfHtmlRenderer(); HashMap<String, String> paramMap = Parameter.asHashMap( request ); if ( paramMap.get( Parameter.FILE ) == null || paramMap.get( Parameter.FILE ).isEmpty() ) { paramMap.put( Parameter.FILE, xcdfFilePath ); } renderer.execute( out, templatePath, defaultTemplate, dashboardsMessagesBaseFilename, paramMap, userSession.getName() ); } public String getPluginName() { return PLUGIN_ID; } // InterPluginBroker calls this method within bean id 'xcdf' public String getContext( @QueryParam( Parameter.PATH ) @DefaultValue( StringUtils.EMPTY ) String path, @QueryParam( Parameter.ACTION ) @DefaultValue( StringUtils.EMPTY ) String action, @DefaultValue( StringUtils.EMPTY ) @QueryParam( Parameter.VIEW_ID ) String viewId, @Context HttpServletRequest servletRequest ) { return ContextEngine.getInstance().getContext( path, viewId, action, Parameter.asHashMap( servletRequest ) ); } // InterPluginBroker calls this method within bean id 'xcdf' public String getHeaders( @QueryParam( Parameter.DASHBOARD_CONTENT ) String dashboardContent, @QueryParam( Parameter.DASHBOARD_TYPE ) String dashboardType, @QueryParam( Parameter.ROOT ) String root, @QueryParam( Parameter.SCHEME ) String scheme, @QueryParam( Parameter.DEBUG ) @DefaultValue( "false" ) String debug, @Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse ) throws Exception { try { CdfHtmlRenderer.getHeaders( dashboardContent, dashboardType, root, scheme, Boolean.parseBoolean( debug ), servletResponse.getOutputStream() ); } catch ( IOException ex ) { logger.error( "getHeaders: " + ex.getMessage(), ex ); throw ex; } return null; } // legacy resource feching support public boolean isCdfResource() { return cdfResource; } // legacy resource feching support public void setCdfResource( boolean cdfResource ) { this.cdfResource = cdfResource; } }
package raptor.connector.fics.game; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import raptor.util.RaptorStringTokenizer; /** * This parser is a bit unusual in that it maintains state as messages are * processed. * * You can invoke getTakeBackMessage(gameId) to receive the last take back offer * requested and whether or not it was accepted. * * It is important to clearTakebackMessages after there is no longer a need to * keep this state. */ public class TakebackParser { public static class TakebackMessage { public int halfMovesRequested = -1; public boolean wasAccepted; public String gameId = ""; } protected Map<String, TakebackMessage> gameToTakebackMessages = new HashMap<String, TakebackMessage>(); public static final String IDENTIFIER = "Game"; public static final String REQUEST_TAKE_BACK = "take back"; public static final String ACCEPTD_TAKE_BACK = "accepts the takeback request"; private static final Log LOG = LogFactory.getLog(TakebackParser.class); /** * Returns the take back message for the specified game id. Returns null if * there are none. */ public TakebackMessage getTakebackMessage(String gameId) { return gameToTakebackMessages.get(gameId); } /** * Clears the take back message for the specified gameId. */ public void clearTakebackMessages(String gameId) { gameToTakebackMessages.remove(gameId); } /** * Returns true if line is a take back accepted message. */ public boolean parse(String line) { if (line.startsWith(IDENTIFIER) && line.contains(REQUEST_TAKE_BACK)) { if (LOG.isDebugEnabled()) { LOG.debug("Processing takeback offer."); } // Game 117: raptorb requests to take back 1 half move(s). TakebackMessage message = new TakebackMessage(); RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " ", true); tok.nextToken(); message.gameId = tok.nextToken(); message.gameId = message.gameId.substring(0, message.gameId .length() - 1); // parse past HANDLE requests to take back tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); message.halfMovesRequested = Integer.parseInt(tok.nextToken()); gameToTakebackMessages.put(message.gameId, message); return false; } else if (line.startsWith(IDENTIFIER) && line.contains(ACCEPTD_TAKE_BACK)) { if (LOG.isDebugEnabled()) { LOG.debug("Processing accepted takeback."); } // Game 117: raptora accepts the takeback request. RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " ", true); tok.nextToken(); String gameId = tok.nextToken(); gameId = gameId.substring(0, gameId.length() - 1); TakebackMessage message = getTakebackMessage(gameId); if (message != null) { message.wasAccepted = true; } else { LOG .debug("Received a takback accepted for a takeback message that was never received."); // Leave halfMoveRequested at -1. This way code which uses the // parser can determine this state and react appropriately. message = new TakebackMessage(); message.wasAccepted = true; message.gameId = gameId; gameToTakebackMessages.put(message.gameId, message); } return true; } return false; } }
package ch.elexis.data; import java.util.List; import ch.rgw.tools.Money; import ch.rgw.tools.TimeTool; public class Eigenleistung extends VerrechenbarAdapter { public static final String CODESYSTEM_NAME = "Eigenleistung"; public static final String TIME = "Zeit"; public static final String VK_PREIS = "VK_Preis"; public static final String EK_PREIS = "EK_Preis"; public static final String BEZEICHNUNG = "Bezeichnung"; public static final String CODE = "Code"; public static final String EIGENLEISTUNGEN = "EIGENLEISTUNGEN"; public static final String XIDDOMAIN = "www.xid.ch/id/customservices"; static { addMapping(EIGENLEISTUNGEN, CODE, BEZEICHNUNG, EK_PREIS, VK_PREIS, TIME); Xid.localRegisterXIDDomainIfNotExists(XIDDOMAIN, CODESYSTEM_NAME, Xid.ASSIGNMENT_LOCAL | Xid.QUALITY_GUID); } public String getXidDomain(){ return XIDDOMAIN; } @Override protected String getTableName(){ return EIGENLEISTUNGEN; } @Override public String getCode(){ return get(CODE); } @Override public String getText(){ return get(BEZEICHNUNG); } public String[] getDisplayedFields(){ return new String[] { CODE, BEZEICHNUNG }; } @Override public String getCodeSystemName(){ return CODESYSTEM_NAME; } @Override public Money getKosten(final TimeTool dat){ return new Money(checkZero(get(EK_PREIS))); } public Money getPreis(final TimeTool dat, final Fall fall){ return new Money(checkZero(get(VK_PREIS))); } public Eigenleistung(final String code, final String name, final String ek, final String vk){ create(null); set(new String[] { CODE, BEZEICHNUNG, EK_PREIS, VK_PREIS }, code, name, ek, vk); } protected Eigenleistung(){} protected Eigenleistung(final String id){ super(id); } public static Eigenleistung load(final String id){ return new Eigenleistung(id); } @Override public boolean isDragOK(){ return true; } @Override public String getCodeSystemCode(){ return "999"; } public int getTP(final TimeTool date, final Fall fall){ return getPreis(date, fall).getCents(); } public double getFactor(final TimeTool date, final Fall fall){ return 1.0; } @Override public List<Object> getActions(Object kontext){ // TODO Auto-generated method stub return null; } }
package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.TabsUtil; import com.joelapenna.foursquared.util.UserUtils; import android.app.TabActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * Displays information on a user. If the user is the logged-in user, we can * show our checkin history. If viewing a stranger, we can show info and * friends. Should look like this: Self History | Friends Stranger Info | * Friends * * @date March 8, 2010. * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsActivity extends TabActivity { private static final String TAG = "UserDetailsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_PARCEL = "com.joelapenna.foursquared.UserParcel"; public static final String EXTRA_USER_ID = "com.joelapenna.foursquared.UserId"; public static final String EXTRA_SHOW_ADD_FRIEND_OPTIONS = Foursquared.PACKAGE_NAME + ".UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS"; private static final int MENU_FRIEND_REQUESTS = 0; private static final int MENU_SHOUT = 1; private ImageView mImageViewPhoto; private TextView mTextViewName; private LinearLayout mLayoutNumMayorships; private LinearLayout mLayoutNumBadges; private TextView mTextViewNumMayorships; private TextView mTextViewNumBadges; private TabHost mTabHost; private LinearLayout mLayoutProgressBar; private StateHolder mStateHolder; private boolean mIsUsersPhotoSet; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_details_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mIsUsersPhotoSet = false; Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTaskUserDetails(this); } else { mStateHolder = new StateHolder(); String userId = null; if (getIntent().getExtras() != null) { if (getIntent().getExtras().containsKey(EXTRA_USER_PARCEL)) { User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL); userId = user.getId(); mStateHolder.setUser(user); } else if (getIntent().getExtras().containsKey(EXTRA_USER_ID)) { userId = getIntent().getExtras().getString(EXTRA_USER_ID); } else { Log.e(TAG, "UserDetailsActivity requires a userid in its intent extras."); finish(); return; } mStateHolder.setShowAddFriendOptions(getIntent().getBooleanExtra( EXTRA_SHOW_ADD_FRIEND_OPTIONS, false)); } else { Log.e(TAG, "UserDetailsActivity requires a userid in its intent extras."); finish(); return; } mStateHolder.startTaskUserDetails(this, userId); } mRrm = ((Foursquared) getApplication()).getRemoteResourceManager(); mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); ensureUi(); populateUi(); if (mStateHolder.getIsRunningUserDetailsTask() == false) { populateUiAfterFullUserObjectFetched(); } } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); unregisterReceiver(mLoggedOutReceiver); RemoteResourceManager rrm = ((Foursquared) getApplication()).getRemoteResourceManager(); rrm.deleteObserver(mResourcesObserver); } } private void ensureUi() { mImageViewPhoto = (ImageView) findViewById(R.id.userDetailsActivityPhoto); mImageViewPhoto.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mStateHolder.getUser() != null) { // If "_thumbs" exists, remove it to get the url of the // full-size image. String photoUrl = mStateHolder.getUser().getPhoto().replace("_thumbs", ""); Intent intent = new Intent(); intent.setClass(UserDetailsActivity.this, FetchImageForViewIntent.class); intent.putExtra(FetchImageForViewIntent.IMAGE_URL, photoUrl); intent.putExtra(FetchImageForViewIntent.PROGRESS_BAR_TITLE, getResources() .getString(R.string.user_activity_fetch_full_image_title)); intent.putExtra(FetchImageForViewIntent.PROGRESS_BAR_MESSAGE, getResources() .getString(R.string.user_activity_fetch_full_image_message)); startActivity(intent); } } }); mTextViewName = (TextView) findViewById(R.id.userDetailsActivityName); mTextViewNumMayorships = (TextView) findViewById(R.id.userDetailsActivityNumMayorships); mTextViewNumBadges = (TextView) findViewById(R.id.userDetailsActivityNumBadges); // When the user clicks the mayorships section, then launch the mayorships activity. mLayoutNumMayorships = (LinearLayout) findViewById(R.id.userDetailsActivityNumMayorshipsLayout); mLayoutNumMayorships.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startMayorshipsActivity(); } }); mLayoutNumMayorships.setEnabled(false); // When the user clicks the badges section, then launch the badges // activity. mLayoutNumBadges = (LinearLayout) findViewById(R.id.userDetailsActivityNumBadgesLayout); mLayoutNumBadges.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startBadgesActivity(); } }); mLayoutNumBadges.setEnabled(false); // At startup, we need to have at least one tab. Once we load the full // user object, // we can clear all tabs, and add our real tabs once we know what they // are. mTabHost = getTabHost(); mTabHost.addTab(mTabHost.newTabSpec("dummy").setIndicator("").setContent( R.id.userDetailsActivityTextViewTabDummy)); mTabHost.getTabWidget().setVisibility(View.GONE); mLayoutProgressBar = (LinearLayout) findViewById(R.id.userDetailsActivityLayoutProgressBar); } private void populateUi() { User user = mStateHolder.getUser(); // User photo. if (user != null && mIsUsersPhotoSet == false) { if (Foursquare.MALE.equals(user.getGender())) { mImageViewPhoto.setImageResource(R.drawable.blank_boy); } else { mImageViewPhoto.setImageResource(R.drawable.blank_girl); } if (user != null) { Uri uriPhoto = Uri.parse(user.getPhoto()); if (mRrm.exists(uriPhoto)) { try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(user .getPhoto()))); mImageViewPhoto.setImageBitmap(bitmap); mIsUsersPhotoSet = true; } catch (IOException e) { } } else { mRrm.request(uriPhoto); } } } // User name. if (user != null) { if (UserUtils.isFriend(user) || user.getId().equals(((Foursquared) getApplication()).getUserId())) { mTextViewName.setText(StringFormatters.getUserFullName(user)); } else { mTextViewName.setText(StringFormatters.getUserAbbreviatedName(user)); } } else { mTextViewName.setText(""); } // Number of mayorships. if (user != null) { if (mStateHolder.getFetchedUserDetails()) { mTextViewNumMayorships.setText(String.valueOf(user.getMayorships().size())); } else { mTextViewNumMayorships.setText("-"); } } else { mTextViewNumMayorships.setText("-"); } // Number of badges. if (user != null) { if (mStateHolder.getFetchedUserDetails()) { mTextViewNumBadges.setText(String.valueOf(user.getBadges().size())); } else { mTextViewNumBadges.setText("-"); } } else { mTextViewNumBadges.setText("-"); } } private void populateUiAfterFullUserObjectFetched() { populateUi(); mLayoutProgressBar.setVisibility(View.GONE); mTabHost.clearAllTabs(); mTabHost.getTabWidget().setVisibility(View.VISIBLE); // Add tab1. TabHost.TabSpec specTab1 = mTabHost.newTabSpec("tab1"); if (mStateHolder.getUser().getId().equals(((Foursquared) getApplication()).getUserId())) { // Ourselves, History tab. View tabView = prepareTabView(getResources().getString( R.string.user_details_activity_tab_title_history)); TabsUtil.setTabIndicator(specTab1, getResources().getString( R.string.user_details_activity_tab_title_history), null, tabView); Intent intent = new Intent(this, UserHistoryActivity.class); specTab1.setContent(intent); } else { // Friend or stranger, Info tab. View tabView = prepareTabView(getResources().getString( R.string.user_details_activity_tab_title_info)); TabsUtil.setTabIndicator(specTab1, getResources().getString( R.string.user_details_activity_tab_title_info), null, tabView); Intent intent = new Intent(this, UserActionsActivity.class); intent.putExtra(UserActionsActivity.EXTRA_USER_PARCEL, mStateHolder.getUser()); intent.putExtra(UserActionsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, mStateHolder .getShowAddFriendOptions()); specTab1.setContent(intent); } mTabHost.addTab(specTab1); // Add tab2, always Friends tab. TabHost.TabSpec specTab2 = mTabHost.newTabSpec("tab2"); View tabView = prepareTabView(getResources().getString( R.string.user_details_activity_tab_title_friends)); TabsUtil.setTabIndicator(specTab2, getResources().getString( R.string.user_details_activity_tab_title_friends), null, tabView); Intent intent = new Intent(this, UserFriendsActivity.class); intent.putExtra(UserFriendsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId()); intent.putExtra(UserFriendsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, mStateHolder .getShowAddFriendOptions()); specTab2.setContent(intent); mTabHost.addTab(specTab2); // User can also now click on the badges / mayorships layouts. mLayoutNumBadges.setEnabled(true); mLayoutNumMayorships.setEnabled(true); } private View prepareTabView(String text) { View view = LayoutInflater.from(this).inflate(R.layout.user_details_activity_tabs, null); TextView tv = (TextView) view.findViewById(R.id.userDetailsActivityTabTextView); tv.setText(text); return view; } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTaskUserDetails(null); return mStateHolder; } private void startBadgesActivity() { if (mStateHolder.getUser() != null) { Intent intent = new Intent(UserDetailsActivity.this, BadgesActivity.class); intent.putParcelableArrayListExtra(BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL, mStateHolder.getUser().getBadges()); startActivity(intent); } } private void startMayorshipsActivity() { if (mStateHolder.getUser() != null) { Intent intent = new Intent(UserDetailsActivity.this, UserMayorshipsActivity.class); intent.putExtra(UserMayorshipsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId()); startActivity(intent); } } private void onUserDetailsTaskComplete(User user, Exception ex) { setProgressBarIndeterminateVisibility(false); mStateHolder.setFetchedUserDetails(true); mStateHolder.setIsRunningUserDetailsTask(false); if (user != null) { mStateHolder.setUser(user); populateUiAfterFullUserObjectFetched(); } else { NotificationsUtil.ToastReasonForFailure(this, ex); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // We have a different set of menu options for the logged-in user vs // viewing a friend and potentially a stranger even. User user = mStateHolder.getUser(); if (user != null && user.getId().equals(((Foursquared) getApplication()).getUserId())) { menu.add(Menu.NONE, MENU_FRIEND_REQUESTS, Menu.NONE, R.string.preferences_friend_requests_title).setIcon(R.drawable.ic_menu_friends); menu.add(Menu.NONE, MENU_SHOUT, Menu.NONE, R.string.shout_action_label).setIcon(R.drawable.ic_menu_shout); MenuUtils.addPreferencesToMenu(this, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_FRIEND_REQUESTS: startActivity(new Intent(this, FriendRequestsActivity.class)); return true; case MENU_SHOUT: Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT, true); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * Even if the caller supplies us with a User object parcelable, it won't * have all the badge etc extra info in it. As soon as the activity starts, * we launch this task to fetch a full user object, and merge it with * whatever is already supplied in mUser. */ private static class UserDetailsTask extends AsyncTask<String, Void, User> { private UserDetailsActivity mActivity; private Exception mReason; public UserDetailsTask(UserDetailsActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setProgressBarIndeterminateVisibility(true); } @Override protected User doInBackground(String... params) { try { return ((Foursquared) mActivity.getApplication()).getFoursquare().user( params[0], true, true, LocationUtils.createFoursquareLocation(((Foursquared) mActivity .getApplication()).getLastKnownLocation())); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onUserDetailsTaskComplete(user, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onUserDetailsTaskComplete(null, mReason); } } public void setActivity(UserDetailsActivity activity) { mActivity = activity; } } private static class StateHolder { /** The user object we are rendering. */ private User mUser; /** Show options to add friends for strangers. */ private boolean mShowAddFriendOptions; private UserDetailsTask mTaskUserDetails; private boolean mIsRunningUserDetailsTask; private boolean mFetchedUserDetails; public StateHolder() { mShowAddFriendOptions = false; mIsRunningUserDetailsTask = false; mFetchedUserDetails = false; } public void setFetchedUserDetails(boolean fetched) { mFetchedUserDetails = fetched; } public boolean getFetchedUserDetails() { return mFetchedUserDetails; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public void setShowAddFriendOptions(boolean showAddFriendOptions) { mShowAddFriendOptions = showAddFriendOptions; } public boolean getShowAddFriendOptions() { return mShowAddFriendOptions; } public void startTaskUserDetails(UserDetailsActivity activity, String userId) { mIsRunningUserDetailsTask = true; mTaskUserDetails = new UserDetailsTask(activity); mTaskUserDetails.execute(userId); } public void setActivityForTaskUserDetails(UserDetailsActivity activity) { if (mTaskUserDetails != null) { mTaskUserDetails.setActivity(activity); } } public void setIsRunningUserDetailsTask(boolean isRunning) { mIsRunningUserDetailsTask = isRunning; } public boolean getIsRunningUserDetailsTask() { return mIsRunningUserDetailsTask; } public void cancelTasks() { if (mTaskUserDetails != null) { mTaskUserDetails.setActivity(null); mTaskUserDetails.cancel(true); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mImageViewPhoto.getHandler().post(new Runnable() { @Override public void run() { Uri uriPhoto = Uri.parse(mStateHolder.getUser().getPhoto()); if (mRrm.exists(uriPhoto)) { try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(uriPhoto)); mImageViewPhoto.setImageBitmap(bitmap); mIsUsersPhotoSet = true; mImageViewPhoto.setImageBitmap(bitmap); } catch (IOException e) { } } } }); } } }
package com.airbnb.reair.incremental; /** * Class to encapsulate how the run of a replication task / job went. */ public class RunInfo { public enum RunStatus { // See similar definitions for // {@link com.airbnb.reair.incremental.ReplicationStatus} SUCCESSFUL, NOT_COMPLETABLE, FAILED, } private RunStatus runStatus; private long bytesCopied; public RunStatus getRunStatus() { return runStatus; } public void setRunStatus(RunStatus runStatus) { this.runStatus = runStatus; } public long getBytesCopied() { return bytesCopied; } public void setBytesCopied(long bytesCopied) { this.bytesCopied = bytesCopied; } public RunInfo(RunStatus runStatus, long bytesCopied) { this.runStatus = runStatus; this.bytesCopied = bytesCopied; } }
package ru.agolovin; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * File sort class. * * @author agolovin (agolovin@list.ru) * @version $Id$ * @since 0.1 */ public class FileSort { /** * First temporary file. */ private File tempOne; /** * Second temporary file. */ private File tempTwo; /** * Distance file. */ private File dist; /** * line separator. */ private String lineSeparator = System.getProperty("lineSeparator"); /** * Constructor. */ FileSort() { this.tempOne = new File("tempOne.tmp"); this.tempTwo = new File("tempTwo.tmp"); this.dist = new File("distance.txt"); } /** * external sort file. * * @param source File * @param distance File * @throws IOException exception */ public void sort(File source, File distance) { if (checkExistFile(source)) { this.dist = distance; } try { if (splitFile(source)) { mergeTempFiles(); while (splitFile(distance)) { mergeTempFiles(); } } } catch (IOException ioe) { ioe.printStackTrace(); } } /** * check file exist. * * @param file File * @return true if exist */ private boolean checkExistFile(File file) { boolean result = true; if (!file.exists() && !file.isFile()) { System.out.println("source file invalid"); result = false; } return result; } /** * check if file already sorted. * * @param file File * @return boolean result * @throws IOException exception */ private boolean splitFile(File file) throws IOException { boolean result = false; boolean flag = true; int currentLineLength = 0; String line; int lastLineLength = 0; try { RandomAccessFile rafFile = new RandomAccessFile(file, "r"); RandomAccessFile rafTempOne = new RandomAccessFile(tempOne, "rw"); RandomAccessFile rafTempTwo = new RandomAccessFile(tempTwo, "rw"); rafTempOne.seek(0); rafTempTwo.seek(0); rafFile.seek(0); while (rafFile.getFilePointer() != rafFile.length()) { line = rafFile.readLine(); currentLineLength = line.length(); if (currentLineLength >= lastLineLength && flag) { write(rafTempOne, line); } else if (currentLineLength < lastLineLength && flag) { write(rafTempTwo, line); flag = false; } else if (currentLineLength >= lastLineLength && !flag) { write(rafTempTwo, line); } else if (currentLineLength < lastLineLength && !flag) { write(rafTempOne, line); flag = true; } lastLineLength = currentLineLength; } rafTempTwo.seek(0); if (rafTempTwo.length() == 0) { result = true; } rafFile.close(); rafTempOne.close(); rafTempTwo.close(); } catch (IOException ioe) { ioe.printStackTrace(); } this.tempTwo.delete(); this.tempOne.delete(); return result; } /** * merge temp files to one distance. */ private void mergeTempFiles() { try { RandomAccessFile rafDistance = new RandomAccessFile(dist, "rw"); RandomAccessFile rafTempOne = new RandomAccessFile(tempOne, "r"); RandomAccessFile rafTempTwo = new RandomAccessFile(tempTwo, "r"); rafDistance.seek(0); rafTempOne.seek(0); rafTempTwo.seek(0); boolean skipTempOne = false; boolean skipTempTwo = false; String lineTempOne = ""; String lineTempTwo = ""; if (tempOne.length() != 0) { lineTempOne = rafTempOne.readLine(); } else { skipTempOne = true; } if (tempTwo.length() != 0) { lineTempTwo = rafTempTwo.readLine(); } else { skipTempTwo = true; } do { if (!skipTempTwo && (skipTempOne || (lineTempTwo.length() >= lineTempOne.length()))) { write(rafDistance, lineTempOne); if (rafTempOne.getFilePointer() != rafTempOne.length()) { lineTempOne = rafTempOne.readLine(); } else { skipTempOne = true; } } else if (!skipTempOne && (skipTempTwo || (lineTempOne.length() > lineTempTwo.length()))) { write(rafDistance, lineTempTwo); if (rafTempTwo.getFilePointer() != rafTempTwo.length()) { lineTempTwo = rafTempTwo.readLine(); } else { skipTempTwo = true; } } } while (!skipTempOne || !skipTempTwo); rafDistance.close(); rafTempOne.close(); rafTempTwo.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * write string in the file. * * @param randomAccessFile RandomAccessFile * @param string String */ private void write(RandomAccessFile randomAccessFile, String string) { try { randomAccessFile.seek(randomAccessFile.length()); randomAccessFile.writeBytes(String.format("%s%s", string, lineSeparator)); } catch (IOException ioe) { ioe.printStackTrace(); } } }
package ru.job4j.io.log; import org.apache.log4j.BasicConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UsageLog4j { private static final Logger LOG = LoggerFactory.getLogger(UsageLog4j.class.getName()); public static void main(String[] args) { BasicConfigurator.configure(); String name = "Tom"; int age = 25; long height = 180; short weight = 74; byte shoes = 41; float clothes = 40; double salary = 28000; boolean married = true; char driver = 'B'; LOG.debug("User info name : {}, age : {}," + " height : {}, weight : {}, shoes : {}," + " clothes : {}, salary : {}, married : {}, driver : {}", name, age, height, weight, shoes, clothes, salary, married, driver); } }
package me.TehGoldyLockz.OlympicHeroes.listeners; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Arrow; import org.bukkit.entity.Arrow.PickupStatus; import org.bukkit.entity.Player; import org.bukkit.entity.Villager; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import me.TehGoldyLockz.OlympicHeroes.Cooldowns; import me.TehGoldyLockz.OlympicHeroes.OlympicHeroes; import me.TehGoldyLockz.OlympicHeroes.Variables; import me.TehGoldyLockz.OlympicHeroes.item.OHItems; import me.TehGoldyLockz.OlympicHeroes.player.OHPlayer; public class PlayerListener implements Listener{ OlympicHeroes plugin; public PlayerListener(OlympicHeroes plugin) { this.plugin = plugin; plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler public void onDamage(EntityDamageEvent e) { if(e.getEntity() instanceof Player) { Player player = (Player) e.getEntity(); OHPlayer ohPlayer = new OHPlayer(player); if(e.getCause() == DamageCause.FALL) { if(ohPlayer.getXP("Zeus") > 0) { e.setDamage(e.getFinalDamage() / 1.5); player.sendMessage("Your fall damage has been reduced thanks to Zeus"); } } if(e.getCause() == DamageCause.ENTITY_ATTACK) { if(ohPlayer.getLevel("Aphrodite") >= 5) { if(!Cooldowns.resCooldown.contains(player.getPlayer())) { Cooldowns.resCooldown.add(player.getPlayer()); player.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 600, 1)); OlympicHeroes.removeCooldown(plugin, Cooldowns.resCooldown, player.getPlayer(), Variables.RES_COOLDOWN); } } } } } @EventHandler public void onBowShoot(EntityShootBowEvent e) { if(e.getEntity() instanceof Player) { Player player = (Player) e.getEntity(); OHPlayer ohPlayer = new OHPlayer(player); if(ohPlayer.getLevel("Artemis") >= 3) { if(e.getBow().containsEnchantment(Enchantment.ARROW_INFINITE) == false && player.getGameMode() != GameMode.CREATIVE) { ((Arrow) e.getProjectile()).setPickupStatus(PickupStatus.DISALLOWED); player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(Material.ARROW, 1)); } } } } @EventHandler public void onShootEntity(ProjectileHitEvent e) { if(e.getEntity().getShooter() instanceof Player) { Player player = (Player) e.getEntity().getShooter(); OHPlayer ohPlayer = new OHPlayer(player); if(ohPlayer.getLevel("Apollo") >= 2) { if(e.getHitEntity() != null) { e.getHitEntity().setGlowing(true); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if(e.getHitEntity().isDead() == false) { e.getHitEntity().setGlowing(false); } } }, 200L); } } if(ohPlayer.getLevel("Apollo") >= 3) { long time = player.getWorld().getTime(); if(time <= 13500 || time >= 23000) { e.getHitEntity().setFireTicks(300); } } } } @EventHandler public void onInteract(PlayerInteractEvent e) { //HANDLE ZEUS ABILITY if(e.getAction() == Action.RIGHT_CLICK_AIR && e.getHand() == EquipmentSlot.HAND) { ItemStack item = e.getItem(); if(item.getType() == Material.DIAMOND_SWORD || item.getType() == Material.GOLD_SWORD || item.getType() == Material.IRON_SWORD || item.getType() == Material.STONE_SWORD || item.getType() == Material.WOOD_SWORD) { OHPlayer ohPlayer = new OHPlayer(e.getPlayer()); if(ohPlayer.getLevel("Zeus") >= 5) { if(!Cooldowns.lightningCooldown.contains(e.getPlayer())) { Block block = e.getPlayer().getTargetBlock(null, 100); Location l = block.getLocation(); e.getPlayer().getWorld().strikeLightning(l); Cooldowns.lightningCooldown.add(e.getPlayer()); OlympicHeroes.removeCooldown(plugin, Cooldowns.lightningCooldown, e.getPlayer(), Variables.LIGHTNING_COOLDOWN); }else { e.getPlayer().sendMessage("That ability is on cooldown."); } } } } // HANDLE ARES ABILITY if( (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) && e.getHand() == EquipmentSlot.HAND) { ItemStack item = e.getItem(); if(item.getType() == Material.DIAMOND_AXE || item.getType() == Material.GOLD_AXE || item.getType() == Material.IRON_AXE || item.getType() == Material.STONE_AXE || item.getType() == Material.WOOD_AXE) { OHPlayer ohPlayer = new OHPlayer(e.getPlayer()); if(ohPlayer.getLevel("Ares") >= 5) { if(!Cooldowns.rageCooldown.contains(e.getPlayer())) { Cooldowns.rageCooldown.add(e.getPlayer()); e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 100, 3), true); e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, 100, 1)); OlympicHeroes.removeCooldown(plugin, Cooldowns.rageCooldown, e.getPlayer(), Variables.RAGE_COOLDOWN); }else { e.getPlayer().sendMessage("That ability is on cooldown."); } } } } } @EventHandler public void onInvClick(InventoryClickEvent e) { if(OHItems.isItemSimilarTo(e.getCurrentItem(), OHItems.AEGIS_SHIELD, false)) { e.setCancelled(true); } } @EventHandler public void PlayerInteractEntity(PlayerInteractEntityEvent e) { if(e.getRightClicked() instanceof Villager) { Villager villager = (Villager) e.getRightClicked(); if(villager.getCustomName() == ChatColor.AQUA + "Vault Manager") { e.getPlayer().sendMessage(ChatColor.AQUA + "That is a Vault Manager"); } } } @EventHandler public void onPlayerDeath(EntityDeathEvent e) { if(e.getEntity() instanceof Player) { for(int i = e.getDrops().size() - 1; i >= 0; i ItemStack item = e.getDrops().get(i); if(OHItems.isItemSimilarTo(item, OHItems.AEGIS_SHIELD, false)) { e.getDrops().remove(i); } } } } }
package me.stefvanschie.buildinggame.managers.plots; import me.stefvanschie.buildinggame.managers.arenas.ArenaManager; import me.stefvanschie.buildinggame.managers.files.SettingsManager; import me.stefvanschie.buildinggame.utils.Arena; import me.stefvanschie.buildinggame.utils.plot.Plot; public class PlotManager { private PlotManager() {} private static PlotManager instance = new PlotManager(); public static PlotManager getInstance() { return instance; } public void setup() { for (Arena arena : ArenaManager.getInstance().getArenas()) { for (String plot : SettingsManager.getInstance().getArenas().getConfigurationSection(arena.getName()).getKeys(false)) { try { Integer.parseInt(plot); } catch (NumberFormatException e) { continue; } Plot p = new Plot(Integer.parseInt(plot)); arena.addPlot(p); p.setArena(arena); } } } }
package org.jpos.qi; import com.vaadin.shared.ui.ContentMode; import com.vaadin.ui.*; import org.jpos.ee.DB; import org.jpos.ee.Revision; import org.jpos.ee.RevisionManager; import java.util.List; public class RevisionsPanel extends Panel { private String ref; public RevisionsPanel (String ref, DB db) { this.ref = ref; QI app = (QI) UI.getCurrent(); VerticalLayout main = new VerticalLayout(); main.setSpacing(true); main.setMargin(true); setContent(main); RevisionManager revmgr = new RevisionManager (db); List<Revision> revisions = revmgr.getRevisionsByRef(ref); if (revisions != null && revisions.size() > 0) { for (Revision r : revisions) addRevision (r); } else { Label noHistoryLabel = new Label(app.getMessage("errorMessage.noRevision")); main.addComponent(noHistoryLabel); } setCaption(((QI) UI.getCurrent()).getMessage("revision.history")); addStyleName(revisions.size() > 0 ? "revision-history" : "invisible"); } private void addRevision (Revision r) { String auth = r.getAuthor() != null ? r.getAuthor().getName() : "author-unknown"; Label author = new Label("<strong>" + auth + "</strong>", ContentMode.HTML); Label date = new Label(r.getDate().toString()); Label info = new Label(r.getInfo(), ContentMode.HTML); author.setWidth("60%"); HorizontalLayout hl = new HorizontalLayout(); hl.setHeight("30px"); hl.setWidth("100%"); hl.addComponent(author); hl.addComponent (date); Layout content = (Layout) getContent(); content.addComponent(hl); content.addComponent(info); } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } }
package wicket.examples.selecttag; import java.util.ArrayList; import java.util.Iterator; import wicket.PageParameters; import wicket.examples.util.NavigationPanel; import wicket.markup.html.HtmlPage; import wicket.markup.html.basic.Label; import wicket.markup.html.form.DropDownChoice; import wicket.markup.html.form.Form; import wicket.markup.html.form.IDetachableChoiceList; import wicket.model.IModel; /** * @author jcompagner * @version $Id$ */ public class Home extends HtmlPage { /** * Constructor * * @param parameters * Page parameters (ignored since this is the home page) */ public Home(final PageParameters parameters) { add(new NavigationPanel("mainNavigation", "Select tag example")); add(new SelectForm("selectform")); } class SelectForm extends Form { SelectModel model; Label label; public SelectForm(String name) { super(name,null); model = new SelectModel(); label = new Label("label",model,"name"); add(label); DropDownChoice choice = new DropDownChoice("users",model,new UserIdList()); add(choice); } /* * @see wicket.markup.html.form.Form#handleSubmit() */ public void handleSubmit() { getRequestCycle().setRedirect(true); getRequestCycle().setPage(Home.this); } } class SelectModel implements IModel { private Object selection; /* * @see wicket.model.IModel#getObject() */ public Object getObject() { return selection; } /* * @see wicket.model.IModel#setObject(java.lang.Object) */ public void setObject(Object object) { selection = object; } } class UserIdList extends ArrayList implements IDetachableChoiceList { /* * @see wicket.markup.html.form.IDetachableChoiceList#detach() */ public void detach() { this.clear(); } /* * @see wicket.markup.html.form.IDetachableChoiceList#attach() */ public void attach() { if(size() == 0) { add(new User(new Long(1),"Foo")); add(new User(new Long(2),"Bar")); add(new User(new Long(3),"FooBar")); } } /* * @see wicket.markup.html.form.IDetachableChoiceList#getDisplayValue(int) */ public String getDisplayValue(int row) { return ((User)get(row)).getName(); } /* * @see wicket.markup.html.form.IDetachableChoiceList#getIdValue(int) */ public String getId(int row) { return ((User)get(row)).getId().toString(); } /* * @see wicket.markup.html.form.IDetachableChoiceList#getObjectById(java.lang.String) */ public Object objectForId(String id) { Long longId = new Long(id); Iterator it = iterator(); while(it.hasNext()) { User user = (User)it.next(); if(user.getId().equals(longId)) { return user; } } return null; } } }
package com.inktomi.cirrus; import com.inktomi.cirrus.forecast.WeatherResponse; import com.inktomi.cirrus.forecast.Data; import com.inktomi.cirrus.forecast.Icon; import com.inktomi.cirrus.forecast.Parameters; import com.inktomi.cirrus.forecast.TemperatureValue; import com.inktomi.cirrus.forecast.TimeLayout; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WeatherUtils { private static final String TAG = WeatherUtils.class.getName(); private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss"); private static Map<String, TemperatureValue> HOURLY_TEMPERATURE = null; private static final Comparator<TimeLayout> TIME_LAYOUT_COMPARATOR = new Comparator<TimeLayout>(){ @Override public int compare(TimeLayout lhs, TimeLayout rhs) { return lhs.layoutKey.compareTo(rhs.layoutKey); } }; /** * This class caches a lot of the work it does forever. When you update your forecast, you * can use this method to clear the cached values. */ public static void notifyDatasetChanged(){ HOURLY_TEMPERATURE.clear(); } /** * Formats a date for use as a map key, or to compare to dates from the NDFD. * @param input the date to format * @return the formatted string. */ public static String formatDate( Date input ){ return DATE_FORMAT.format(input); } /** * Will return the current hourly temperature from a weather response. * * @param weather the response from getWeatherForecast that you want to get the current hourly temperature from. */ public static TemperatureValue getForecastMaximumTemperature(WeatherResponse weather, Date when){ Data responseData = null; if (null != weather.data && !weather.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < weather.data.size(); i++ ){ Data trialSet = weather.data.get(i); if( null != trialSet.type && trialSet.type.equals("forecast") ){ responseData = trialSet; } } } Parameters parameters = null; if (null != responseData && null != responseData.parameters && !responseData.parameters.isEmpty() ) { parameters = responseData.parameters.get(0); } Parameters.Temperature temp = null; if( null != parameters ){ if( null != parameters.temperature ){ for( int i = 0; i < parameters.temperature.size(); i++ ){ Parameters.Temperature trial = parameters.temperature.get(i); if( null == trial.type ){ continue; } if( trial.type.equals("maximum") ){ temp = trial; } } } } // What temperature index should we look for? String timeKey = temp.timeLayout; // Find the layout to use. int forecastIndex = -1; if( null != responseData.timeLayout && !responseData.timeLayout.isEmpty() ){ Collections.sort(responseData.timeLayout, TIME_LAYOUT_COMPARATOR); TimeLayout predicate = new TimeLayout(); predicate.layoutKey = timeKey; int layoutPosition = Collections.binarySearch(responseData.timeLayout, predicate, TIME_LAYOUT_COMPARATOR); if( layoutPosition > -1 ){ TimeLayout timeLayout = responseData.timeLayout.get(layoutPosition); forecastIndex = timeLayout.getIndexForTime(when); } } if( forecastIndex > -1 ){ return temp.value.get(forecastIndex); } return null; } public static TemperatureValue getCurrentTemperature(WeatherResponse weather){ Data responseData = null; if (null != weather.data && !weather.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < weather.data.size(); i++ ){ Data trialSet = weather.data.get(i); if( null != trialSet.type && trialSet.type.equals("current observations") ){ responseData = trialSet; } } } Parameters parameters = null; if (null != responseData && null != responseData.parameters && !responseData.parameters.isEmpty() ) { parameters = responseData.parameters.get(0); } Parameters.Temperature temp = null; if( null != parameters ){ if( null != parameters.temperature ){ for( int i = 0; i < parameters.temperature.size(); i++ ){ Parameters.Temperature trial = parameters.temperature.get(i); if( null == trial.type ){ continue; } if( trial.type.equals("apparent") ){ temp = trial; } } } } // No need for time layouts here! if( null != temp && null != temp.value && !temp.value.isEmpty()){ return temp.value.get(0); } return null; } public static TemperatureValue getForecastMinimumTemperature(WeatherResponse weather, Date when){ Data responseData = null; if (null != weather.data && !weather.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < weather.data.size(); i++ ){ Data trialSet = weather.data.get(i); if( null != trialSet.type && trialSet.type.equals("forecast") ){ responseData = trialSet; } } } Parameters parameters = null; if (null != responseData && null != responseData.parameters && !responseData.parameters.isEmpty() ) { parameters = responseData.parameters.get(0); } Parameters.Temperature temp = null; if( null != parameters ){ if( null != parameters.temperature ){ for( int i = 0; i < parameters.temperature.size(); i++ ){ Parameters.Temperature trial = parameters.temperature.get(i); if( null == trial.type ){ continue; } if( trial.type.equals("minimum") ){ temp = trial; } } } } // What temperature index should we look for? String timeKey = temp.timeLayout; // Find the layout to use. int forecastIndex = -1; if( null != responseData.timeLayout && !responseData.timeLayout.isEmpty() ){ Collections.sort(responseData.timeLayout, TIME_LAYOUT_COMPARATOR); TimeLayout predicate = new TimeLayout(); predicate.layoutKey = timeKey; int layoutPosition = Collections.binarySearch(responseData.timeLayout, predicate, TIME_LAYOUT_COMPARATOR); if( layoutPosition > -1 ){ TimeLayout timeLayout = responseData.timeLayout.get(layoutPosition); forecastIndex = timeLayout.getIndexForTime(when); } } if( forecastIndex > -1 ){ return temp.value.get(forecastIndex); } return null; } public static String getForecastWeatherConditions(WeatherResponse response, Date when){ Data responseData = null; if (null != response.data && !response.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < response.data.size(); i++ ){ Data trialSet = response.data.get(i); if( null != trialSet.type && trialSet.type.equals("forecast") ){ responseData = trialSet; } } } return getWeatherConditions(when, responseData); } public static String getCurrentWeatherConditions(WeatherResponse response){ Data responseData = null; if (null != response.data && !response.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < response.data.size(); i++ ){ Data trialSet = response.data.get(i); if( null != trialSet.type && trialSet.type.equals("current observations") ){ responseData = trialSet; } } } return getWeatherConditions(null, responseData); } private static String getWeatherConditions(Date when, Data responseData) { Parameters parameters = null; if (null != responseData && null != responseData.parameters && !responseData.parameters.isEmpty() ) { parameters = responseData.parameters.get(0); } Parameters.Weather weather = null; if( null != parameters ){ List<Parameters.Weather> weatherList = parameters.weather; if( null != weatherList && !weatherList.isEmpty() ){ weather = weatherList.get(0); } } if( null != weather ){ // What temperature index should we look for? String timeKey = weather.timeLayout; // Find the layout to use. int forecastIndex = -1; if( null != responseData.timeLayout && !responseData.timeLayout.isEmpty() ){ Collections.sort(responseData.timeLayout, TIME_LAYOUT_COMPARATOR); TimeLayout predicate = new TimeLayout(); predicate.layoutKey = timeKey; int layoutPosition = Collections.binarySearch(responseData.timeLayout, predicate, TIME_LAYOUT_COMPARATOR); if( layoutPosition > -1 ){ TimeLayout timeLayout = responseData.timeLayout.get(layoutPosition); if( null == when ){ forecastIndex = 0; } else { forecastIndex = timeLayout.getIndexForTime(when); } } } Parameters.Weather.WeatherConditions conditions = null; if( forecastIndex > -1 ){ // Get the weather conditions out. conditions = weather.weatherConditions.get(forecastIndex); } if( null != conditions ){ return conditions.weatherSummary; } } return null; } /** * Returns the Cirrus Icon representation of the icon included for the current conditions. * * Note that this call will often lead to a null response, because the conditions icon is only included * in the current observations about 80% the time. * * @param response the WeatherResponse to get the icon from. * @return an Icon or null if we didn't have one. */ public static Icon getCurrentWeatherIcon(WeatherResponse response) { Data responseData = null; if (null != response.data && !response.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < response.data.size(); i++ ){ Data trialSet = response.data.get(i); if( null != trialSet.type && trialSet.type.equals("current observations") ){ responseData = trialSet; } } } return getIcon(null, responseData); } public static Icon getForecastWeatherIcon(WeatherResponse response, Date when) { Data responseData = null; if (null != response.data && !response.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < response.data.size(); i++ ){ Data trialSet = response.data.get(i); if( null != trialSet.type && trialSet.type.equals("forecast") ){ responseData = trialSet; } } } return getIcon(when, responseData); } /** * Returns the first forecast icon from the weather response. * @param response the response to use. * @return an Icon */ public static Icon getUpcomingWeatherIcon(WeatherResponse response){ Data responseData = null; if (null != response.data && !response.data.isEmpty()) { // We need to pull the forecast data out. for( int i = 0; i < response.data.size(); i++ ){ Data trialSet = response.data.get(i); if( null != trialSet.type && trialSet.type.equals("forecast") ){ responseData = trialSet; } } } Parameters parameters = null; if (null != responseData && null != responseData.parameters && !responseData.parameters.isEmpty() ) { parameters = responseData.parameters.get(0); } Parameters.ConditionsIcon conditionsIcon = null; if( null != parameters ){ conditionsIcon = parameters.conditionsIcon; } if( null != conditionsIcon ){ // Find the layout to use. int forecastIndex = 0; String iconLink = null; if( !conditionsIcon.iconLink.isEmpty() ){ // Get the weather conditions out. iconLink = conditionsIcon.iconLink.get(forecastIndex); } // Now figure out which Icon matches up with our icon's link // Get the filename out of the icon link. if( null != iconLink ){ Pattern getConditionCode = Pattern.compile("^.*/(?:hi_)?(?:m_)?n?([a-z]*)\\d*.(?:jpg||png)$"); Matcher codeMatcher = getConditionCode.matcher(iconLink); if( codeMatcher.matches() ){ String code = codeMatcher.group(1); return Icon.getByIconName(code); } } } return null; } private static Icon getIcon(Date when, Data responseData) { Parameters parameters = null; if (null != responseData && null != responseData.parameters && !responseData.parameters.isEmpty() ) { parameters = responseData.parameters.get(0); } Parameters.ConditionsIcon conditionsIcon = null; if( null != parameters ){ conditionsIcon = parameters.conditionsIcon; } if( null != conditionsIcon ){ // What temperature index should we look for? String timeKey = conditionsIcon.timeLayout; // Find the layout to use. int forecastIndex = -1; if( null != responseData.timeLayout && !responseData.timeLayout.isEmpty() ){ Collections.sort(responseData.timeLayout, TIME_LAYOUT_COMPARATOR); TimeLayout predicate = new TimeLayout(); predicate.layoutKey = timeKey; int layoutPosition = Collections.binarySearch(responseData.timeLayout, predicate, TIME_LAYOUT_COMPARATOR); if( layoutPosition > -1 ){ TimeLayout timeLayout = responseData.timeLayout.get(layoutPosition); if( null == when ){ forecastIndex = 0; } else { forecastIndex = timeLayout.getIndexForTime(when); } } } String iconLink = null; if( forecastIndex > -1 ){ // Get the weather conditions out. iconLink = conditionsIcon.iconLink.get(forecastIndex); } // Now figure out which Icon matches up with our icon's link // Get the filename out of the icon link. if( null != iconLink ){ Pattern getConditionCode = Pattern.compile("^.*/(?:hi_)?(?:m_)?n?([a-z]*)\\d*.(?:jpg||png)$"); Matcher codeMatcher = getConditionCode.matcher(iconLink); if( codeMatcher.matches() ){ String code = codeMatcher.group(1); return Icon.getByIconName(code); } } } return null; } }
package io.bitsquare.p2p.peers; import io.bitsquare.app.Log; import io.bitsquare.common.Clock; import io.bitsquare.common.Timer; import io.bitsquare.common.UserThread; import io.bitsquare.p2p.NodeAddress; import io.bitsquare.p2p.network.*; import io.bitsquare.p2p.peers.peerexchange.Peer; import io.bitsquare.storage.Storage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class PeerManager implements ConnectionListener { // Static private static final Logger log = LoggerFactory.getLogger(PeerManager.class); private static final long CHECK_MAX_CONN_DELAY_SEC = Timer.STRESS_TEST ? 1 : 5; // Use a long delay as the bootstrapping peer might need a while until it knows its onion address private static final long REMOVE_ANONYMOUS_PEER_SEC = Timer.STRESS_TEST ? 10 : 120; private static int MAX_CONNECTIONS; private static int MIN_CONNECTIONS; private static int MAX_CONNECTIONS_PEER; private static int MAX_CONNECTIONS_NON_DIRECT; private static int MAX_CONNECTIONS_ABSOLUTE; private final boolean printReportedPeersDetails = true; private boolean lostAllConnections; public static void setMaxConnections(int maxConnections) { MAX_CONNECTIONS = maxConnections; MIN_CONNECTIONS = Math.max(1, maxConnections - 4); MAX_CONNECTIONS_PEER = MAX_CONNECTIONS + 4; MAX_CONNECTIONS_NON_DIRECT = MAX_CONNECTIONS + 8; MAX_CONNECTIONS_ABSOLUTE = MAX_CONNECTIONS + 18; } static { setMaxConnections(12); } private static final int MAX_REPORTED_PEERS = 1000; private static final int MAX_PERSISTED_PEERS = 500; private static final long MAX_AGE = TimeUnit.DAYS.toMillis(14); // max age for reported peers is 14 days // Listener public interface Listener { void onAllConnectionsLost(); void onNewConnectionAfterAllConnectionsLost(); void onAwakeFromStandby(); } // Instance fields private final NetworkNode networkNode; private Clock clock; private final Set<NodeAddress> seedNodeAddresses; private final Storage<HashSet<Peer>> dbStorage; private final HashSet<Peer> persistedPeers = new HashSet<>(); private final Set<Peer> reportedPeers = new HashSet<>(); private Timer checkMaxConnectionsTimer; private final Clock.Listener listener; private final List<Listener> listeners = new CopyOnWriteArrayList<>(); private boolean stopped; // Constructor public PeerManager(NetworkNode networkNode, Set<NodeAddress> seedNodeAddresses, File storageDir, Clock clock) { this.networkNode = networkNode; this.clock = clock; // seedNodeAddresses can be empty (in case there is only 1 seed node, the seed node starting up has no other seed nodes) this.seedNodeAddresses = new HashSet<>(seedNodeAddresses); networkNode.addConnectionListener(this); dbStorage = new Storage<>(storageDir); HashSet<Peer> persistedPeers = dbStorage.initAndGetPersisted("PersistedPeers"); if (persistedPeers != null) { log.info("We have persisted reported peers. persistedPeers.size()=" + persistedPeers.size()); this.persistedPeers.addAll(persistedPeers); } // we check if app was idle for more then 5 sec. listener = new Clock.Listener() { @Override public void onSecondTick() { } @Override public void onMinuteTick() { } @Override public void onMissedSecondTick(long missed) { if (missed > Clock.IDLE_TOLERANCE) { log.warn("We have been in standby mode for {} sec", missed / 1000); stopped = false; listeners.stream().forEach(Listener::onAwakeFromStandby); } } }; clock.addListener(listener); } public void shutDown() { Log.traceCall(); networkNode.removeConnectionListener(this); clock.removeListener(listener); stopCheckMaxConnectionsTimer(); } // API public int getMaxConnections() { return MAX_CONNECTIONS_ABSOLUTE; } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } // ConnectionListener implementation @Override public void onConnection(Connection connection) { if (isSeedNode(connection)) connection.setPeerType(Connection.PeerType.SEED_NODE); doHouseKeeping(); if (lostAllConnections) { lostAllConnections = false; stopped = false; listeners.stream().forEach(Listener::onNewConnectionAfterAllConnectionsLost); } } @Override public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) { handleConnectionFault(connection); lostAllConnections = networkNode.getAllConnections().isEmpty(); if (lostAllConnections) { stopped = true; listeners.stream().forEach(Listener::onAllConnectionsLost); } } @Override public void onError(Throwable throwable) { } // Housekeeping private void doHouseKeeping() { if (checkMaxConnectionsTimer == null) { printConnectedPeers(); checkMaxConnectionsTimer = UserThread.runAfter(() -> { stopCheckMaxConnectionsTimer(); if (!stopped) { removeAnonymousPeers(); removeSuperfluousSeedNodes(); removeTooOldReportedPeers(); removeTooOldPersistedPeers(); checkMaxConnections(MAX_CONNECTIONS); } else { log.warn("We have stopped already. We ignore that checkMaxConnectionsTimer.run call."); } }, CHECK_MAX_CONN_DELAY_SEC); } } private boolean checkMaxConnections(int limit) { Log.traceCall("limit=" + limit); Set<Connection> allConnections = networkNode.getAllConnections(); int size = allConnections.size(); log.info("We have {} connections open. Our limit is {}", size, limit); if (size > limit) { log.info("We have too many connections open.\n\t" + "Lets try first to remove the inbound connections of type PEER."); List<Connection> candidates = allConnections.stream() .filter(e -> e instanceof InboundConnection) .filter(e -> e.getPeerType() == Connection.PeerType.PEER) .collect(Collectors.toList()); if (candidates.size() == 0) { log.info("No candidates found. We check if we exceed our " + "MAX_CONNECTIONS_PEER limit of {}", MAX_CONNECTIONS_PEER); if (size > MAX_CONNECTIONS_PEER) { log.info("Lets try to remove ANY connection of type PEER."); candidates = allConnections.stream() .filter(e -> e.getPeerType() == Connection.PeerType.PEER) .collect(Collectors.toList()); if (candidates.size() == 0) { log.info("No candidates found. We check if we exceed our " + "MAX_CONNECTIONS_NON_DIRECT limit of {}", MAX_CONNECTIONS_NON_DIRECT); if (size > MAX_CONNECTIONS_NON_DIRECT) { log.info("Lets try to remove any connection which is not of type DIRECT_MSG_PEER."); candidates = allConnections.stream() .filter(e -> e.getPeerType() != Connection.PeerType.DIRECT_MSG_PEER) .collect(Collectors.toList()); if (candidates.size() == 0) { log.info("No candidates found. We check if we exceed our " + "MAX_CONNECTIONS_ABSOLUTE limit of {}", MAX_CONNECTIONS_ABSOLUTE); if (size > MAX_CONNECTIONS_ABSOLUTE) { log.info("Lets try to remove any connection."); candidates = allConnections.stream().collect(Collectors.toList()); } } } } } } if (candidates.size() > 0) { candidates.sort((o1, o2) -> ((Long) o1.getStatistic().getLastActivityTimestamp()).compareTo(((Long) o2.getStatistic().getLastActivityTimestamp()))); log.info("Candidates.size() for shut down=" + candidates.size()); Connection connection = candidates.remove(0); log.info("We are going to shut down the oldest connection.\n\tconnection=" + connection.toString()); if (!connection.isStopped()) connection.shutDown(CloseConnectionReason.TOO_MANY_CONNECTIONS_OPEN, () -> checkMaxConnections(limit)); return true; } else { log.warn("No candidates found to remove (That case should not be possible as we use in the " + "last case all connections).\n\t" + "allConnections=", allConnections); return false; } } else { log.trace("We only have {} connections open and don't need to close any.", size); return false; } } private void removeAnonymousPeers() { Log.traceCall(); networkNode.getAllConnections().stream() .filter(connection -> !connection.hasPeersNodeAddress()) .forEach(connection -> UserThread.runAfter(() -> { // We give 30 seconds delay and check again if still no address is set if (!connection.hasPeersNodeAddress() && !connection.isStopped()) { log.info("We close the connection as the peer address is still unknown.\n\t" + "connection=" + connection); connection.shutDown(CloseConnectionReason.UNKNOWN_PEER_ADDRESS); } }, REMOVE_ANONYMOUS_PEER_SEC)); } private void removeSuperfluousSeedNodes() { Log.traceCall(); if (networkNode.getConfirmedConnections().size() > MAX_CONNECTIONS) { Set<Connection> connections = networkNode.getConfirmedConnections(); if (hasSufficientConnections()) { List<Connection> candidates = connections.stream() .filter(this::isSeedNode) .collect(Collectors.toList()); if (candidates.size() > 1) { candidates.sort((o1, o2) -> ((Long) o1.getStatistic().getLastActivityTimestamp()).compareTo(((Long) o2.getStatistic().getLastActivityTimestamp()))); log.info("Number of connections exceeding MAX_CONNECTIONS_EXTENDED_1. Current size=" + candidates.size()); Connection connection = candidates.remove(0); log.info("We are going to shut down the oldest connection.\n\tconnection=" + connection.toString()); connection.shutDown(CloseConnectionReason.TOO_MANY_SEED_NODES_CONNECTED, this::removeSuperfluousSeedNodes); } } } } // Reported peers private boolean removeReportedPeer(Peer reportedPeer) { boolean contained = reportedPeers.remove(reportedPeer); printReportedPeers(); return contained; } @Nullable private Peer removeReportedPeer(NodeAddress nodeAddress) { Optional<Peer> reportedPeerOptional = reportedPeers.stream() .filter(e -> e.nodeAddress.equals(nodeAddress)).findAny(); if (reportedPeerOptional.isPresent()) { Peer reportedPeer = reportedPeerOptional.get(); removeReportedPeer(reportedPeer); return reportedPeer; } else { return null; } } private void removeTooOldReportedPeers() { Log.traceCall(); Set<Peer> reportedPeersToRemove = reportedPeers.stream() .filter(reportedPeer -> new Date().getTime() - reportedPeer.date.getTime() > MAX_AGE) .collect(Collectors.toSet()); reportedPeersToRemove.forEach(this::removeReportedPeer); } public Set<Peer> getReportedPeers() { return reportedPeers; } public void addToReportedPeers(HashSet<Peer> reportedPeersToAdd, Connection connection) { printNewReportedPeers(reportedPeersToAdd); // We check if the reported msg is not violating our rules if (reportedPeersToAdd.size() <= (MAX_REPORTED_PEERS + MAX_CONNECTIONS_ABSOLUTE + 10)) { reportedPeers.addAll(reportedPeersToAdd); purgeReportedPeersIfExceeds(); persistedPeers.addAll(reportedPeersToAdd); purgePersistedPeersIfExceeds(); if (dbStorage != null) dbStorage.queueUpForSave(persistedPeers, 2000); printReportedPeers(); } else { // If a node is trying to send too many peers we treat it as rule violation. // Reported peers include the connected peers. We use the max value and give some extra headroom. // Will trigger a shutdown after 2nd time sending too much connection.reportIllegalRequest(RuleViolation.TOO_MANY_REPORTED_PEERS_SENT); } } private void purgeReportedPeersIfExceeds() { Log.traceCall(); int size = reportedPeers.size(); int limit = MAX_REPORTED_PEERS - MAX_CONNECTIONS_ABSOLUTE; if (size > limit) { log.trace("We have already {} reported peers which exceeds our limit of {}." + "We remove random peers from the reported peers list.", size, limit); int diff = size - limit; List<Peer> list = new ArrayList<>(reportedPeers); // we dont use sorting by lastActivityDate to keep it more random for (int i = 0; i < diff; i++) { Peer toRemove = list.remove(new Random().nextInt(list.size())); removeReportedPeer(toRemove); } } else { log.trace("No need to purge reported peers.\n\tWe don't have more then {} reported peers yet.", MAX_REPORTED_PEERS); } } private void printReportedPeers() { if (!reportedPeers.isEmpty()) { if (printReportedPeersDetails) { StringBuilder result = new StringBuilder("\n\n "Collected reported peers:"); reportedPeers.stream().forEach(e -> result.append("\n").append(e)); result.append("\n log.info(result.toString()); } log.info("Number of collected reported peers: {}", reportedPeers.size()); } } private void printNewReportedPeers(HashSet<Peer> reportedPeers) { if (printReportedPeersDetails) { StringBuilder result = new StringBuilder("We received new reportedPeers:"); reportedPeers.stream().forEach(e -> result.append("\n\t").append(e)); log.info(result.toString()); } log.info("Number of new arrived reported peers: {}", reportedPeers.size()); } // Persisted peers private boolean removePersistedPeer(Peer persistedPeer) { if (persistedPeers.contains(persistedPeer)) { persistedPeers.remove(persistedPeer); if (dbStorage != null) dbStorage.queueUpForSave(persistedPeers, 2000); return true; } else { return false; } } private boolean removePersistedPeer(NodeAddress nodeAddress) { Optional<Peer> persistedPeerOptional = getPersistedPeerOptional(nodeAddress); return persistedPeerOptional.isPresent() && removePersistedPeer(persistedPeerOptional.get()); } private Optional<Peer> getPersistedPeerOptional(NodeAddress nodeAddress) { return persistedPeers.stream() .filter(e -> e.nodeAddress.equals(nodeAddress)).findAny(); } private void removeTooOldPersistedPeers() { Log.traceCall(); Set<Peer> persistedPeersToRemove = persistedPeers.stream() .filter(reportedPeer -> new Date().getTime() - reportedPeer.date.getTime() > MAX_AGE) .collect(Collectors.toSet()); persistedPeersToRemove.forEach(this::removePersistedPeer); } private void purgePersistedPeersIfExceeds() { Log.traceCall(); int size = persistedPeers.size(); int limit = MAX_PERSISTED_PEERS; if (size > limit) { log.trace("We have already {} persisted peers which exceeds our limit of {}." + "We remove random peers from the persisted peers list.", size, limit); int diff = size - limit; List<Peer> list = new ArrayList<>(persistedPeers); // we dont use sorting by lastActivityDate to avoid attack vectors and keep it more random for (int i = 0; i < diff; i++) { Peer toRemove = list.remove(new Random().nextInt(list.size())); removePersistedPeer(toRemove); } } else { log.trace("No need to purge persisted peers.\n\tWe don't have more then {} persisted peers yet.", MAX_PERSISTED_PEERS); } } public Set<Peer> getPersistedPeers() { return persistedPeers; } // Misc public boolean hasSufficientConnections() { return networkNode.getNodeAddressesOfConfirmedConnections().size() >= MIN_CONNECTIONS; } public boolean isSeedNode(Peer reportedPeer) { return seedNodeAddresses.contains(reportedPeer.nodeAddress); } public boolean isSeedNode(NodeAddress nodeAddress) { return seedNodeAddresses.contains(nodeAddress); } public boolean isSeedNode(Connection connection) { return connection.hasPeersNodeAddress() && seedNodeAddresses.contains(connection.getPeersNodeAddressOptional().get()); } public boolean isSelf(Peer reportedPeer) { return isSelf(reportedPeer.nodeAddress); } public boolean isSelf(NodeAddress nodeAddress) { return nodeAddress.equals(networkNode.getNodeAddress()); } public boolean isConfirmed(Peer reportedPeer) { return isConfirmed(reportedPeer.nodeAddress); } // Checks if that connection has the peers node address public boolean isConfirmed(NodeAddress nodeAddress) { return networkNode.getNodeAddressesOfConfirmedConnections().contains(nodeAddress); } public void handleConnectionFault(Connection connection) { connection.getPeersNodeAddressOptional().ifPresent(nodeAddress -> handleConnectionFault(nodeAddress, connection)); } public void handleConnectionFault(NodeAddress nodeAddress) { handleConnectionFault(nodeAddress, null); } public void handleConnectionFault(NodeAddress nodeAddress, @Nullable Connection connection) { Log.traceCall("nodeAddress=" + nodeAddress); boolean doRemovePersistedPeer = false; removeReportedPeer(nodeAddress); Optional<Peer> persistedPeerOptional = getPersistedPeerOptional(nodeAddress); if (persistedPeerOptional.isPresent()) { Peer persistedPeer = persistedPeerOptional.get(); persistedPeer.increaseFailedConnectionAttempts(); doRemovePersistedPeer = persistedPeer.tooManyFailedConnectionAttempts(); } doRemovePersistedPeer = doRemovePersistedPeer || (connection != null && connection.getRuleViolation() != null); if (doRemovePersistedPeer) removePersistedPeer(nodeAddress); else removeTooOldPersistedPeers(); } public void shutDownConnection(Connection connection, CloseConnectionReason closeConnectionReason) { if (connection.getPeerType() != Connection.PeerType.DIRECT_MSG_PEER) connection.shutDown(closeConnectionReason); } public void shutDownConnection(NodeAddress peersNodeAddress, CloseConnectionReason closeConnectionReason) { networkNode.getAllConnections().stream() .filter(connection -> connection.getPeersNodeAddressOptional().isPresent() && connection.getPeersNodeAddressOptional().get().equals(peersNodeAddress) && connection.getPeerType() != Connection.PeerType.DIRECT_MSG_PEER) .findAny() .ifPresent(connection -> connection.shutDown(closeConnectionReason)); } public HashSet<Peer> getConnectedNonSeedNodeReportedPeers(NodeAddress excludedNodeAddress) { return new HashSet<>(getConnectedNonSeedNodeReportedPeers().stream() .filter(e -> !e.nodeAddress.equals(excludedNodeAddress)) .collect(Collectors.toSet())); } // Private private Set<Peer> getConnectedReportedPeers() { // networkNode.getConfirmedConnections includes: // filter(connection -> connection.getPeersNodeAddressOptional().isPresent()) return networkNode.getConfirmedConnections().stream() .map(c -> new Peer(c.getPeersNodeAddressOptional().get())) .collect(Collectors.toSet()); } private HashSet<Peer> getConnectedNonSeedNodeReportedPeers() { return new HashSet<>(getConnectedReportedPeers().stream() .filter(e -> !isSeedNode(e)) .collect(Collectors.toSet())); } private void stopCheckMaxConnectionsTimer() { if (checkMaxConnectionsTimer != null) { checkMaxConnectionsTimer.stop(); checkMaxConnectionsTimer = null; } } private void printConnectedPeers() { if (!networkNode.getConfirmedConnections().isEmpty()) { StringBuilder result = new StringBuilder("\n\n "Connected peers for node " + networkNode.getNodeAddress() + ":"); networkNode.getConfirmedConnections().stream().forEach(e -> result.append("\n") .append(e.getPeersNodeAddressOptional().get()).append(" ").append(e.getPeerType())); result.append("\n log.info(result.toString()); } } }
package org.alltiny.chorus.gui.canvas; import org.alltiny.chorus.dom.clef.Clef; import org.alltiny.chorus.dom.Element; import org.alltiny.chorus.dom.Note; import org.alltiny.chorus.dom.Rest; import org.alltiny.chorus.dom.decoration.AccidentalSign; import org.alltiny.chorus.dom.decoration.Bound; import org.alltiny.chorus.dom.decoration.Decoration; import org.alltiny.chorus.dom.decoration.Triplet; import org.alltiny.chorus.gui.layout.ColSpanGridConstraints; import org.alltiny.chorus.gui.layout.GridConstraints; import org.alltiny.chorus.gui.layout.MedianGridLayout; import org.alltiny.chorus.render.Visual; import org.alltiny.chorus.render.element.*; import org.alltiny.chorus.render.element.Cell; import org.alltiny.chorus.model.SongModel; import org.alltiny.chorus.model.MusicDataModel; import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.util.ArrayList; import java.util.HashMap; /** * This class represents * * @author <a href="mailto:ralf.hergert.de@gmail.com">Ralf Hergert</a> * @version 03.12.2008 16:58:50 */ public class MusicCanvas extends JComponent implements Scrollable { public static final String CURRENT_CURSOR_POSITION = "currentCursorPosition"; public static final String ZOOM_FACTOR = "zoomFactor"; private static final int HPADDING_LINE = 40; private static final int VPADDING_LINE = 20; private static final double LEAD_OFFSET = 6.5; private final SongModel model; private final MusicDataModel songModel; private final MedianGridLayout layout; // this is a helper list to get the correct column for the current tick. private final TickColumnMap tickColumnMap = new TickColumnMap(); private Zoom zoom = Zoom.FIT_TO_HEIGHT; private double zoomFactor = 1; private Rectangle cursorPosition; public MusicCanvas(SongModel model, final MusicDataModel songModel) { this.model = model; this.songModel = songModel; layout = new MedianGridLayout(); setLayout(layout); setOpaque(true); setDoubleBuffered(true); model.addPropertyChangeListener(SongModel.CURRENT_SONG, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { update(); revalidate(); repaint(); } }); update(); } public void paintComponent(Graphics graphics) { Graphics2D g = (Graphics2D)graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setBackground(Color.WHITE); g.setColor(Color.BLACK); g.clearRect(0,0,getWidth(),getHeight()); g.scale(zoomFactor,zoomFactor); g.transform(AffineTransform.getTranslateInstance(VPADDING_LINE, HPADDING_LINE)); // only draw all components in clipping bounds. for (Component comp : layout.getComponentsInClipBounds(g.getClipBounds())) { comp.paint(g); } } private void update() { final int numVoice = songModel.getNumberOfVoices(); // remove all components removeAll(); // clear the tick column helper map. tickColumnMap.clear(); // ArrayList ArrayList<Lines> lines = new ArrayList<Lines>(); for (int i = 0; i < numVoice; i++) { lines.add(new Lines()); // assign the lines also to this container to be drawn. note that the lines must not be layed out. add(lines.get(i)); } int currentColumn = 0; final int linesStartCol = currentColumn; // draw a leading BarLine... for (int i = 0; i < numVoice; i++) { // create the starting BarLine on the left. Visual barLine = new BarLine().setPadding(new Rectangle2D.Float(0,0,0,0)); // finally add the cell to the grid. add(barLine, new GridConstraints(getNotesRowOfVoice(i), currentColumn)); } currentColumn++; // draw clefts for (int i = 0; i < numVoice; i++) { Cell cell = new Cell(); if (model.getSong().getMusic().getVoices().get(i).getSequence().getClef() == Clef.G) { cell.addVisualToNotes(new ClefG()); } if (model.getSong().getMusic().getVoices().get(i).getSequence().getClef() == Clef.G8basso) { cell.addVisualToNotes(new ClefG8basso()); } if (model.getSong().getMusic().getVoices().get(i).getSequence().getClef() == Clef.F) { cell.addVisualToNotes(new ClefF()); } // finally add the cell to the grid. add(cell, new GridConstraints(getNotesRowOfVoice(i), currentColumn)); } currentColumn++; // draw keys for (int i = 0; i < numVoice; i++) { add(new KeyRender(model.getSong().getMusic().getVoices().get(i).getSequence()), new GridConstraints(getNotesRowOfVoice(i), currentColumn)); } currentColumn++; /* * The helper maps a created here because the notes are processed by frames and not be voices. */ // create a key map for each voice. KeyMapHelper[] keyMapper = new KeyMapHelper[numVoice]; // create a helper map for bindings. HashMap<Integer, BindingHelper>[] bindingHelpers = new HashMap[numVoice]; TripletHelper[] tripletHelpers = new TripletHelper[numVoice]; for (int i = 0; i < numVoice; i++) { keyMapper[i] = new KeyMapHelper(model.getSong().getMusic().getVoices().get(i).getSequence().getKey()); bindingHelpers[i] = new HashMap<Integer,BindingHelper>(); } int numberOfBeat = 1; for (org.alltiny.chorus.model.Frame frame : songModel.getFrames()) { // if this frame should start with a bar, then add a bar to the lines. if (frame.isNewBarStarts()) { numberOfBeat++; // add a number to the beat. add(new BeatNumber(numberOfBeat), new GridConstraints(0, currentColumn)); for (int i = 0; i < numVoice; i++) { // add a bar line to each voice line. add(new BarLine(), new GridConstraints(getNotesRowOfVoice(i), currentColumn)); // reset all key mappings. keyMapper[i].clear(); } currentColumn++; } // create a TickHelper for this frame only if this frame has elements with duration. if (frame.getTickLength() > 0) { tickColumnMap.addMapping(currentColumn, frame.getTickOffset(), frame.getTickLength()); } for (int voiceIndex = 0; voiceIndex < numVoice; voiceIndex++) { Cell cell = new Cell(); // create a helper map for bindings. HashMap<Integer, BindingHelper> bindingHelper = bindingHelpers[voiceIndex]; for (Element element : frame.get(voiceIndex)) { if (element instanceof Note) { Note note = (Note)element; // get the current accidental modification for this note. AccidentalSign sign = keyMapper[voiceIndex].getAccidentalSign(note.getOctave(), note.getNote()); NoteRender renderer = new NoteRender(note); // check whether the current modification conflicts with the note accidental. if (sign != note.getSign()) { // register the modification to the mapping to influence trailing notes. keyMapper[voiceIndex].setAccidentalSign(note.getOctave(), note.getNote(), note.getSign()); renderer.setDrawAccidentalSign(true); } // check if lyrics are assign to the note. if (note.getLyric() != null) { add(new Lyrics(note.getLyric()), new GridConstraints(getLyricsRowOfVoice(voiceIndex), currentColumn)); } // check for bindings Bound bound = getBoundDecorFromNote(note); if (bound != null) { // check if a previous binding already exists if (bindingHelper.containsKey(bound.getRef())) { BindingHelper helper = bindingHelper.get(bound.getRef()); // create a new binding. Binding binding = new Binding().setStartElement(helper.getRender()).setEndElement(renderer); // add the binding to the layout. add(binding, new ColSpanGridConstraints(getNotesRowOfVoice(voiceIndex), helper.getColumn(), currentColumn)); } // add the current note render to be able to create a binding for it. bindingHelper.put(bound.getRef(), new BindingHelper(currentColumn, renderer)); } else { // remove all binding infos if the note is unbound. bindingHelper.clear(); } // check for triplets Triplet triplet = getTripletDecorFromNote(note); if (triplet != null) { // does a current triplet already exist? if (tripletHelpers[voiceIndex] != null) { if (tripletHelpers[voiceIndex].getTripletRefId() == triplet.getRef()) { tripletHelpers[voiceIndex].getCurrentTripletSpan().setEndElement(renderer); tripletHelpers[voiceIndex].setEndColumn(currentColumn); } else { // if the ref ids do not match then add the current TripletSpan to the layout. addTripletSpanToLayout(tripletHelpers[voiceIndex]); tripletHelpers[voiceIndex] = null; } } if (tripletHelpers[voiceIndex] == null) { tripletHelpers[voiceIndex] = new TripletHelper(voiceIndex, triplet.getRef(), currentColumn, new TripletSpan().setStartElement(renderer).setEndElement(renderer)); } } else if (tripletHelpers[voiceIndex] != null) { addTripletSpanToLayout(tripletHelpers[voiceIndex]); tripletHelpers[voiceIndex] = null; } cell.addVisualToNotes(renderer); } if (element instanceof Rest) { cell.addVisualToNotes(new RestRender((Rest)element)); } } add(cell, new GridConstraints(getNotesRowOfVoice(voiceIndex), currentColumn)); } currentColumn++; } // check if a missing tripletHelper exists. for (int i = 0; i < numVoice; i++) { if (tripletHelpers[i] != null) { addTripletSpanToLayout(tripletHelpers[i]); tripletHelpers[i] = null; } } final int linesEndCol = currentColumn; // draw the trailing BarLines. for (int i = 0; i < numVoice; i++) { // create the ending BarLine on the right. Visual barLine = new BarLine().setPadding(new Rectangle2D.Float(0,0,0,0)); // finally add the cell to the grid. add(barLine, new GridConstraints(getNotesRowOfVoice(i), currentColumn)); } currentColumn++; // add the lines to the grid for (int i = 0; i < numVoice; i++) { add(new Lines(), new ColSpanGridConstraints(getNotesRowOfVoice(i), linesStartCol, linesEndCol)); } // update the current cursor position. getXPosForTick(0); } private void addTripletSpanToLayout(final TripletHelper helper) { add(helper.getCurrentTripletSpan(), new ColSpanGridConstraints(getNotesRowOfVoice(helper.getVoiceIndex()), helper.getStartColumn(), helper.getEndColumn())); } private Bound getBoundDecorFromNote(Note note) { for (Decoration decor : note.getDecorations()) { if (decor instanceof Bound) { return (Bound)decor; } } return null; } private Triplet getTripletDecorFromNote(Note note) { for (Decoration decor : note.getDecorations()) { if (decor instanceof Triplet) { return (Triplet)decor; } } return null; } private int getNotesRowOfVoice(int i) { return i * 2 + 1; } private int getLyricsRowOfVoice(int i) { return i * 2 + 2; } public Dimension getPreferredSize() { int height = super.getPreferredSize().height; int width = super.getPreferredSize().width; if (height > 0) { height += 2 * HPADDING_LINE; // add an additional padding. } if (width > 0) { width += 2 * VPADDING_LINE; } return new Dimension((int)(width * zoomFactor), (int)(height * zoomFactor)); } public void setZoom(Zoom zoom) { this.zoom = zoom; revalidate(); } public Zoom getZoom() { return zoom; } public double getZoomFactor() { return zoomFactor; } public void setZoomFactor(double newZoomFactor) { double old = zoomFactor; if (zoomFactor != newZoomFactor) { zoomFactor = newZoomFactor; firePropertyChange(ZOOM_FACTOR, old, newZoomFactor); revalidate(); } } public void setSize(int width, int height) { /* * I assume that the Scrolpane calls this method to inform this canvas * about the possible size. */ final Dimension currentPrefSize = getPreferredSize(); double fitHeightZoom = (currentPrefSize.height == 0) ? 1 : (double)height / currentPrefSize.height; double fitWidthZoom = (currentPrefSize.width == 0) ? 1 : (double)width / currentPrefSize.width; switch (zoom) { case FIT_TO_HEIGHT: setZoomFactor(zoomFactor * fitHeightZoom); break; case FIT_TO_WIDTH: setZoomFactor(zoomFactor * fitWidthZoom); break; case FIT_BOTH: setZoomFactor(zoomFactor * Math.min(fitHeightZoom, fitWidthZoom)); break; default: /* don not change the zoom factor */ } final Dimension zoomedPrefSize = getPreferredSize(); super.setSize(zoomedPrefSize.width, zoomedPrefSize.height); } public double getXPosForTick(long tick) { final TickInfo info = tickColumnMap.getInfoForTick(tick); if (info == null) { return 0; } // now i is the index of the column in which the tick is. get the x position. double startPosX = layout.getAbsMedianX(info.getColMin()); double endPosX = (info.getColMax() != 0) ? layout.getAbsMedianX(info.getColMax() + 1) : layout.getAbsMedianX(info.getColMin()) + layout.getExtendRight(info.getColMin()); final double ratio = (double)(tick - info.getTickMin()) / (info.getTickMax() - info.getTickMin()); final double xPos = startPosX + ratio * (endPosX - startPosX) + VPADDING_LINE - LEAD_OFFSET; setCursorPosition(new Rectangle((int)Math.round(xPos * getZoomFactor()), HPADDING_LINE ,1, 50)); return xPos; } public long getTickForPos(final double position) { double pos = position / getZoomFactor() - VPADDING_LINE + LEAD_OFFSET; int minCol = layout.getMinColumnIndexAtPosition(pos); int maxCol = layout.getMaxColumnIndexAtPosition(pos); double minX = layout.getAbsMedianX(minCol); double maxX = layout.getAbsMedianX(maxCol) + layout.getExtendRight(maxCol); long minTick = tickColumnMap.getInfoForColumn(minCol).getTickMin(); long maxTick = tickColumnMap.getInfoForColumn(maxCol).getTickMax(); double ratio = (pos - minX) / (maxX - minX); ratio = Math.max(ratio, 0); ratio = Math.min(ratio, 1); return Math.round(minTick + ratio * (maxTick - minTick)); } public void setCursorPosition(Rectangle newCursorPosition) { Rectangle old = cursorPosition; cursorPosition = newCursorPosition; firePropertyChange(CURRENT_CURSOR_POSITION, old, newCursorPosition); } public Rectangle getCurrentCursorPosition() { return cursorPosition; } public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return (int)(0.3 * getScrollableBlockIncrement(visibleRect, orientation, direction)); } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return orientation == SwingConstants.HORIZONTAL ? visibleRect.width : visibleRect.height; } public boolean getScrollableTracksViewportWidth() { return zoom == Zoom.FIT_TO_WIDTH || zoom == Zoom.FIT_BOTH; } public boolean getScrollableTracksViewportHeight() { return zoom == Zoom.FIT_TO_HEIGHT || zoom == Zoom.FIT_BOTH; } public enum Zoom { FIT_TO_HEIGHT, FIT_TO_WIDTH, FIT_BOTH, ZOOM } /** Helper class to associate a column and its render element. */ private static class BindingHelper { private int column; private NoteRender render; private BindingHelper(int column, NoteRender render) { this.column = column; this.render = render; } public int getColumn() { return column; } public NoteRender getRender() { return render; } } /** Helper class to associate some objects together. */ private static class TripletHelper { private final int voiceIndex; private final int tripletRefId; private final int startColumn; private int endColumn; private final TripletSpan currentTripletSpan; private TripletHelper(int voiceIndex, int tripletRefId, int startColumn, TripletSpan currentTripletSpan) { this.voiceIndex = voiceIndex; this.tripletRefId = tripletRefId; this.startColumn = startColumn; this.endColumn = startColumn; this.currentTripletSpan = currentTripletSpan; } public int getVoiceIndex() { return voiceIndex; } public int getTripletRefId() { return tripletRefId; } public int getStartColumn() { return startColumn; } public int getEndColumn() { return endColumn; } public void setEndColumn(int endColumn) { this.endColumn = endColumn; } public TripletSpan getCurrentTripletSpan() { return currentTripletSpan; } } }
package com.github.podd.client.api; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.model.Model; import org.openrdf.model.URI; import org.openrdf.model.vocabulary.RDFS; import org.openrdf.rio.RDFFormat; import org.semanticweb.owlapi.model.IRI; import com.github.ansell.restletutils.RestletUtilRole; import com.github.podd.api.DanglingObjectPolicy; import com.github.podd.api.DataReferenceVerificationPolicy; import com.github.podd.api.data.DataReference; import com.github.podd.utils.InferredOWLOntologyID; import com.github.podd.utils.PoddUser; /** * An interface defining the operations that are currently implemented by the PODD Web Services. * * @author Peter Ansell p_ansell@yahoo.com */ public interface PoddClient { /** * Fetch all of the properties for the given object URI. */ public static final String TEMPLATE_SPARQL_BY_URI = new StringBuilder() .append("CONSTRUCT { ?object ?predicate ?value . }") .append(" WHERE { ?object ?predicate ?value . }") .append(" VALUES ( ?object ) { ( %s ) }").toString(); /** * Fetch all of the properties for the given objects under the given parent with the given type. */ public static final String TEMPLATE_SPARQL_BY_TYPE_AND_PARENT_ALL_PROPERTIES = new StringBuilder() .append("CONSTRUCT { ?parent ?parentPredicate ?object . ?object a ?type . ?object ?predicate ?label . }") .append(" WHERE { ?parent ?parentPredicate ?object . ?object a ?type . OPTIONAL { ?object ?predicate ?label . } }") .append(" VALUES (?parent ?parentPredicate ?type ) { ( %s %s %s ) }").toString(); /** * Fetch type and label and barcode statements for the given object type. */ public static final String TEMPLATE_SPARQL_BY_TYPE_WITH_LABEL = new StringBuilder() .append("CONSTRUCT { ?object a ?type . ") .append(" ?object <http://www.w3.org/2000/01/rdf-schema#label> ?label . ") .append(" ?object <http://purl.org/podd/ns/poddScience#hasBarcode> ?barcode . } ") .append(" WHERE { ?object a ?type . ") .append(" OPTIONAL { ?object <http://www.w3.org/2000/01/rdf-schema#label> ?label . }") .append(" OPTIONAL { ?object <http://purl.org/podd/ns/poddScience#hasBarcode> ?barcode . } }") .append(" VALUES (?type) { ( %s ) }").toString(); /** * Fetch all of the properties for the given objects with the given type */ public static final String TEMPLATE_SPARQL_BY_TYPE_ALL_PROPERTIES = new StringBuilder() .append("CONSTRUCT { ?object a ?type . ?object ?predicate ?value . }") .append(" WHERE { ?object a ?type . ?object ?predicate ?value . }").append(" VALUES (?type) { ( %s ) }") .toString(); public static final String TEMPLATE_SPARQL_BY_TYPE_LABEL_STRSTARTS = new StringBuilder() .append("CONSTRUCT { ?object a ?type . ?object <http://www.w3.org/2000/01/rdf-schema#label> ?label . }") .append(" WHERE { ?object a ?type . ?object <http://www.w3.org/2000/01/rdf-schema#label> ?label . FILTER(STRSTARTS(?label, \"%s\")) }") .append(" VALUES (?type) { ( %s ) }").toString(); public static final String TEMPLATE_SPARQL_BY_BARCODE_STRSTARTS = new StringBuilder() .append("CONSTRUCT { ?object a ?type . ?object <http://purl.org/podd/ns/poddScience#hasBarcode> ?barcode . ?object ?property ?value . }") .append(" WHERE { ?object a ?type . ?object <http://purl.org/podd/ns/poddScience#hasBarcode> ?barcode . FILTER(STRSTARTS(?barcode, \"%s\")). ?object ?property ?value . }") .append(" VALUES (?type) { ( %s ) }").toString(); public static final String TEMPLATE_SPARQL_BY_BARCODE_MATCH_NO_TYPE = new StringBuilder() .append("CONSTRUCT { ?object <http://purl.org/podd/ns/poddScience#hasBarcode> ?barcode . ?object ?property ?value . }") .append(" WHERE { ?object <http://purl.org/podd/ns/poddScience#hasBarcode> ?barcode . FILTER(STR(?barcode) = \"%s\"). ?object ?property ?value . }") .toString(); public static final String TEMPLATE_SPARQL_CONTAINERS_TO_MATERIAL_AND_GENOTYPE = new StringBuilder() .append("CONSTRUCT { ?container <http://purl.org/podd/ns/poddScience .append(" WHERE { ?container <http://purl.org/podd/ns/poddScience .append(" VALUES (?container) { %s }").toString(); /** * NOTE: Both the first and second arguments are the predicate, the first being the mapped * predicate, and the second being the original predicate. */ public static final String TEMPLATE_SPARQL_BY_TYPE_LABEL_STRSTARTS_PREDICATE = new StringBuilder() .append("CONSTRUCT { ?object a ?type . ?object %s ?label . }") .append(" WHERE { ?object a ?type . ?object %s ?label . FILTER(STRSTARTS(?label, \"%s\")) }") .append(" VALUES (?type) { ( %s ) }").toString(); public static final String TEMPLATE_SPARQL_TRAY_POT_NUMBER_TO_BARCODE = new StringBuilder().append("CONSTRUCT { ") .append(" ?pot <http://purl.org/podd/ns/poddScience#hasPotNumberTray> ?potNumberTray . ") .append(" ?pot <http://purl.org/podd/ns/poddScience#hasPotNumber> ?potNumberOverall . ") .append(" ?pot <http://purl.org/podd/ns/poddScience#hasBarcode> ?potBarcode . }") .append(" WHERE { ?tray <http://purl.org/podd/ns/poddScience#hasBarcode> ?trayBarcode . ") .append(" ?tray <http://purl.org/podd/ns/poddScience#hasPot> ?pot . ") .append(" ?pot <http://purl.org/podd/ns/poddScience#hasPotNumberTray> ?potNumberTray . ") .append(" ?pot <http://purl.org/podd/ns/poddScience#hasPotNumber> ?potNumberOverall . ") .append(" ?pot <http://purl.org/podd/ns/poddScience#hasBarcode> ?potBarcode . ") .append(" FILTER(STR(?trayBarcode) = \"%s\") }").toString(); /** * Adds the given role for the given user to the given artifact * * @param userIdentifier * @param role * @param artifact * @throws PoddClientException * If there is an error setting the role for the given user. */ void addRole(String userIdentifier, RestletUtilRole role, InferredOWLOntologyID artifact) throws PoddClientException; /** * Submits a request to the PODD Edit Artifact service to append to the artifact using the RDF * triples that are contained in the given {@link InputStream}. * <p> * If the given ontologyId contains a version IRI and the version is out of date, a * PoddClientException may be thrown if the server refuses to complete the operation due to the * version being out of date. In these cases the ontology would need to be manually merged, and * the update would need to be attempted again. * * @param ontologyIRI * The IRI of the Artifact to update. * @param format * The format of the RDF triples in the given InputStream. * @param partialInputStream * The partial set of RDF triples serialised into an InputStream in the given format * that will be appended to the given artifact. * @return An {@link InferredOWLOntologyID} object containing the details of the updated * artifact. */ InferredOWLOntologyID appendArtifact(InferredOWLOntologyID ontologyId, InputStream partialInputStream, RDFFormat format) throws PoddClientException; InferredOWLOntologyID appendArtifact(InferredOWLOntologyID ontologyId, InputStream partialInputStream, RDFFormat format, DanglingObjectPolicy danglingObjectPolicy, DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws PoddClientException; /** * Appends multiple artifacts in PODD. * * @param uploadQueue * A Map containing the keys for the artifacts, and Models containing the appended * content for each of the artifacts. * @return A map from the original keys to the new artifact keys after the changes. * @throws PoddClientException * If an error occurred. */ Map<InferredOWLOntologyID, InferredOWLOntologyID> appendArtifacts(Map<InferredOWLOntologyID, Model> uploadQueue) throws PoddClientException; /** * Submits a request to the PODD File Reference Attachment service to attach a file reference * from a registered repository into the artifact as a child of the given object IRI. * <p> * If the given ontologyId contains a version IRI and the version is out of date, a * PoddClientException may be thrown if the server refuses to complete the operation due to the * version being out of date. In these cases the ontology would need to be manually merged, and * the update would need to be attempted again. * * @param ontologyId * The {@link InferredOWLOntologyID} of the artifact to attach the file reference to. * @param objectIRI * The IRI of the object to attach the file reference to. * @param label * A label to attach to the file reference. * @param repositoryAlias * The alias of the repository that the file is located in. * @param filePathInRepository * The path inside of the repository that can be used to locate the file. * @return An {@link InferredOWLOntologyID} object containing the details of the updated * artifact. */ InferredOWLOntologyID attachDataReference(DataReference ref) throws PoddClientException; /** * Creates a new PoddUser using the details in the given PoddUser. * * @param user * The user to create. * @return An instance of PoddUser containing the actual details of the created user, except for * the password. * @throws PoddClientException */ PoddUser createUser(PoddUser user) throws PoddClientException; /** * Submits a request to the PODD Delete Artifact service to delete the artifact identified by * the given IRI. * <p> * If the given ontologyId contains a version IRI and the version is out of date, a * PoddClientException may be thrown if the server refuses to complete the operation due to the * version being out of date. In these cases the ontology deletion would need to be attempted * again using the up to date version, or alternatively, by omitting the version IRI. * * @param ontologyId * The OWLOntologyID of the artifact to delete. * @return True if the artifact was deleted and false otherwise. */ boolean deleteArtifact(InferredOWLOntologyID ontologyId) throws PoddClientException; /** * Performs a CONSTRUCT or DESCRIBE SPARQL query on the given artifact. * * @param queryString * The CONSTRUCT or DESCRIBE SPARQL query on the given artifact. * @param artifacts * The PODD artifacts to perform the query on. * @return A {@link Model} containing the results of the SPARQL query. * @throws PoddClientException * If an error occurred. */ Model doSPARQL(String queryString, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; /** * Submits a request to the PODD Get Artifact service to download the artifact identified by the * given {@link InferredOWLOntologyID}, optionally including a version IRI if it is specifically * known. * <p> * If the version is not currently available, the latest version will be returned. * * @param artifactId * The {@link InferredOWLOntologyID} of the artifact to be downloaded, including * version as necessary to fetch old versions. * @return A model containing the RDF statements * @throws PoddClientException * If the artifact could not be downloaded for any reason */ Model downloadArtifact(InferredOWLOntologyID artifactId) throws PoddClientException; /** * Submits a request to the PODD Get Artifact service to download the artifact identified by the * given {@link InferredOWLOntologyID}, optionally including a version IRI if it is specifically * known. * <p> * If the version is not currently available, the latest version will be returned. * * @param artifactId * The {@link InferredOWLOntologyID} of the artifact to be downloaded, including * version as necessary to fetch old versions. * @param outputStream * The {@link OutputStream} to download the artifact to. * @param format * The format of the RDF information to be downloaded to the output stream. * @throws PoddClientException * If the artifact could not be downloaded for any reason */ void downloadArtifact(InferredOWLOntologyID artifactId, OutputStream outputStream, RDFFormat format) throws PoddClientException; /** * Returns RDF statements containing all of the directly linked statements from the URI. * * @param object * The URI of the object to search for. Must not be null. * @param artifacts * An optional list of artifacts which are to be searched. * @return A {@link Model} containing the RDF statements which describe the matching object. * @throws PoddClientException * If there is an exception while executing the query. */ Model getObjectByURI(URI object, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; /** * Returns RDF statements containing the types and labels for all objects in the given artifacts * with the given types. If there are no artifacts specified then all accessible artifacts will * be searched. The type is the fully inferred type for the object, not just its concrete types. * * @param type * The URI with the RDF Type to search for. Must not be null. * @param artifacts * An optional list of artifacts which are to be searched. * @return A {@link Model} containing the RDF statements which describe the matching objects. * @throws PoddClientException * If there is an exception while executing the query. */ Model getObjectsByType(URI type, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; /** * Returns RDF statements containing the types and labels for all objects in the given artifacts * with the given types linked to from the given parent with the given predicate. If there are * no artifacts specified then all accessible artifacts will be searched. The type is the fully * inferred type for the object, not just its concrete types, and the parentPredicate may be a * super-property of the concrete property that was used. * * @param type * The URI with the RDF Type to search for. Must not be null. * @param labelPrefix * The string which must start the {@link RDFS#LABEL} for the object for it to be * matched. * @param artifacts * An optional list of artifacts which are to be searched. * @return A {@link Model} containing the RDF statements which describe the matching objects. * @throws PoddClientException * If there is an exception while executing the query. */ Model getObjectsByTypeAndParent(URI parent, URI parentPredicate, URI type, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; /** * Returns RDF statements containing the types and labels for all objects in the given artifacts * with the given types, whose labels start with the given prefix. If there are no artifacts * specified then all accessible artifacts will be searched. The type is the fully inferred type * for the object, not just its concrete types. * * @param type * The URI with the RDF Type to search for. Must not be null. * @param labelPrefix * The string which must start the {@link RDFS#LABEL} for the object for it to be * matched. * @param artifacts * An optional list of artifacts which are to be searched. * @return A {@link Model} containing the RDF statements which describe the matching objects. * @throws PoddClientException * If there is an exception while executing the query. */ Model getObjectsByTypeAndPrefix(URI type, String labelPrefix, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; String getPoddServerUrl(); /** * * @param userIdentifier * The user identifier to fetch details for, or null to fetch the current user * details. * @return A {@link PoddUser} object containing the relevant details for the user. * @throws PoddClientException * If the user is not accessible, including if the user does not exist. */ PoddUser getUserDetails(String userIdentifier) throws PoddClientException; /** * Returns the current login status. * * @return True if the client was logged in after the last request, and false otherwise. */ boolean isLoggedIn(); /** * Lists the artifacts that are accessible and returns the details as a {@link Model}. * * @param published * If true, requests are made for published artifacts. If this is false, unpublished * must NOT be false. * @param unpublished * If true, requests are made for the unpublished artifacts accessible to the current * user. If this is false, published must NOT be false. * @return A Model containing RDF statements describing the artifact. * @throws PoddClientException * If an error occurred. */ Model listArtifacts(boolean published, boolean unpublished) throws PoddClientException; /** * * @return A list of Strings identifying the possible values for the repository alias in calls * to {@link #attachFileReference(IRI, String, String)}. */ List<String> listDataReferenceRepositories() throws PoddClientException; /** * * @return A map of the {@link InferredOWLOntologyID}s to top object labels, identifying the * artifacts that the user has access to which are published. This may include artifacts * that the user cannot modify or fork. */ Set<PoddArtifact> listPublishedArtifacts() throws PoddClientException; /** * List the roles that have been assigned to the given artifact. * * @param artifactId * The {@link InferredOWLOntologyID} identifying an artifact to fetch roles for. * * @return A map of {@link RestletUtilRole}s identifying PODD roles attached to the given * artifact to users who have each role. * @throws PoddClientException */ Map<RestletUtilRole, Collection<String>> listRoles(InferredOWLOntologyID artifactId) throws PoddClientException; /** * List the roles that have been assigned to the given user, or the currently logged in user if * the user is not specified. * * @param userIdentifier * If not null, specifies a specific user to request information about. * * @return A map of {@link RestletUtilRole}s identifying roles that have been given to the user, * optionally to artifacts that the role maps to for this user. * @throws PoddClientException */ Map<RestletUtilRole, Collection<URI>> listRoles(String userIdentifier) throws PoddClientException; /** * * @return A map of the {@link InferredOWLOntologyID}s to labels, identifying the artifacts that * the user has access to which are unpublished. */ Set<PoddArtifact> listUnpublishedArtifacts() throws PoddClientException; /** * * @return A list of the current users registered with the system, masked by the abilities of * the current user to view each users existence. If the current user is a repository * administrator they should be able to view all users. Some other roles may only be * able to see some other users. */ List<PoddUser> listUsers() throws PoddClientException; /** * Submits a request to the PODD Login service to login the user with the given username and * password. * <p> * Once the user is logged in, future queries using this client, prior to calling the logout * method, will be authenticated as the given user, barring any session timeouts that may occur. * <p> * If the given user is already logged in, this method may return true immediately without * reauthentication. * * @param username * The username to submit to the login service. * @param password * A character array containing the password to submit to the login service. * @return True if the user was successfully logged in and false otherwise. */ boolean login(String username, String password) throws PoddClientException; /** * Submits a request to the PODD Logout service to logout the user and close the session. * * @return True if the user was successfully logged out and false otherwise. */ boolean logout() throws PoddClientException; /** * Submits a request to the PODD Publish Artifact service to publish an artifact that was * previously unpublished. * <p> * If the given ontologyId contains a version IRI and the version is out of date, a * PoddClientException may be thrown if the server refuses to complete the operation due to the * version being out of date. In these cases the ontology would need to be manually merged, and * the publish would need to be attempted again. * * @param ontologyId * The {@link InferredOWLOntologyID} of the unpublished artifact that is to be * published. * @return The {@link InferredOWLOntologyID} of the artifact that was published. Artifacts may * be given a different IRI after they are published, to distinguish them from the * previously unpublished artifact. */ InferredOWLOntologyID publishArtifact(InferredOWLOntologyID ontologyId) throws PoddClientException; /** * Removes the given role for the given user to the given artifact. * * @param userIdentifier * @param role * @param artifact * @throws PoddClientException * If there is an error removing the role for the given user. */ void removeRole(String userIdentifier, RestletUtilRole role, InferredOWLOntologyID artifact) throws PoddClientException; void setPoddServerUrl(String serverUrl); /** * Submits a request to the PODD Unpublish Artifact service to unpublish an artifact that was * previously published. * <p> * If the given ontologyId contains a version IRI and the version is out of date, a * PoddClientException will be thrown, as the published artifact must have an accurate version * to ensure consistency. To avoid this, the operation may be attempted omitting the version * IRI. * * @param ontologyId * @return The {@link InferredOWLOntologyID} of the artifact after it has been unpublished. * Artifacts may be given a different IRI after they unpublished, to distinguish them * from the previously available artifact. */ InferredOWLOntologyID unpublishArtifact(InferredOWLOntologyID ontologyId) throws PoddClientException; /** * Submits a request to the PODD Edit Artifact service to update the entire artifact, replacing * the existing content with the content in the given {@link InputStream}. * <p> * If the given ontologyId contains a version IRI and the version is out of date, a * PoddClientException may be thrown if the server refuses to complete the operation due to the * version being out of date. In these cases the ontology would need to be manually merged, and * the update would need to be attempted again. * * @param ontologyId * The OWLOntologyID of the Artifact to update. * @param format * The format of the RDF triples in the given InputStream. * @param fullInputStream * The full set of RDF triples serialised into the InputStream in the given format * that will be used to update the given artifact. * @return An {@link InferredOWLOntologyID} object containing the details of the updated * artifact. */ InferredOWLOntologyID updateArtifact(InferredOWLOntologyID ontologyId, InputStream fullInputStream, RDFFormat format) throws PoddClientException; /** * Submits a request to the PODD Load Artifact service. * * @param input * The {@link InputStream} containing the artifact to load. * @param format * The format of the RDF triples in the given InputStream. * @return An {@link InferredOWLOntologyID} object containing the details of the loaded * artifact. The {@link InferredOWLOntologyID#getOntologyIRI()} method can be used to * get the artifact IRI for future requests, while the * {@link InferredOWLOntologyID#getVersionIRI()} method can be used to get the version * IRI to determine if there have been changes to the ontology in future. */ InferredOWLOntologyID uploadNewArtifact(InputStream input, RDFFormat format) throws PoddClientException; InferredOWLOntologyID uploadNewArtifact(InputStream input, RDFFormat format, DanglingObjectPolicy danglingObjectPolicy, DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws PoddClientException; /** * Submits a request to the PODD Load Artifact service. * * @param model * The {@link Model} containing the artifact to load. * @return An {@link InferredOWLOntologyID} object containing the details of the loaded * artifact. The {@link InferredOWLOntologyID#getOntologyIRI()} method can be used to * get the artifact IRI for future requests, while the * {@link InferredOWLOntologyID#getVersionIRI()} method can be used to get the version * IRI to determine if there have been changes to the ontology in future. */ InferredOWLOntologyID uploadNewArtifact(Model model) throws PoddClientException; Model getObjectsByTypePredicateAndPrefix(URI type, URI predicate, String labelPrefix, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; /** * Try to automatically login using the properties defined in poddclient.properties. * * @return True if the login was successful and false if it was unsuccessful. * @throws PoddClientException * If there was an exception accessing PODD. */ boolean autologin() throws PoddClientException; Model getObjectsByTypeAndBarcode(URI type, String barcode, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; Model getObjectsByBarcode(String barcode, Collection<InferredOWLOntologyID> artifacts) throws PoddClientException; }
package replicant; import arez.Arez; import arez.ArezTestUtil; import arez.Disposable; import arez.Observer; import arez.ObserverError; import arez.Procedure; import arez.SafeFunction; import arez.SafeProcedure; import elemental2.dom.DomGlobal; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.braincheck.BrainCheckTestUtil; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import static org.testng.Assert.*; public abstract class AbstractReplicantTest { private final ArrayList<String> _observerErrors = new ArrayList<>(); private boolean _ignoreObserverErrors; private boolean _printObserverErrors; @BeforeMethod protected void beforeTest() throws Exception { BrainCheckTestUtil.resetConfig( false ); ArezTestUtil.resetConfig( false ); ReplicantTestUtil.resetConfig( false ); getProxyLogger().setLogger( new TestLogger() ); setIgnoreObserverErrors( false ); setPrintObserverErrors( true ); _observerErrors.clear(); Arez.context().addObserverErrorHandler( this::onObserverError ); DomGlobal.window = null; } @Nonnull protected final Disposable pauseScheduler() { return Arez.context().pauseScheduler(); } final void autorun( @Nonnull final Procedure procedure ) { Arez.context().autorun( procedure ); } protected final void safeAction( @Nonnull final SafeProcedure action ) { Arez.context().safeAction( action ); } protected final <T> T safeAction( @Nonnull final SafeFunction<T> action ) { return Arez.context().safeAction( action ); } @Nonnull final Entity findOrCreateEntity( @Nonnull final Class<?> type, final int id ) { return safeAction( () -> Replicant .context() .getEntityService() .findOrCreateEntity( Replicant.areNamesEnabled() ? type.getSimpleName() + "/" + id : null, type, id ) ); } @Nonnull protected final Subscription createSubscription( @Nonnull final ChannelAddress address, @Nullable final Object filter, final boolean explicitSubscription ) { return safeAction( () -> Replicant.context() .getSubscriptionService() .createSubscription( address, filter, explicitSubscription ) ); } @AfterMethod protected void afterTest() throws Exception { BrainCheckTestUtil.resetConfig( true ); ArezTestUtil.resetConfig( true ); ReplicantTestUtil.resetConfig( true ); if ( !_ignoreObserverErrors && !_observerErrors.isEmpty() ) { fail( "Unexpected Observer Errors: " + _observerErrors.stream().collect( Collectors.joining( "\n" ) ) ); } } @Nonnull final TestLogger getTestLogger() { return (TestLogger) getProxyLogger().getLogger(); } @Nonnull private ReplicantLogger.ProxyLogger getProxyLogger() { return (ReplicantLogger.ProxyLogger) ReplicantLogger.getLogger(); } final void setIgnoreObserverErrors( final boolean ignoreObserverErrors ) { _ignoreObserverErrors = ignoreObserverErrors; } final void setPrintObserverErrors( final boolean printObserverErrors ) { _printObserverErrors = printObserverErrors; } private void onObserverError( @Nonnull final Observer observer, @Nonnull final ObserverError error, @Nullable final Throwable throwable ) { if ( !_ignoreObserverErrors ) { final String message = "Observer: " + observer.getName() + " Error: " + error + " " + throwable; _observerErrors.add( message ); if ( _printObserverErrors ) { System.out.println( message ); } } } @SuppressWarnings( "NonJREEmulationClassesInClientCode" ) @Nonnull protected final Field toField( @Nonnull final Class<?> type, @Nonnull final String fieldName ) { Class<?> clazz = type; while ( null != clazz && Object.class != clazz ) { try { final Field field = clazz.getDeclaredField( fieldName ); field.setAccessible( true ); return field; } catch ( final Throwable t ) { clazz = clazz.getSuperclass(); } } fail(); return null; } @SuppressWarnings( "SameParameterValue" ) final Object getFieldValue( @Nonnull final Object object, @Nonnull final String fieldName ) { try { return toField( object.getClass(), fieldName ).get( object ); } catch ( final Throwable t ) { throw new AssertionError( t ); } } @Nonnull final TestSpyEventHandler registerTestSpyEventHandler() { final TestSpyEventHandler handler = new TestSpyEventHandler(); Replicant.context().getSpy().addSpyEventHandler( handler ); return handler; } @Nonnull final SystemSchema newSchema() { return newSchema( ValueUtil.randomInt() ); } @Nonnull final SystemSchema newSchema( final int schemaId ) { final ChannelSchema[] channels = new ChannelSchema[ 0 ]; final EntitySchema[] entities = new EntitySchema[ 0 ]; return new SystemSchema( schemaId, ValueUtil.randomString(), channels, entities ); } }
package org.jetel.database; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.sql.Connection; import java.sql.Driver; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.jetel.util.ComponentXMLAttributes; import org.jetel.util.PropertyRefResolver; import org.w3c.dom.NamedNodeMap; public class DBConnection { String dbDriverName; String dbURL; Driver dbDriver; Connection dbConnection; Properties config; boolean threadSafeConnections; private Map openedConnections; public final static String JDBC_DRIVER_LIBRARY_NAME = "driverLibrary"; public final static String TRANSACTION_ISOLATION_PROPERTY_NAME="transactionIsolation"; public static final String XML_DBURL_ATTRIBUTE = "dbURL"; public static final String XML_DBDRIVER_ATTRIBUTE = "dbDriver"; public static final String XML_DBCONFIG_ATTRIBUTE = "dbConfig"; public static final String XML_PASSWORD_ATTRIBUTE = "password"; public static final String XML_USER_ATTRIBUTE = "user"; public static final String XML_THREAD_SAFE_CONNECTIONS="threadSafeConnection"; // not yet used by component public static final String XML_NAME_ATTRIBUTE = "name"; /** * Constructor for the DBConnection object * * @param dbDriver Description of the Parameter * @param dbURL Description of the Parameter * @param user Description of the Parameter * @param password Description of the Parameter */ public DBConnection(String dbDriver, String dbURL, String user, String password) { this.config = new Properties(); if (user!=null) config.setProperty(XML_USER_ATTRIBUTE, user); if (password!=null) config.setProperty(XML_PASSWORD_ATTRIBUTE, password); this.dbDriverName = dbDriver; this.dbURL = dbURL; this.threadSafeConnections=false; this.openedConnections=new HashMap(); } /** * Constructor for the DBConnection object (not used in engine yet) * * @param configFilename properties filename containing definition of driver, dbURL, username, password */ public DBConnection(String configFilename) { this.config = new Properties(); this.openedConnections=new HashMap(); try { InputStream stream = new BufferedInputStream(new FileInputStream(configFilename)); this.config.load(stream); stream.close(); this.dbDriverName = config.getProperty(XML_DBDRIVER_ATTRIBUTE); this.dbURL = config.getProperty(XML_DBURL_ATTRIBUTE); this.threadSafeConnections=Boolean.parseBoolean(config.getProperty(XML_THREAD_SAFE_CONNECTIONS,"false")); } catch (Exception ex) { throw new RuntimeException(ex); } } public DBConnection(Properties configProperties) { this.openedConnections=new HashMap(); this.dbDriverName = (String)configProperties.remove(XML_DBDRIVER_ATTRIBUTE); this.config = new Properties(); this.config.putAll(configProperties); this.dbURL = (String)this.config.remove(XML_DBURL_ATTRIBUTE); this.threadSafeConnections=Boolean.parseBoolean(configProperties.getProperty(XML_THREAD_SAFE_CONNECTIONS,"false")); } /** * Method which connects to database and if successful, sets various * connection parameters. If as a property "transactionIsolation" is defined, then * following options are allowed:<br> * <ul> * <li>READ_UNCOMMITTED</li> * <li>READ_COMMITTED</li> * <li>REPEATABLE_READ</li> * <li>SERIALIZABLE</li> * </ul> * * @see java.sql.Connection#setTransactionIsolation(int) */ public void connect() { if (dbDriver==null){ try { dbDriver = (Driver) Class.forName(dbDriverName).newInstance(); } catch (ClassNotFoundException ex) { // let's try to load in any additional .jar library (if specified) String jdbcDriverLibrary = config .getProperty(JDBC_DRIVER_LIBRARY_NAME); if (jdbcDriverLibrary != null) { String urlString = "file:" + jdbcDriverLibrary; URL[] myURLs; try { myURLs = new URL[] { new URL(urlString) }; URLClassLoader classLoader = new URLClassLoader(myURLs); dbDriver = (Driver) Class.forName(dbDriverName, true, classLoader).newInstance(); } catch (MalformedURLException ex1) { throw new RuntimeException("Malformed URL: " + ex1.getMessage()); } catch (ClassNotFoundException ex1) { throw new RuntimeException("Can not find class: " + ex1); } catch (Exception ex1) { throw new RuntimeException("General exception: " + ex1.getMessage()); } } else { throw new RuntimeException("Can't load DB driver :" + ex.getMessage()); } } catch (Exception ex) { throw new RuntimeException("Can't load DB driver :" + ex.getMessage()); } } try { dbConnection = dbDriver.connect(dbURL, this.config); } catch (SQLException ex) { throw new RuntimeException("Can't connect to DB :" + ex.getMessage()); } if (dbConnection == null) { throw new RuntimeException( "Not suitable driver for specified DB URL : " + dbDriver + " ; " + dbURL); } // try to set Transaction isolation level, it it was specified if (config.containsKey(TRANSACTION_ISOLATION_PROPERTY_NAME)) { int trLevel; String isolationLevel = config .getProperty(TRANSACTION_ISOLATION_PROPERTY_NAME); if (isolationLevel.equalsIgnoreCase("READ_UNCOMMITTED")) { trLevel = Connection.TRANSACTION_READ_UNCOMMITTED; } else if (isolationLevel.equalsIgnoreCase("READ_COMMITTED")) { trLevel = Connection.TRANSACTION_READ_COMMITTED; } else if (isolationLevel.equalsIgnoreCase("REPEATABLE_READ")) { trLevel = Connection.TRANSACTION_REPEATABLE_READ; } else if (isolationLevel.equalsIgnoreCase("SERIALIZABLE")) { trLevel = Connection.TRANSACTION_SERIALIZABLE; } else { trLevel = Connection.TRANSACTION_NONE; } try { dbConnection.setTransactionIsolation(trLevel); } catch (SQLException ex) { // we do nothing, if anything goes wrong, we just // leave whatever was the default } } } /** * Description of the Method * * @exception SQLException Description of the Exception */ public void close() throws SQLException { for(Iterator i=openedConnections.entrySet().iterator();i.hasNext();){ ((Connection)i.next()).close(); } } /** * Gets the connection attribute of the DBConnection object. If threadSafe option * is set, then each call will result in new connection being created. * * @return The database connection (JDBC) */ public Connection getConnection() { Connection con=null; if (threadSafeConnections){ con=(Connection)openedConnections.get(Thread.currentThread()); if(con==null){ connect(); con=dbConnection; openedConnections.put(Thread.currentThread(),con); } }else{ try{ if (dbConnection.isClosed()){ connect(); } }catch(SQLException ex){ throw new RuntimeException( "Can't establish or reuse existing connection : " + dbDriver + " ; " + dbURL); } con=dbConnection; } return con; } /** * Creates new statement with default parameters and returns it * * @return The new statement * @exception SQLException Description of the Exception */ public Statement getStatement() throws SQLException { return getConnection().createStatement(); } /** * Creates new statement with specified parameters * * @param type one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY, * ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE * @param concurrency one of the following ResultSet constants: ResultSet.CONCUR_READ_ONLY or * ResultSet.CONCUR_UPDATABLE * @param holdability one of the following ResultSet constants: ResultSet.HOLD_CURSORS_OVER_COMMIT * or ResultSet.CLOSE_CURSORS_AT_COMMIT * @return The new statement * @throws SQLException */ public Statement getStatement(int type,int concurrency,int holdability) throws SQLException { return getConnection().createStatement(type,concurrency,holdability); } /** * Creates new prepared statement with default parameters * * @param sql SQL/DML query * @return Description of the Return Value * @exception SQLException Description of the Exception */ public PreparedStatement prepareStatement(String sql) throws SQLException { return getConnection().prepareStatement(sql); } /** * Creates new prepared statement with specified parameters * * @param sql SQL/DML query * @param resultSetType * @param resultSetConcurrency * @param resultSetHoldability * @return * @throws SQLException */ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return getConnection().prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability); } /** * Sets the property attribute of the DBConnection object * * @param name The new property value * @param value The new property value */ public void setProperty(String name, String value) { config.setProperty(name, value); } /** * Sets the property attribute of the DBConnection object * * @param properties The new property value */ public void setProperty(Properties properties) { config.putAll(properties); } /** * Gets the property attribute of the DBConnection object * * @param name Description of the Parameter * @return The property value */ public String getProperty(String name) { return config.getProperty(name); } /** * Description of the Method * * @param nodeXML Description of the Parameter * @return Description of the Return Value */ public static DBConnection fromXML(org.w3c.dom.Node nodeXML) { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML); NamedNodeMap attributes = nodeXML.getAttributes(); DBConnection con; // for resolving reference in additional parameters // this should be changed in the future when ComponentXMLAttributes // is enhanced to support iterating through attributes PropertyRefResolver refResolver=new PropertyRefResolver(); try { // do we have dbConfig parameter specified ?? if (xattribs.exists(XML_DBCONFIG_ATTRIBUTE)) { return new DBConnection(xattribs.getString(XML_DBCONFIG_ATTRIBUTE)); } else { String dbDriver = xattribs.getString(XML_DBDRIVER_ATTRIBUTE); String dbURL = xattribs.getString(XML_DBURL_ATTRIBUTE); String user = ""; String password = ""; con = new DBConnection(dbDriver, dbURL, user, password); //check thread safe option if (xattribs.exists(XML_THREAD_SAFE_CONNECTIONS)){ con.setThreadSafeConnections(xattribs.getBoolean(XML_THREAD_SAFE_CONNECTIONS)); } // assign rest of attributes/parameters to connection properties so // it can be retrieved by DB JDBC driver for (int i = 0; i < attributes.getLength(); i++) { con.setProperty(attributes.item(i).getNodeName(), refResolver.resolveRef(attributes.item(i).getNodeValue())); } return con; } } catch (Exception ex) { System.err.println(ex.getMessage()); return null; } } public void saveConfiguration(OutputStream outStream) throws IOException { Properties propsToStore = new Properties(); propsToStore.putAll(config); propsToStore.put(XML_DBDRIVER_ATTRIBUTE,this.dbDriverName); propsToStore.put(XML_DBURL_ATTRIBUTE,this.dbURL); propsToStore.put(XML_THREAD_SAFE_CONNECTIONS,new Boolean(this.threadSafeConnections)); propsToStore.store(outStream,null); } /** * Description of the Method * * @return Description of the Return Value */ public String toString() { return dbURL; } /** * @return Returns the threadSafeConnections. */ public boolean isThreadSafeConnections() { return threadSafeConnections; } /** * @param threadSafeConnections The threadSafeConnections to set. */ public void setThreadSafeConnections(boolean threadSafeConnections) { this.threadSafeConnections = threadSafeConnections; } }
package com.codeandstrings.niohttp.sessions; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import com.codeandstrings.niohttp.data.Parameters; import com.codeandstrings.niohttp.exceptions.http.HttpException; import com.codeandstrings.niohttp.exceptions.http.RequestEntityTooLargeException; import com.codeandstrings.niohttp.exceptions.tcp.CloseConnectionException; import com.codeandstrings.niohttp.request.Request; import com.codeandstrings.niohttp.request.RequestBodyFactory; import com.codeandstrings.niohttp.request.RequestHeaderFactory; import com.codeandstrings.niohttp.response.ResponseContent; class HttpSession$Line { public final String line; public final int start; public final int nextStart; public HttpSession$Line(String line, int start, int nextStart) { this.line = line; this.start = start; this.nextStart = nextStart; } @Override public String toString() { return "HttpSession$Line [line=" + line + ", start=" + start + ", nextStart=" + nextStart + "]"; } } public class HttpSession extends Session { /* Object Variables */ private byte[] requestHeaderData; private int requestHeaderMarker; private ArrayList<HttpSession$Line> requestHeaderLines; private int lastHeaderByteLocation; private ByteBuffer readBuffer; private RequestHeaderFactory headerFactory; private boolean bodyReadBegun; private RequestBodyFactory bodyFactory; /* Write Queue */ private ByteBuffer writeBuffer; private boolean writeBufferLastPacket; private Request writeRequest; /** * Constructor for a new HTTP session. * * @param channel The TCP this session is operating against * @param selector The NIO selector this channel interacts with. */ public HttpSession(SocketChannel channel, Selector selector, Parameters parameters) { super(channel, selector, parameters); this.readBuffer = ByteBuffer.allocate(128); this.resetHeaderReads(); } @Override public void resetHeaderReads() { this.requestHeaderData = new byte[maxRequestSize]; this.requestHeaderMarker = 0; this.requestHeaderLines = new ArrayList<HttpSession$Line>(); this.lastHeaderByteLocation = 0; this.headerFactory = new RequestHeaderFactory(); this.bodyReadBegun = false; this.bodyFactory = new RequestBodyFactory(); this.readBuffer.clear(); } private Request generateAndHandleRequest() throws IOException { InetSocketAddress remote = (InetSocketAddress) this.channel .getRemoteAddress(); Request r = Request.generateRequest(this.getSessionId(), this.getNextRequestId(), remote.getHostString(), remote.getPort(), headerFactory.build(), bodyFactory.build(), this.parameters); return r; } private void copyExistingBytesToBody(int startPosition) { this.bodyFactory.addBytes(this.requestHeaderData, startPosition, this.requestHeaderMarker - startPosition); } private Request storeAndReturnRequest(Request request) { if (request != null) { this.requestQueue.add(request); } return request; } private Request analyzeForHeader() throws HttpException, IOException { // likely won't ever happen anyways, but just in case // don't do this - we're already in body mode if (this.bodyReadBegun) { return null; } // there is nothing to analyze if (this.requestHeaderLines.size() == 0) return null; // resetHeaderReads our factory this.headerFactory.reset(); // walk the received header lines. for (HttpSession$Line sessionLine : this.requestHeaderLines) { headerFactory.addLine(sessionLine.line); if (headerFactory.shouldBuildRequestHeader()) { int requestBodySize = headerFactory.shouldExpectBody(); if (requestBodySize > this.parameters.getMaximumPostSize()) { throw new RequestEntityTooLargeException(requestBodySize); } else if (requestBodySize != -1) { // we have a request body; attempt to grab it from // existing request information; otherwise we'll just defer // off to the next read event to try to finish the request. this.bodyFactory.resize(requestBodySize); this.bodyReadBegun = true; this.copyExistingBytesToBody(sessionLine.nextStart); if (this.bodyFactory.isFull()) { return this.storeAndReturnRequest(this.generateAndHandleRequest()); } } else { // there is no request body; go return this.storeAndReturnRequest(this.generateAndHandleRequest()); } } } // if we're here, we don't have enough of a request yet return null; } private void extractLines() { for (int i = this.lastHeaderByteLocation; i < this.requestHeaderMarker; i++) { if (i == 0) { continue; } if ((this.requestHeaderData[i] == 10) && (this.requestHeaderData[i - 1] == 13)) { String line = null; if ((i - this.lastHeaderByteLocation - 1) == 0) { line = new String(); } else { line = new String(this.requestHeaderData, this.lastHeaderByteLocation, i - this.lastHeaderByteLocation - 1); } this.requestHeaderLines.add(new HttpSession$Line(line, this.lastHeaderByteLocation, i + 1)); this.lastHeaderByteLocation = (i + 1); } } } private final void clearWriteOperations() { if (this.writeBufferLastPacket) { this.writeRequest = null; this.writeBufferLastPacket = false; } this.writeBuffer = null; } private final boolean hasWriteEventQueued() { if (this.writeBuffer != null) { if (this.writeBuffer.hasRemaining()) { return true; } else { return false; } } else { return false; } } private final void socketResponseConcluded() throws CloseConnectionException { boolean shouldClose = true; if (this.writeBufferLastPacket) { if (this.writeRequest != null && this.writeRequest.isKeepAlive()) { shouldClose = false; } } else { shouldClose = false; } this.clearWriteOperations(); if (shouldClose) { throw new CloseConnectionException(); } } private final void socketWriteEventExecute() throws IOException, CloseConnectionException { this.channel.write(this.writeBuffer); if (!this.writeBuffer.hasRemaining()) { this.socketResponseConcluded(); } } private final void covertResponseContentToQueue(ResponseContent responseContent) { this.writeBuffer = ByteBuffer.wrap(responseContent.getBuffer()); this.writeBufferLastPacket = responseContent.isLastBufferForRequest(); } private final void queueNextWriteEvent() throws ClosedChannelException { if (this.contentQueue.size() == 0) { this.setSelectionRequest(false); return; } if (this.writeRequest == null) { if (this.requestQueue.size() > 0) { this.writeRequest = this.requestQueue.remove(); } } if (this.writeRequest == null) { this.covertResponseContentToQueue(this.contentQueue.remove()); return; } else { Iterator<ResponseContent> iterator = this.contentQueue.iterator(); while (iterator.hasNext()) { ResponseContent responseContent = iterator.next(); if (responseContent.getRequestId() == this.writeRequest.getRequestId()) { this.covertResponseContentToQueue(responseContent); iterator.remove(); return; } } } if (!this.hasWriteEventQueued()) { this.setSelectionRequest(false); } } @Override public void socketWriteEvent() throws IOException, CloseConnectionException { if (this.hasWriteEventQueued()) { this.socketWriteEventExecute(); } else { queueNextWriteEvent(); } } @Override public Request socketReadEvent() throws IOException, CloseConnectionException, HttpException { try { if (!this.channel.isConnected() || !this.channel.isOpen()) { return null; } int bytesRead = this.channel.read(this.readBuffer); if (bytesRead == -1) { throw new CloseConnectionException(); } else { byte[] bytes = new byte[bytesRead]; this.readBuffer.flip(); this.readBuffer.get(bytes); if (this.bodyReadBegun) { this.bodyFactory.addBytes(bytes); if (this.bodyFactory.isFull()) { return this.storeAndReturnRequest(this.generateAndHandleRequest()); } else { return null; } } else { for (int i = 0; i < bytesRead; i++) { if (this.requestHeaderMarker >= (this.maxRequestSize - 1)) { // we won't receive header blocks that are much bigger than // the maximum requst size, which is generally 8192 bytes. // Once the header has been setup the request body can // reach the maximum post in size without issue. throw new RequestEntityTooLargeException(); } this.requestHeaderData[this.requestHeaderMarker] = bytes[i]; this.requestHeaderMarker++; } // header has been ingested this.extractLines(); // return the request if one is there return this.analyzeForHeader(); } } } catch (IOException e) { throw new CloseConnectionException(e); } } }
package org.nick.wwwjdic; import java.util.List; import org.nick.wwwjdic.utils.Analytics; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.text.ClipboardManager; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class ExamplesResultListFragment extends ResultListFragmentBase<ExampleSentence> { private static final String TAG = ExamplesResultListFragment.class .getSimpleName(); public static String EXTRA_EXAMPLES_BACKDOOR_SEARCH = "org.nick.wwwjdic.EXAMPLES_BACKDOOR_SEARCH"; private static final String EXAMPLE_SEARCH_QUERY_STR = "?11"; private static final int MENU_ITEM_BREAK_DOWN = 0; private static final int MENU_ITEM_LOOKUP_ALL_KANJI = 1; private static final int MENU_ITEM_COPY_JP = 2; private static final int MENU_ITEM_COPY_ENG = 3; static class ExampleSentenceAdapter extends BaseAdapter { private final Context context; private final List<ExampleSentence> entries; private final String queryString; public ExampleSentenceAdapter(Context context, List<ExampleSentence> entries, String queryString) { this.context = context; this.entries = entries; this.queryString = queryString; } public int getCount() { return entries == null ? 0 : entries.size(); } public Object getItem(int position) { return entries == null ? null : entries.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ExampleSentence entry = entries.get(position); if (convertView == null) { convertView = new ExampleSentenceView(context); } ((ExampleSentenceView) convertView).populate(entry, queryString); return convertView; } static class ExampleSentenceView extends LinearLayout { private static final int HILIGHT_COLOR = 0xff427ad7; private TextView japaneseSentenceText; private TextView englishSentenceText; ExampleSentenceView(Context context) { super(context); LayoutInflater inflater = LayoutInflater.from(context); inflater.inflate(R.layout.example_sentence_item, this); japaneseSentenceText = (TextView) findViewById(R.id.japaneseSentenceText); englishSentenceText = (TextView) findViewById(R.id.englishSentenceText); } void populate(ExampleSentence sentence, String queryString) { SpannableString english = markQueryString( sentence.getEnglish(), queryString, true); SpannableString japanese = null; if (sentence.getMatches().isEmpty()) { japanese = markQueryString(sentence.getJapanese(), queryString, false); } else { japanese = new SpannableString(sentence.getJapanese()); for (String match : sentence.getMatches()) { markQueryString(japanese, sentence.getJapanese(), match, false); } } japaneseSentenceText.setText(japanese); englishSentenceText.setText(english); } private SpannableString markQueryString(String sentenceStr, String queryString, boolean italicize) { SpannableString result = new SpannableString(sentenceStr); markQueryString(result, sentenceStr, queryString, italicize); return result; } private void markQueryString(SpannableString result, String sentenceStr, String queryString, boolean italicize) { String sentenceUpper = sentenceStr.toUpperCase(); String queryUpper = queryString.toUpperCase(); int idx = sentenceUpper.indexOf(queryUpper); while (idx != -1) { result.setSpan(new ForegroundColorSpan(HILIGHT_COLOR), idx, idx + queryString.length(), 0); if (italicize) { result.setSpan(new StyleSpan(Typeface.ITALIC), idx, idx + queryString.length(), 0); } int startIdx = idx + queryString.length() + 1; if (startIdx <= sentenceStr.length() - 1) { idx = sentenceUpper.indexOf(queryUpper, idx + 1); } else { break; } } } } } private List<ExampleSentence> sentences; private ClipboardManager clipboardManager; private boolean dualPane; private int currentCheckPosition = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); clipboardManager = (ClipboardManager) getActivity().getSystemService( Context.CLIPBOARD_SERVICE); getListView().setOnCreateContextMenuListener(this); View detailsFrame = getActivity().findViewById(R.id.details); dualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE; extractSearchCriteria(); boolean useBackdoor = getActivity().getIntent().getBooleanExtra( EXTRA_EXAMPLES_BACKDOOR_SEARCH, false); SearchTask<ExampleSentence> searchTask = null; if (useBackdoor) { searchTask = new ExampleSearchTaskBackdoor(getWwwjdicUrl(), getHttpTimeoutSeconds(), this, criteria, WwwjdicPreferences.isReturnRandomExamples(getActivity())); } else { searchTask = new ExampleSearchTask(getWwwjdicUrl() + EXAMPLE_SEARCH_QUERY_STR, getHttpTimeoutSeconds(), this, criteria, criteria.getNumMaxResults()); } submitSearchTask(searchTask); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.search_results_fragment, container, false); return v; } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { menu.add(0, MENU_ITEM_BREAK_DOWN, 0, R.string.break_down_jap); menu.add(0, MENU_ITEM_LOOKUP_ALL_KANJI, 1, R.string.look_up_all_kanji); menu.add(0, MENU_ITEM_COPY_JP, 2, R.string.copy_jp); menu.add(0, MENU_ITEM_COPY_ENG, 3, R.string.copy_eng); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } switch (item.getItemId()) { case MENU_ITEM_BREAK_DOWN: breakDown(getCurrentSentence(info.position), info.position); return true; case MENU_ITEM_LOOKUP_ALL_KANJI: lookupAllKanji(info.id); return true; case MENU_ITEM_COPY_JP: copyJapanese(info.id); return true; case MENU_ITEM_COPY_ENG: copyEnglish(info.id); return true; } return false; } @Override public void onListItemClick(ListView l, View v, int position, long id) { ExampleSentence sentence = getCurrentSentence(id); breakDown(sentence, position); } private void breakDown(ExampleSentence sentence, int index) { Analytics.event("sentenceBreakdown", getActivity()); if (dualPane) { getListView().setItemChecked(index, true); SentenceBreakdownFragment breakdown = (SentenceBreakdownFragment) getFragmentManager() .findFragmentById(R.id.details); if (breakdown == null || breakdown.getShownIndex() != index) { breakdown = SentenceBreakdownFragment.newInstance(index, sentence.getJapanese(), sentence.getEnglish()); FragmentTransaction ft = getFragmentManager() .beginTransaction(); ft.replace(R.id.details, breakdown); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } else { Intent intent = new Intent(getActivity(), SentenceBreakdown.class); intent.putExtra(SentenceBreakdown.EXTRA_SENTENCE, sentence.getJapanese()); intent.putExtra(SentenceBreakdown.EXTRA_SENTENCE_TRANSLATION, sentence.getEnglish()); startActivity(intent); } } private void copyEnglish(long id) { ExampleSentence sentence = getCurrentSentence(id); clipboardManager.setText(sentence.getEnglish()); } private ExampleSentence getCurrentSentence(long id) { return sentences.get((int) id); } private void copyJapanese(long id) { ExampleSentence sentence = getCurrentSentence(id); clipboardManager.setText(sentence.getJapanese()); } private void lookupAllKanji(long id) { ExampleSentence sentence = getCurrentSentence(id); SearchCriteria criteria = SearchCriteria .createForKanjiOrReading(sentence.getJapanese()); Intent intent = new Intent(getActivity(), KanjiResultListView.class); intent.putExtra(Constants.CRITERIA_KEY, criteria); startActivity(intent); } @Override public void setResult(final List<ExampleSentence> result) { guiThread.post(new Runnable() { public void run() { sentences = (List<ExampleSentence>) result; ExampleSentenceAdapter adapter = new ExampleSentenceAdapter( getActivity(), sentences, criteria.getQueryString()); setListAdapter(adapter); getListView().setTextFilterEnabled(true); String message = getResources() .getString(R.string.examples_for); getActivity().setTitle( String.format(message, sentences.size(), criteria.getQueryString())); if (dualPane) { getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (!sentences.isEmpty()) { breakDown(sentences.get(currentCheckPosition), currentCheckPosition); } } dismissProgressDialog(); } }); } }
package org.croudtrip.trip; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.croudtrip.R; import org.croudtrip.api.account.User; import org.croudtrip.api.trips.TripReservation; import java.util.List; public class JoinTripResultsAdapter extends RecyclerView.Adapter<JoinTripResultsAdapter.ViewHolder> { // private final Context context; private List<TripReservation> reservations; protected OnItemClickListener listener; // public static interface OnItemClickListener { public void onItemClicked(View view, int position); } /** * Provides a reference to the views for each data item. */ public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ protected TextView tvPrice; protected TextView tvDriverName; protected TextView tvDistance; protected TextView tvDuration; public ViewHolder(View view) { super(view); this.tvPrice = (TextView) view.findViewById(R.id.tv_join_trip_results_price); this.tvDriverName = (TextView) view.findViewById(R.id.tv_join_trip_results_driver_name); this.tvDistance = (TextView) view.findViewById(R.id.tv_join_trip_results_distance); this.tvDuration = (TextView) view.findViewById(R.id.tv_join_trip_results_duration); view.setOnClickListener(this); } @Override public void onClick(View view) { if (listener != null) { listener.onItemClicked(view, getPosition()); } } } // public JoinTripResultsAdapter(Context context, List<TripReservation> reservations) { this.context = context; this.reservations = reservations; } // @Override public JoinTripResultsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // Create new views (invoked by the layout manager) View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.cardview_join_trip_results, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { TripReservation reservation = reservations.get(position); // Price info String price = reservation.getTotalPriceInCents() / 100 + ","; // euros int cents = reservation.getTotalPriceInCents() % 100; if(cents == 0){ price = price + "00"; }else if(cents < 10){ price = price + "0" + cents; }else{ price = price + cents; } holder.tvPrice.setText(price + " €"); // Driver info User driver = reservation.getDriver(); holder.tvDriverName.setText(driver.getFirstName()); // Distance information long distance = reservation.getQuery().getPassengerRoute().getDistanceInMeters(); if(distance < 1000){ holder.tvDistance.setText(context.getString( R.string.join_trip_results_distance_m, distance)); }else{ distance = Math.round(distance / 1000.0); holder.tvDistance.setText(context.getString( R.string.join_trip_results_distance_km, distance)); } // Duration info long timeInMinutes = reservation.getQuery().getPassengerRoute().getDurationInSeconds() / 60; if(timeInMinutes < 60){ holder.tvDuration.setText(context.getString(R.string.join_trip_results_duration_min, timeInMinutes)); }else{ holder.tvDuration.setText(context.getString(R.string.join_trip_results_duration_hmin, timeInMinutes / 60, timeInMinutes % 60)); } } /** * Adds the given items to the adapter. * @param additionalReservations new elements to add to the adapter */ public void addElements(List<TripReservation> additionalReservations){ if(additionalReservations == null){ return; } if(reservations == null){ reservations = additionalReservations; }else{ reservations.addAll(additionalReservations); } this.notifyDataSetChanged(); } @Override public int getItemCount() { if (reservations == null) { return 0; } return reservations.size(); } public void setOnItemClickListener(final OnItemClickListener listener) { this.listener = listener; } /** * Returns the TripReservation at the specific position * @param position the position in the adapter of the item to return * @return the item at the specific position */ public TripReservation getItem(int position){ if(position < 0 || position >= reservations.size()){ return null; } return reservations.get(position); } }
package com.thoughtworks.xstream.mapper; import com.thoughtworks.xstream.converters.SingleValueConverter; public interface Mapper { /** * Place holder type used for null values. */ class Null {} /** * How a class name should be represented in its serialized form. */ String serializedClass(Class type); /** * How a serialized class representation should be mapped back to a real class. */ Class realClass(String elementName); /** * How a class member should be represented in its serialized form. */ String serializedMember(Class type, String memberName); /** * How a serialized member representation should be mapped back to a real member. */ String realMember(Class type, String serialized); /** * Whether this type is a simple immutable value (int, boolean, String, URL, etc. * Immutable types will be repeatedly written in the serialized stream, instead of using object references. */ boolean isImmutableValueType(Class type); Class defaultImplementationOf(Class type); /** * @deprecated since 1.2, use aliasForAttribute instead. */ String attributeForImplementationClass(); /** * @deprecated since 1.2, use aliasForAttribute instead. */ String attributeForClassDefiningField(); /** * @deprecated since 1.2, use aliasForAttribute instead. */ String attributeForReadResolveField(); /** * @deprecated since 1.2, use aliasForAttribute instead. */ String attributeForEnumType(); /** * Get the alias for an attrbute's name. * * @param attribute the attribute * @return the alias * @since 1.2 */ String aliasForAttribute(String attribute); /** * Get the attribut's name for an alias. * * @param alias the alias * @return the attribute's name * @since 1.2 */ String attributeForAlias(String alias); /** * Get the name of the field that acts as the default collection for an object, or return null if there is none. * * @param definedIn owning type * @param itemType item type * @param itemFieldName optional item element name */ String getFieldNameForItemTypeAndName(Class definedIn, Class itemType, String itemFieldName); Class getItemTypeForItemFieldName(Class definedIn, String itemFieldName); ImplicitCollectionMapping getImplicitCollectionDefForFieldName(Class itemType, String fieldName); /** * Determine whether a specific member should be serialized. * * @since 1.1.3 */ boolean shouldSerializeMember(Class definedIn, String fieldName); interface ImplicitCollectionMapping { String getFieldName(); String getItemFieldName(); Class getItemType(); } SingleValueConverter getConverterFromItemType(String fieldName, Class type); SingleValueConverter getConverterFromItemType(Class type); SingleValueConverter getConverterFromAttribute(String name); Mapper lookupMapperOfType(Class type); /** * Returns a single value converter to be used in a specific field. * * @param fieldName the field name * @param type the field type * @param definedIn the type which defines this field * @return a SingleValueConverter or null if there no such converter should be used for this * field. * @since upcoming */ SingleValueConverter getConverterFromItemType(String fieldName, Class type, Class definedIn); /** * Returns an alias for a single field defined in an specific type. * * @param definedIn the type where the field was defined * @param fieldName the field name * @return the alias for this field or its own name if no alias was defined * @since upcoming */ String aliasForAttribute(Class definedIn, String fieldName); /** * Returns the field name for an aliased attribute. * * @param definedIn the type where the field was defined * @param alias the alias * @return the original attribute name * @since upcoming */ String attributeForAlias(Class definedIn, String alias); /** * Returns which converter to use for an specific attribute in a type. * * @param type the field type * @param attribute the attribute name * @since upcoming */ SingleValueConverter getConverterFromAttribute(Class type, String attribute); }
package org.jetel.component; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.input.NullReader; import org.jetel.component.HttpConnector.PartWithName; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.NullRecord; import org.jetel.data.NullRecordTest; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.InputPort; import org.jetel.graph.InputPortDirect; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.test.CloverTestCase; import org.jetel.util.CTLMapping; public class HttpConnectorTest extends CloverTestCase { @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { } public void testPrepareMultipartEntitiesEmpty() { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities(null); Map<String, HttpConnectorMutlipartEntity> result = httpConnector.prepareMultipartEntities(); assertNotNull(result); } public void testPrepareMutlipartMappedByFieldNamesOnly() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity2"); HashMap<String, String> inputRecord = new HashMap<String, String>(); inputRecord.put("entity1", "ValueOfEntity1"); inputRecord.put("entity2", "ValueOfEntity2"); httpConnector.inputRecord = this.createConstDataRecord(inputRecord); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = null; // this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertEquals("ValueOfEntity2", result.get("entity2").content); } public void testPrepareMutlipartMappedByFieldEnitityContentMapped() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity2"); HashMap<String, String> inputRecord = new HashMap<String, String>(); inputRecord.put("entity1", "ValueOfEntity1"); inputRecord.put("entity2", "ValueOfEntity2"); httpConnector.inputRecord = this.createConstDataRecord(inputRecord); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = new HashMap<String, String>(); mappingFieldValues.put("entity2_Content", "ValueOfContent"); this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertEquals("ValueOfContent", result.get("entity2").content); } public void testPrepareMutlipartMappedByFieldEnitityFileMapped() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity2"); HashMap<String, String> inputRecord = new HashMap<String, String>(); inputRecord.put("entity1", "ValueOfEntity1"); inputRecord.put("entity2", "ValueOfEntity2"); httpConnector.inputRecord = this.createConstDataRecord(inputRecord); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = new HashMap<String, String>(); mappingFieldValues.put("entity2_File", "ValueOfContent"); this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertNull(result.get("entity2").content); assertEquals("ValueOfContent",result.get("entity2").file); } public void testPrepareMutlipartMappedByFieldEnitityFileAndContentMapped() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity2"); HashMap<String, String> inputRecord = new HashMap<String, String>(); inputRecord.put("entity1", "ValueOfEntity1"); inputRecord.put("entity2", "ValueOfEntity2"); httpConnector.inputRecord = this.createConstDataRecord(inputRecord); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = new HashMap<String, String>(); mappingFieldValues.put("entity2_File", "filename"); mappingFieldValues.put("entity2_Content", "ValueOfContent"); this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertEquals("ValueOfContent",result.get("entity2").content); assertEquals("filename",result.get("entity2").file); } public void testPrepareMultipartEntitiesNotMapped() throws ComponentNotReadyException { HttpConnector httpConnector = null; httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("test1"); httpConnector.tryToInit(false); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertNotNull(result); assertEquals(1, result.size()); httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("test1;test2"); httpConnector.tryToInit(false); result = httpConnector.prepareMultipartEntities(); assertNotNull(result); assertEquals(2, result.size()); assertNotNull(result.get("test1")); assertEquals("test1",result.get("test1").name); assertEquals("",result.get("test1").content); assertNull(result.get("test1").file); assertNull(result.get("test1").charset); assertNull(result.get("test1").conentType); assertNotNull(result.get("test2")); assertEquals("test2",result.get("test2").name); assertEquals("",result.get("test2").content); assertNull(result.get("test2").file); assertNull(result.get("test2").charset); assertNull(result.get("test2").conentType); } public void testMultipartEntitiesContentMapped() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity"); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = null; mappingFieldValues = new HashMap<String, String>(); mappingFieldValues.put("entity_Content", "contentValue"); this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertEquals("contentValue", result.get("entity").content); } public void testMultipartEntitiesCharsetMapped() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity"); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = null; mappingFieldValues = new HashMap<String, String>(); mappingFieldValues.put("entity_Charset", "customCharset"); this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertEquals("customCharset", result.get("entity").charset); } public void testMultipartEntitiesContentTypeMapped() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity"); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = null; mappingFieldValues = new HashMap<String, String>(); mappingFieldValues.put("entity_ContentType", "customContentType"); this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertEquals("customContentType", result.get("entity").conentType); } public void testCreateMultipartRecord() { DataRecordMetadata record = HttpConnector.createMultipartMetadataFromString("field1;otherField", "nameOfMetadata", ";"); assertEquals(8, record.getFields().length); assertEquals("field1_Content", record.getField(0).getLabelOrName()); assertEquals("otherField_ContentType", record.getField(6).getLabelOrName()); record = HttpConnector.createMultipartMetadataFromString(null, "nameOfMetadata", ";"); assertNull(record); record = HttpConnector.createMultipartMetadataFromString("", "nameOfMetadata", ";"); assertNull(record); } public void testMultipartEntitiesMultipleValues() throws ComponentNotReadyException { HttpConnector httpConnector = createHttpConnector(); httpConnector.setMultipartEntities("entity;second;third"); httpConnector.tryToInit(false); Map<String, String> mappingFieldValues = null; mappingFieldValues = new HashMap<String, String>(); mappingFieldValues.put("entity_Charset", "customCharset"); mappingFieldValues.put("second_Charset", "customCharset2"); mappingFieldValues.put("second_Content", "secContent"); mappingFieldValues.put("third_File", "file"); mappingFieldValues.put("third_ContentType", "myContentType"); this.createInputTransformation(httpConnector,mappingFieldValues); Map<String, HttpConnectorMutlipartEntity> result = null; result = httpConnector.prepareMultipartEntities(); assertEquals("customCharset", result.get("entity").charset); assertEquals("customCharset2", result.get("second").charset); assertEquals("secContent", result.get("second").content); assertEquals("file", result.get("third").file); assertEquals("myContentType", result.get("third").conentType); } private HttpConnector createHttpConnector() { HttpConnector httpConnector = new HttpConnector("HTTP_CONNECTOR1"); // DataRecord record = DataRecordFactory.newRecord(new DataRecordMetadata("TEST1")); DataRecord record = NullRecord.NULL_RECORD; httpConnector.inputRecord = record; return httpConnector; } private void createInputTransformation(HttpConnector httpConnector, Map<String,String> fieldValues) { // CTLMapping mapping = new CTLMapping("name", httpConnector); httpConnector.inputMappingTransformation.addInputMetadata("input", new CustomMetadata()); httpConnector.inputMappingTransformation.setTransformation("//#CTL2\nfunction integer transform() {return ALL;}"); DataRecord multipartRecord = null; if(fieldValues.keySet()!=null) { DataRecordMetadata[] metadata = httpConnector.inputMappingTransformation.getOutputRecordsMetadata(); for (int i=0; i<metadata.length; i++) { if(metadata[i]!=null && metadata[i].getName()!=null && metadata[i].getName().equals("MultipartEntities")) { multipartRecord = httpConnector.inputMappingTransformation.getOutputRecord(i); } } if (multipartRecord != null) { for (String key : fieldValues.keySet()) { multipartRecord.getField(key).setValue(fieldValues.get(key)); } } } } private DataRecord createConstDataRecord(Map<String,String> fieldValues) { DataRecordMetadata metadata = new DataRecordMetadata("Test"); for(String key : fieldValues.keySet()) { metadata.addField(new DataFieldMetadata(key, "|")); } DataRecord record = DataRecordFactory.newRecord(metadata ); record.init(); for(String key : fieldValues.keySet()) { record.getField(key).setValue(fieldValues.get(key)); } return record; } public void testBuildMultiPart() throws IOException { HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>(); HttpConnectorMutlipartEntity entity; entity = new HttpConnectorMutlipartEntity(); entity.name = "test1"; entity.content = "contenetOfValue"; multipartEntities.put(entity.name, entity); PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities); assertEquals(1, result.length); assertEquals("test1", result[0].name); assertEquals("contenetOfValue".length(), result[0].value.getContentLength()); } public void testBuildMultiPartFileName() throws IOException { HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>(); HttpConnectorMutlipartEntity entity; entity = new HttpConnectorMutlipartEntity(); entity.name = "test1"; entity.file = this.getClass().getResource("./HttpConnectorTest.class").getFile(); multipartEntities.put(entity.name, entity); PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities); assertEquals(1, result.length); assertEquals("HttpConnectorTest.class", result[0].value.getFilename()); assertEquals("test1", result[0].name); } public void testBuildMultiPartFileNameNameOverriden() throws IOException { HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>(); HttpConnectorMutlipartEntity entity; entity = new HttpConnectorMutlipartEntity(); entity.name = "test1"; entity.content = "ContentOfFile"; entity.file = "someFileName"; multipartEntities.put(entity.name, entity); PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities); assertEquals(1, result.length); assertEquals("someFileName", result[0].value.getFilename()); assertEquals("ContentOfFile".length(), result[0].value.getContentLength()); assertEquals("test1", result[0].name); } public void testBuildMultiPartFileNameMultipleSettings() throws IOException { HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>(); HttpConnectorMutlipartEntity entity; entity = new HttpConnectorMutlipartEntity(); entity.name = "test1"; entity.content = "Filename1"; entity.file = this.getClass().getResource("./HttpConnectorTest.class").getFile(); multipartEntities.put(entity.name, entity); entity = new HttpConnectorMutlipartEntity(); entity.name = "test2"; entity.conentType = "application/octetstream"; entity.file = this.getClass().getResource("./HttpConnectorTest.class").getFile(); multipartEntities.put(entity.name, entity); entity = new HttpConnectorMutlipartEntity(); entity.name = "test3"; entity.content = "Filename2"; entity.charset = "UTF-16"; entity.conentType = "application/octetstream"; entity.file = this.getClass().getResource("./HttpConnectorTest.class").getFile(); multipartEntities.put(entity.name, entity); entity = new HttpConnectorMutlipartEntity(); entity.name = "test4"; entity.content = "Filename2"; entity.charset = "UTF-16"; entity.conentType = "abcd"; multipartEntities.put(entity.name, entity); PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities); assertEquals(4, result.length); } public void testBuildMultiPartFileNameFileWithDetails() throws IOException { HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>(); HttpConnectorMutlipartEntity entity; entity = new HttpConnectorMutlipartEntity(); entity.name = "test3"; entity.content = "FileContent"; entity.charset = "UTF-16"; entity.conentType = "application/aaa"; entity.file = "Filename2"; multipartEntities.put(entity.name, entity); PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities); assertEquals(1, result.length); assertEquals("test3", result[0].name); assertEquals("Filename2", result[0].value.getFilename()); assertEquals("application/aaa", result[0].value.getMimeType()); assertEquals("UTF-16",result[0].value.getCharset()); } public void testBuildMultiPartContentType() throws IOException { HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>(); HttpConnectorMutlipartEntity entity; entity = new HttpConnectorMutlipartEntity(); entity.name = "test1"; entity.conentType = "abcdef"; multipartEntities.put(entity.name, entity); PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities); assertEquals(1, result.length); assertEquals("abcdef", result[0].value.getMimeType()); } public void testBuildMultiPartCharset() throws IOException { HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>(); HttpConnectorMutlipartEntity entity; entity = new HttpConnectorMutlipartEntity(); entity.name = "test1"; entity.charset = "UTF-16"; multipartEntities.put(entity.name, entity); PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities); assertEquals(1, result.length); assertEquals("UTF-16", result[0].value.getCharset()); } public void testBuildMultiPartEmpty() throws IOException { assertNull(this.createHttpConnector().buildMultiPart(null)); assertNotNull(this.createHttpConnector().buildMultiPart(new HashMap<String, HttpConnectorMutlipartEntity>())); assertEquals(0, this.createHttpConnector().buildMultiPart(new HashMap<String, HttpConnectorMutlipartEntity>()).length); } } class CustomMetadata extends DataRecordMetadata { private static final long serialVersionUID = 1L; /** * @param name */ public CustomMetadata() { super("TestMetadata"); } }
// FILE: c:/projects/jetel/org/jetel/data/DelimitedDataParser.java package org.jetel.data.parser; import java.io.IOException; import java.io.InputStream; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.IParserExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.exception.PolicyType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.QuotingDecoder; import org.jetel.util.StringUtils; /** * Parsing delimited text data. Supports delimiters with the length of up to 32 * characters. Delimiter for each individual field must be specified - through * metadata definition. The maximum length of one parseable field is denoted by * <b>FIELD_BUFFER_LENGTH</b> . Parser handles quoted strings (single or double). * This class is using the new IO (NIO) features * introduced in Java 1.4 - directly mapped byte buffers & character * encoders/decoders * *@author D.Pavlis *@since March 27, 2002 *@see Parser *@see org.jetel.data.Defaults * @revision $Revision$ */ public class DelimitedDataParser implements Parser { static Log logger = LogFactory.getLog(DelimitedDataParser.class); private String charSet = null; private IParserExceptionHandler exceptionHandler; private ByteBuffer dataBuffer; private CharBuffer charBuffer; private CharBuffer fieldStringBuffer; private char[] delimiterCandidateBuffer; private DataRecordMetadata metadata; private ReadableByteChannel reader; private CharsetDecoder decoder; private int recordCounter; private char[][] delimiters; private char[] fieldTypes; private boolean isEof; // Attributes // maximum length of delimiter private final static int DELIMITER_CANDIDATE_BUFFER_LENGTH = 32; private QuotingDecoder qdecoder; public DelimitedDataParser() { this(Defaults.DataParser.DEFAULT_CHARSET_DECODER, new QuotingDecoder()); } // Associations // Operations /** * Constructor for the DelimitedDataParser object. With default size and * default character encoding. * *@since March 28, 2002 */ public DelimitedDataParser(QuotingDecoder qdecoder) { this(Defaults.DataParser.DEFAULT_CHARSET_DECODER, qdecoder); } public DelimitedDataParser(String charsetDecoder) { this(charsetDecoder, new QuotingDecoder()); } /** * Constructor for the DelimitedDataParser object * *@param charsetDecoder Charset Decoder used for converting input data into * UNICODE chars *@since March 28, 2002 */ public DelimitedDataParser(String charsetDecoder, QuotingDecoder qdecoder) { this.charSet = charsetDecoder; this.qdecoder = qdecoder; dataBuffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); charBuffer = CharBuffer.allocate(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); fieldStringBuffer = CharBuffer.allocate(Defaults.DataParser.FIELD_BUFFER_LENGTH); delimiterCandidateBuffer = new char [DELIMITER_CANDIDATE_BUFFER_LENGTH]; decoder = Charset.forName(charsetDecoder).newDecoder(); } /** * Returs next data record parsed from input stream or NULL if no more data * available * *@return The Next value *@exception IOException Description of Exception *@since May 2, 2002 */ public DataRecord getNext() throws JetelException { // create a new data record DataRecord record = new DataRecord(metadata); record.init(); boolean success = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.handleException(); success = parseNext(record); } } return success ? record : null; } /** * Returs next data record parsed from input stream or NULL if no more data * available The specified DataRecord's fields are altered to contain new * values. * *@param record Description of Parameter *@return The Next value *@exception IOException Description of Exception *@since May 2, 2002 */ public DataRecord getNext(DataRecord record) throws JetelException { return getNext0(record) ? record : null; } private boolean getNext0(DataRecord record) throws JetelException { boolean retval = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.handleException(); //record.init(); //redundant retval = parseNext(record); } } return retval; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#init(org.jetel.metadata.DataRecordMetadata) */ public void init(DataRecordMetadata metadata) throws ComponentNotReadyException { if (metadata.getRecType() != DataRecordMetadata.DELIMITED_RECORD) { throw new ComponentNotReadyException("Delimited data expected but not encountered"); } DataFieldMetadata fieldMetadata; this.metadata = metadata; // create array of delimiters & initialize them delimiters = new char[metadata.getNumFields()][]; fieldTypes = new char[metadata.getNumFields()]; for (int i = 0; i < metadata.getNumFields(); i++) { fieldMetadata = metadata.getField(i); delimiters[i] = fieldMetadata.getDelimiter().toCharArray(); fieldTypes[i] = fieldMetadata.getType(); // we handle only one character delimiters } } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object) */ public void setDataSource(Object inputDataSource) { releaseDataSource(); decoder.reset();// reset CharsetDecoder dataBuffer.clear(); dataBuffer.flip(); charBuffer.clear(); charBuffer.flip(); recordCounter = 1;// reset record counter if (inputDataSource == null) { isEof = true; } else { isEof = false; if (inputDataSource instanceof ReadableByteChannel) { reader = ((ReadableByteChannel)inputDataSource); } else { reader = Channels.newChannel((InputStream)inputDataSource); } } } /** * Release data source * */ private void releaseDataSource() { if (reader == null || !reader.isOpen()) { return; } try { reader.close(); } catch (IOException e) { logger.error(e.getStackTrace()); } reader = null; } /** * Release resources * *@since May 2, 2002 */ public void close() { releaseDataSource(); } /** * Assembles error message when exception occures during parsing * *@param exceptionMessage message from exception getMessage() call *@param recNo recordNumber *@param fieldNo fieldNumber *@return error message *@since September 19, 2002 */ private String getErrorMessage(String exceptionMessage,CharSequence value, int recNo, int fieldNo) { StringBuffer message = new StringBuffer(); message.append(exceptionMessage); message.append(" when parsing record message.append(recordCounter); message.append(" field "); message.append(metadata.getField(fieldNo).getName()); if (value!=null){ message.append(" value \"").append(value).append("\""); } return message.toString(); } /** * Description of the Method * * @return Description of the Returned Value * @exception IOException * Description of Exception * @since May 13, 2002 */ private int readChar() throws IOException { CoderResult result; if (charBuffer.hasRemaining()) { return charBuffer.get(); } if (isEof) return -1; charBuffer.clear(); if (dataBuffer.hasRemaining()) dataBuffer.compact(); else dataBuffer.clear(); if (reader.read(dataBuffer) == -1) { isEof = true; } dataBuffer.flip(); result = decoder.decode(dataBuffer, charBuffer, isEof); if (result == CoderResult.UNDERFLOW) { // try to load additional data dataBuffer.compact(); if (reader.read(dataBuffer) == -1) { isEof = true; } dataBuffer.flip(); decoder.decode(dataBuffer, charBuffer, isEof); } else if (result.isError()) { throw new IOException(result.toString()+" when converting from "+decoder.charset()); } if (isEof) { result = decoder.flush(charBuffer); if (result.isError()) { throw new IOException(result.toString()+" when converting from "+decoder.charset()); } } charBuffer.flip(); return charBuffer.hasRemaining() ? charBuffer.get() : -1; } /** * An operation that does ... * *@param record Description of Parameter *@return Next DataRecord (parsed from input data) or null if * no more records available *@exception IOException Description of Exception *@since March 27, 2002 */ private boolean parseNext(DataRecord record) throws JetelException { int result; int fieldCounter = 0; int character; int totalCharCounter = 0; int delimiterPosition; int charCounter; boolean isWithinQuotes; // populate all data fields while (fieldCounter < metadata.getNumFields()) { // we clear our buffer fieldStringBuffer.clear(); character = 0; isWithinQuotes=false; // read data till we reach delimiter, end of file or exceed buffer size // exceeded buffer is indicated by BufferOverflowException charCounter = 0; delimiterPosition = 0; try { while ((character = readChar()) != -1) { // causes problem when composed delimiter "\r\n" is used // if(character=='\r') //fix for new line being \r\n // continue; totalCharCounter++; // handle quoted strings // TODO ignore quotes in case they are preceded by escape character if (isWithinQuotes) { /* TODO complain in case that the closing quote isn't at the end of the field or consider unescaped closing quote to be end of the field */ if (qdecoder.isEndQuote((char)character)) { isWithinQuotes = false; } } else { if (qdecoder.isStartQuote((char)character) && charCounter == 0) { isWithinQuotes=true; } } if ((result = is_delimiter((char) character, fieldCounter, delimiterPosition,isWithinQuotes)) == 1) { /* * DELIMITER */ break; } else if (result == 0) { /* * NOT A DELIMITER */ if (delimiterPosition > 0) { fieldStringBuffer.put(delimiterCandidateBuffer,0,delimiterPosition); } else { try{ fieldStringBuffer.put((char) character); }catch(BufferOverflowException ex){ throw new IOException("Field too long or can not find delimiter ["+String.valueOf(delimiters[fieldCounter])+"]"); } } delimiterPosition = 0; } else { /* * CAN'T DECIDE DELIMITER */ delimiterCandidateBuffer[delimiterPosition]=((char) character); delimiterPosition++; } charCounter++; } if ((character == -1) && (totalCharCounter > 1)) { //- incomplete record - do something throw new RuntimeException("Incomplete record"); } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(getErrorMessage(ex.getClass().getName()+":"+ex.getMessage(),null, recordCounter, fieldCounter),ex); } // did we have EOF situation ? if (character == -1) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); throw new JetelException(e.getMessage()); } return false; } // set field's value // are we skipping this row/field ? if (record != null){ fieldStringBuffer.flip(); populateField(record, fieldCounter, fieldStringBuffer); } fieldCounter++; } recordCounter++; return true; } /** * Description of the Method * *@param record Description of Parameter *@param fieldNum Description of Parameter *@param data Description of Parameter *@since March 28, 2002 */ private void populateField(DataRecord record, int fieldNum, CharBuffer data) { CharSequence strData = buffer2String(data, fieldNum); try { record.getField(fieldNum).fromString(strData); } catch (BadDataFormatException bdfe) { if(exceptionHandler != null ) { //use handler only if configured exceptionHandler.populateHandler(getErrorMessage(bdfe .getMessage(), data, recordCounter, fieldNum), record, -1, fieldNum, "\"" + StringUtils.specCharToString(strData) + "\"", bdfe); } else { bdfe.setRecordNumber(recordCounter); bdfe.setFieldNumber(fieldNum); bdfe.setOffendingValue("\"" + StringUtils.specCharToString(strData) + "\""); throw bdfe; } } catch (Exception ex) { throw new RuntimeException(getErrorMessage(ex.getMessage(),null,recordCounter, fieldNum),ex); } } /** * Transfers CharBuffer into string and handles quoting of strings (removes quotes) * *@param buffer Character buffer to work on *@return String with quotes removed if specified */ private CharSequence buffer2String(CharBuffer buffer,int fieldNum) { if (metadata.getField(fieldNum).getType()== DataFieldMetadata.STRING_FIELD) { return qdecoder.decode(buffer); } return buffer; } /** * Decides whether delimiter was encountered * *@param character character to compare with delimiter *@param fieldCounter delimiter for which field *@param delimiterPosition current position within delimiter string *@return 1 if delimiter matched; -1 if can't decide yet; 0 if not part of delimiter */ private int is_delimiter(char character, int fieldCounter, int delimiterPosition, boolean isWithinQuotes) { if (isWithinQuotes){ return 0; } if (character == delimiters[fieldCounter][delimiterPosition]) { if (delimiterPosition == delimiters[fieldCounter].length - 1) { return 1; // whole delimiter matched } else { return -1; // can't decide } } else { return 0; // not a match } } /** * Returns charset name of this parser * @return Returns name of the charset used to construct or null if none was specified */ public String getCharsetName() { return(this.charSet); } /** * Returns data policy type for this parser * @return Data policy type or null if none was specified */ public PolicyType getPolicyType() { if (this.exceptionHandler != null) { return this.exceptionHandler.getType(); } else { return null; } } public void setExceptionHandler(IParserExceptionHandler handler) { this.exceptionHandler = handler; } public IParserExceptionHandler getExceptionHandler() { return exceptionHandler; } /** * Skip records. * @param nRec Number of records to be skipped * @return Number of successfully skipped records. * @throws JetelException */ public int skip(int nRec) throws JetelException { int skipped; for (skipped = 0; skipped < nRec; skipped++) { if (!getNext0(null)) { // end of file reached break; } } return skipped; } } /* * end class DelimitedDataParser */
package org.col.db.mapper; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import com.google.common.base.Preconditions; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; /** * Mybatis result handler that offers the streamed records in batches. * Make always sure to close the handler to submit the last batch! */ public class BatchResultHandler<T> implements ResultHandler<T>, AutoCloseable { private final Consumer<List<T>> batchConsumer; private final int batchSize; private final List<T> batch; public BatchResultHandler(Consumer<List<T>> batchConsumer, int batchSize) { Preconditions.checkArgument(batchSize > 0); this.batchConsumer = batchConsumer; this.batchSize = batchSize; batch = new ArrayList<>(batchSize); } @Override public void handleResult(ResultContext<? extends T> ctx) { batch.add(ctx.getResultObject()); if (batch.size() >= batchSize) { submit(); } } private void submit() { batchConsumer.accept(batch); batch.clear(); } @Override public void close() throws Exception { submit(); } }
package org.cometd.bayeux; public interface Channel { /** Constant representing the meta prefix */ public static final String META = "/meta"; /** Constant representing the handshake meta channel. */ public final static String META_HANDSHAKE = META + "/handshake"; /** Constant representing the connect meta channel */ public final static String META_CONNECT = META + "/connect"; /** Constant representing the subscribe meta channel */ public final static String META_SUBSCRIBE = META + "/subscribe"; /** Constant representing the unsubscribe meta channel */ public final static String META_UNSUBSCRIBE = META + "/unsubscribe"; /** Constant representing the disconnect meta channel */ public final static String META_DISCONNECT = META + "/disconnect"; /** * @return The channel id */ String getId(); /** * @return true if the channel is a meta channel */ boolean isMeta(); /** * @return true if the channel is a service channel */ boolean isService(); /** * @return true if the channel is wild. */ boolean isWild(); /** * @return true if the channel is deeply wild. */ boolean isDeepWild(); }
package fr.free.nrw.commons.upload; import android.content.*; import android.os.*; import com.nostra13.universalimageloader.core.ImageLoader; import android.net.*; import android.support.v4.app.NavUtils; import com.actionbarsherlock.view.MenuItem; import android.widget.*; import fr.free.nrw.commons.*; import fr.free.nrw.commons.modifications.CategoryModifier; import fr.free.nrw.commons.modifications.TemplateRemoveModifier; import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.EventLog; import fr.free.nrw.commons.category.CategorizationFragment; import fr.free.nrw.commons.contributions.*; import fr.free.nrw.commons.auth.*; import fr.free.nrw.commons.modifications.ModificationsContentProvider; import fr.free.nrw.commons.modifications.ModifierSequence; import java.util.ArrayList; public class ShareActivity extends AuthenticatedActivity implements SingleUploadFragment.OnUploadActionInitiated, CategorizationFragment.OnCategoriesSaveHandler { private SingleUploadFragment shareView; private CategorizationFragment categorizationFragment; public ShareActivity() { super(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE); } private CommonsApplication app; private String source; private String mimeType; private Uri mediaUri; private Contribution contribution; private ImageView backgroundImageView; private UploadController uploadController; public void uploadActionInitiated(String title, String description) { Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG); startingToast.show(); uploadController.startUpload(title, mediaUri, description, mimeType, source, new UploadController.ContributionUploadProgress() { public void onUploadStarted(Contribution contribution) { ShareActivity.this.contribution = contribution; showPostUpload(); } }); } private void showPostUpload() { if(categorizationFragment == null) { categorizationFragment = new CategorizationFragment(); } getSupportFragmentManager().beginTransaction() .replace(R.id.single_upload_fragment_container, categorizationFragment, "categorization") .commit(); } public void onCategoriesSave(ArrayList<String> categories) { if(categories.size() > 0) { ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri()); categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{}))); categoriesSequence.queueModifier(new TemplateRemoveModifier("Uncategorized")); categoriesSequence.setContentProviderClient(getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY)); categoriesSequence.save(); } // FIXME: Make sure that the content provider is up // This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin ContentResolver.setSyncAutomatically(app.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT) .param("username", app.getCurrentAccount().name) .param("categories-count", categories.size()) .param("files-count", 1) .param("source", contribution.getSource()) .param("result", "queued") .log(); finish(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(contribution != null) { outState.putParcelable("contribution", contribution); } } @Override public void onBackPressed() { super.onBackPressed(); if(categorizationFragment != null && categorizationFragment.isVisible()) { EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT) .param("username", app.getCurrentAccount().name) .param("categories-count", categorizationFragment.getCurrentSelectedCount()) .param("files-count", 1) .param("source", contribution.getSource()) .param("result", "cancelled") .log(); } else { EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT) .param("username", app.getCurrentAccount().name) .param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE)) .param("multiple", true) .param("result", "cancelled") .log(); } } @Override protected void onAuthCookieAcquired(String authCookie) { super.onAuthCookieAcquired(authCookie); app.getApi().setAuthCookie(authCookie); shareView = (SingleUploadFragment) getSupportFragmentManager().findFragmentByTag("shareView"); categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization"); if(shareView == null && categorizationFragment == null) { shareView = new SingleUploadFragment(); this.getSupportFragmentManager() .beginTransaction() .add(R.id.single_upload_fragment_container, shareView, "shareView") .commit(); } uploadController.prepareService(); } @Override protected void onAuthFailure() { super.onAuthFailure(); Toast failureToast = Toast.makeText(this, R.string.authentication_failed, Toast.LENGTH_LONG); failureToast.show(); finish(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uploadController = new UploadController(this); setContentView(R.layout.activity_share); app = (CommonsApplication)this.getApplicationContext(); backgroundImageView = (ImageView)findViewById(R.id.backgroundImage); Intent intent = getIntent(); if(intent.getAction().equals(Intent.ACTION_SEND)) { mediaUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if(intent.hasExtra(UploadService.EXTRA_SOURCE)) { source = intent.getStringExtra(UploadService.EXTRA_SOURCE); } else { source = Contribution.SOURCE_EXTERNAL; } mimeType = intent.getType(); } ImageLoader.getInstance().displayImage(mediaUri.toString(), backgroundImageView); if(savedInstanceState != null) { contribution = savedInstanceState.getParcelable("contribution"); } requestAuthToken(); } @Override protected void onDestroy() { super.onDestroy(); uploadController.cleanup(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }
package net.runelite.api; /** * Represents a chat entity that has a name. */ public interface Nameable extends Comparable<Nameable> { /** * The name of the player. * * @return the name */ String getName(); /** * The previous name the player had. * * @return the previous name */ String getPrevName(); }
package org.spine3.server; import org.junit.Test; import org.spine3.test.project.Project; import org.spine3.test.project.ProjectId; import javax.annotation.Nullable; import static org.junit.Assert.assertEquals; /** * @author Alexander Litus */ @SuppressWarnings("InstanceMethodNamingConvention") public class RepositoryBaseShould { @Test @SuppressWarnings("ResultOfObjectAllocationIgnored") // OK in this case public void throw_exception_if_entity_constructor_is_protected() { try { new RepositoryForEntitiesWithProtectedConstructor(); } catch (RuntimeException e) { assertEquals(e.getCause().getClass(), IllegalAccessException.class); } } @Test @SuppressWarnings("ResultOfObjectAllocationIgnored") // OK in this case public void throw_exception_if_entity_constructor_is_private() { try { new RepositoryForEntitiesWithPrivateConstructor(); } catch (RuntimeException e) { assertEquals(e.getCause().getClass(), IllegalAccessException.class); } } @Test @SuppressWarnings("ResultOfObjectAllocationIgnored") // OK in this case public void throw_exception_if_entity_has_no_required_constructor() { try { new RepositoryForEntitiesWithoutRequiredConstructor(); } catch (RuntimeException e) { assertEquals(e.getCause().getClass(), NoSuchMethodException.class); } } public static class RepositoryForEntitiesWithProtectedConstructor extends RepositoryBase<ProjectId, EntityWithProtectedConstructor> { @Override protected void checkStorageClass(Object storage) { } @Override public void store(EntityWithProtectedConstructor obj) { } @Nullable @Override public EntityWithProtectedConstructor load(ProjectId id) { return null; } } public static class EntityWithProtectedConstructor extends Entity<ProjectId, Project> { protected EntityWithProtectedConstructor(ProjectId id) { super(id); } @Override protected Project getDefaultState() { return Project.getDefaultInstance(); } } public static class RepositoryForEntitiesWithPrivateConstructor extends RepositoryBase<ProjectId, EntityWithPrivateConstructor> { @Override protected void checkStorageClass(Object storage) { } @Override public void store(EntityWithPrivateConstructor obj) { } @Nullable @Override public EntityWithPrivateConstructor load(ProjectId id) { return null; } } public static class EntityWithPrivateConstructor extends Entity<ProjectId, Project> { private EntityWithPrivateConstructor(ProjectId id) { super(id); } @Override protected Project getDefaultState() { return Project.getDefaultInstance(); } } public static class RepositoryForEntitiesWithoutRequiredConstructor extends RepositoryBase<ProjectId, EntityWithoutRequiredConstructor> { @Override protected void checkStorageClass(Object storage) { } @Override public void store(EntityWithoutRequiredConstructor obj) { } @Nullable @Override public EntityWithoutRequiredConstructor load(ProjectId id) { return null; } } public static class EntityWithoutRequiredConstructor extends Entity<ProjectId, Project> { private EntityWithoutRequiredConstructor() { super(ProjectId.getDefaultInstance()); } @Override protected Project getDefaultState() { return Project.getDefaultInstance(); } } }
package alluxio.worker.file; import alluxio.AlluxioURI; import alluxio.Configuration; import alluxio.Constants; import alluxio.Sessions; import alluxio.exception.FileAlreadyExistsException; import alluxio.exception.FileDoesNotExistException; import alluxio.heartbeat.HeartbeatContext; import alluxio.heartbeat.HeartbeatThread; import alluxio.thrift.FileSystemWorkerClientService; import alluxio.util.ThreadFactoryUtils; import alluxio.util.network.NetworkAddressUtils; import alluxio.util.network.NetworkAddressUtils.ServiceType; import alluxio.worker.AbstractWorker; import alluxio.worker.SessionTracker; import alluxio.worker.WorkerContext; import alluxio.worker.block.BlockWorker; import com.google.common.base.Preconditions; import org.apache.thrift.TProcessor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.annotation.concurrent.NotThreadSafe; /** * This class is responsible for managing all top level components of the file system worker. */ // TODO(calvin): Add session concept // TODO(calvin): Reconsider the naming of the ufs operations @NotThreadSafe // TODO(jiri): make thread-safe (c.f. ALLUXIO-1624) public final class FileSystemWorker extends AbstractWorker implements SessionTracker { /** Logic for managing file persistence. */ private final FileDataManager mFileDataManager; /** Client for file system master communication. */ private final FileSystemMasterClient mFileSystemMasterWorkerClient; /** Configuration object. */ private final Configuration mConf; /** Logic for handling RPC requests. */ private final FileSystemWorkerClientServiceHandler mServiceHandler; /** Object for managing this worker's sessions. */ private final Sessions mSessions; /** Manager for under file system operations. */ private final UnderFileSystemManager mUnderFileSystemManager; /** The service that persists files. */ private Future<?> mFilePersistenceService; /** * Creates a new instance of {@link FileSystemWorker}. * * @param blockWorker the block worker handle * @throws IOException if an I/O error occurs */ public FileSystemWorker(BlockWorker blockWorker) throws IOException { super(Executors.newFixedThreadPool(3, ThreadFactoryUtils.build("file-system-worker-heartbeat-%d", true))); mConf = WorkerContext.getConf(); mSessions = new Sessions(); mFileDataManager = new FileDataManager(Preconditions.checkNotNull(blockWorker)); mUnderFileSystemManager = new UnderFileSystemManager(); // Setup AbstractMasterClient mFileSystemMasterWorkerClient = new FileSystemMasterClient( NetworkAddressUtils.getConnectAddress(ServiceType.MASTER_RPC, mConf), mConf); mServiceHandler = new FileSystemWorkerClientServiceHandler(this); } @Override public Map<String, TProcessor> getServices() { Map<String, TProcessor> services = new HashMap<>(); services.put( Constants.FILE_SYSTEM_WORKER_CLIENT_SERVICE_NAME, new FileSystemWorkerClientService.Processor<>(getWorkerServiceHandler())); return services; } /** * Cancels a file currently being written to the under file system. The open stream will be * closed and the partial file will be cleaned up. * * @param sessionId the session id of the request * @param tempUfsFileId the id of the file to cancel, only understood by the worker that created * the file * @throws FileDoesNotExistException if this worker is not writing the specified file * @throws IOException if an error occurs interacting with the under file system */ public void cancelUfsFile(long sessionId, long tempUfsFileId) throws FileDoesNotExistException, IOException { mUnderFileSystemManager.cancelFile(sessionId, tempUfsFileId); } /** * Cleans up after sessions, to prevent zombie sessions. This method is called periodically by * {@link SessionCleaner} thread. */ public void cleanupSessions() { for (long session: mSessions.getTimedOutSessions()) { mSessions.removeSession(session); mUnderFileSystemManager.cleanupSession(session); } } /** * Closes a file currently being read from the under file system. The open stream will be * closed and the file id will no longer be valid. * * @param sessionId the session id of the request * @param tempUfsFileId the id of the file to close, only understood by the worker that opened * the file * @throws FileDoesNotExistException if the worker is not reading the specified file * @throws IOException if an error occurs interacting with the under file system */ public void closeUfsFile(long sessionId, long tempUfsFileId) throws FileDoesNotExistException, IOException { mUnderFileSystemManager.closeFile(sessionId, tempUfsFileId); } /** * Completes a file currently being written to the under file system. The open stream will be * closed and the partial file will be promoted to the completed file in the under file system. * * @param sessionId the session id of the request * @param tempUfsFileId the id of the file to complete, only understood by the worker that created * the file * @throws FileDoesNotExistException if the worker is not writing the specified file * @throws IOException if an error occurs interacting with the under file system */ public void completeUfsFile(long sessionId, long tempUfsFileId) throws FileDoesNotExistException, IOException { mUnderFileSystemManager.completeFile(sessionId, tempUfsFileId); } /** * Creates a new file in the under file system. This will register a new stream in the under * file system manager. The stream can only be accessed with the returned id afterward. * * @param sessionId the session id of the request * @param ufsUri the under file system uri to create a file for * @throws FileAlreadyExistsException if a file already exists in the under file system with * the same path * @throws IOException if an error occurs interacting with the under file system * @return the temporary worker specific file id which references the in-progress ufs file */ // TODO(calvin): Add a session id to clean up in case of disconnection public long createUfsFile(long sessionId, AlluxioURI ufsUri) throws FileAlreadyExistsException, IOException { return mUnderFileSystemManager.createFile(sessionId, ufsUri); } /** * Opens a stream to the under file system file denoted by the temporary file id. This call * will skip to the position specified in the file before returning the stream. The caller of * this method is required to close the stream after they have finished operations on it. * * @param tempUfsFileId the worker specific temporary file id for the file in the under storage * @param position the absolute position in the file to position the stream at before returning * @return an input stream to the ufs file positioned at the given position * @throws FileDoesNotExistException if the worker file id is invalid * @throws IOException if an error occurs interacting with the under file system */ public InputStream getUfsInputStream(long tempUfsFileId, long position) throws FileDoesNotExistException, IOException { return mUnderFileSystemManager.getInputStreamAtPosition(tempUfsFileId, position); } /** * Returns the output stream to the under file system file denoted by the temporary file id. * The stream should not be closed by the caller but through the {@link #cancelUfsFile(long,long)} * or the {@link #completeUfsFile(long,long)} methods. * * @param tempUfsFileId the worker specific temporary file id for the file in the under storage * @return the output stream writing the contents of the file * @throws FileDoesNotExistException if the temporary file id is invalid */ public OutputStream getUfsOutputStream(long tempUfsFileId) throws FileDoesNotExistException { return mUnderFileSystemManager.getOutputStream(tempUfsFileId); } /** * @return the worker service handler */ public FileSystemWorkerClientServiceHandler getWorkerServiceHandler() { return mServiceHandler; } /** * Opens a file in the under file system and registers a temporary file id with the file. This * id is valid until the file is closed. * * @param sessionId the session id of the request * @param ufsUri the under file system path of the file to open * @return the temporary file id which references the file * @throws FileDoesNotExistException if the file does not exist in the under file system * @throws IOException if an error occurs interacting with the under file system */ public long openUfsFile(long sessionId, AlluxioURI ufsUri) throws FileDoesNotExistException, IOException { return mUnderFileSystemManager.openFile(sessionId, ufsUri); } /** * Registers a client's heartbeat to keep its session alive. The client can also * piggyback metrics on this call. Currently there are no metrics collected from this call. * * @param sessionId the session id to renew * @param metrics a list of metrics to update from the client */ public void sessionHeartbeat(long sessionId, List<Long> metrics) { // Metrics currently ignored mSessions.sessionHeartbeat(sessionId); } /** * Starts the filesystem worker service. */ @Override public void start() { mFilePersistenceService = getExecutorService() .submit(new HeartbeatThread(HeartbeatContext.WORKER_FILESYSTEM_MASTER_SYNC, new FileWorkerMasterSyncExecutor(mFileDataManager, mFileSystemMasterWorkerClient), mConf.getInt(Constants.WORKER_FILESYSTEM_HEARTBEAT_INTERVAL_MS))); } /** * Stops the filesystem worker service. */ @Override public void stop() { if (mFilePersistenceService != null) { mFilePersistenceService.cancel(true); } mFileSystemMasterWorkerClient.close(); getExecutorService().shutdown(); } }
package org.openecard.sal; import iso.std.iso_iec._24727.tech.schema.ACLList; import iso.std.iso_iec._24727.tech.schema.ACLListResponse; import iso.std.iso_iec._24727.tech.schema.ACLModify; import iso.std.iso_iec._24727.tech.schema.ACLModifyResponse; import iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType; import iso.std.iso_iec._24727.tech.schema.AuthorizationServiceActionName; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSessionResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationList; import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse.CardApplicationNameList; import iso.std.iso_iec._24727.tech.schema.CardApplicationPath; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathType; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceActionName; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribe; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribeResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceList; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoad; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoadResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse.CardApplicationServiceNameList; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceType; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSessionResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationType; import iso.std.iso_iec._24727.tech.schema.Connect; import iso.std.iso_iec._24727.tech.schema.ConnectResponse; import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType; import iso.std.iso_iec._24727.tech.schema.ConnectionServiceActionName; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticate; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticationDataType; import iso.std.iso_iec._24727.tech.schema.DIDCreate; import iso.std.iso_iec._24727.tech.schema.DIDCreateResponse; import iso.std.iso_iec._24727.tech.schema.DIDDelete; import iso.std.iso_iec._24727.tech.schema.DIDDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DIDGet; import iso.std.iso_iec._24727.tech.schema.DIDGetResponse; import iso.std.iso_iec._24727.tech.schema.DIDInfoType; import iso.std.iso_iec._24727.tech.schema.DIDList; import iso.std.iso_iec._24727.tech.schema.DIDListResponse; import iso.std.iso_iec._24727.tech.schema.DIDNameListType; import iso.std.iso_iec._24727.tech.schema.DIDQualifierType; import iso.std.iso_iec._24727.tech.schema.DIDScopeType; import iso.std.iso_iec._24727.tech.schema.DIDStructureType; import iso.std.iso_iec._24727.tech.schema.DIDUpdate; import iso.std.iso_iec._24727.tech.schema.DIDUpdateDataType; import iso.std.iso_iec._24727.tech.schema.DIDUpdateResponse; import iso.std.iso_iec._24727.tech.schema.DSICreate; import iso.std.iso_iec._24727.tech.schema.DSICreateResponse; import iso.std.iso_iec._24727.tech.schema.DSIDelete; import iso.std.iso_iec._24727.tech.schema.DSIDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DSIList; import iso.std.iso_iec._24727.tech.schema.DSIListResponse; import iso.std.iso_iec._24727.tech.schema.DSINameListType; import iso.std.iso_iec._24727.tech.schema.DSIRead; import iso.std.iso_iec._24727.tech.schema.DSIReadResponse; import iso.std.iso_iec._24727.tech.schema.DSIWrite; import iso.std.iso_iec._24727.tech.schema.DSIWriteResponse; import iso.std.iso_iec._24727.tech.schema.DSIType; import iso.std.iso_iec._24727.tech.schema.DataSetCreate; import iso.std.iso_iec._24727.tech.schema.DataSetCreateResponse; import iso.std.iso_iec._24727.tech.schema.DataSetDelete; import iso.std.iso_iec._24727.tech.schema.DataSetDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DataSetInfoType; import iso.std.iso_iec._24727.tech.schema.DataSetList; import iso.std.iso_iec._24727.tech.schema.DataSetListResponse; import iso.std.iso_iec._24727.tech.schema.DataSetNameListType; import iso.std.iso_iec._24727.tech.schema.DataSetSelect; import iso.std.iso_iec._24727.tech.schema.DataSetSelectResponse; import iso.std.iso_iec._24727.tech.schema.Decipher; import iso.std.iso_iec._24727.tech.schema.DecipherResponse; import iso.std.iso_iec._24727.tech.schema.DifferentialIdentityServiceActionName; import iso.std.iso_iec._24727.tech.schema.Disconnect; import iso.std.iso_iec._24727.tech.schema.DisconnectResponse; import iso.std.iso_iec._24727.tech.schema.Encipher; import iso.std.iso_iec._24727.tech.schema.EncipherResponse; import iso.std.iso_iec._24727.tech.schema.ExecuteAction; import iso.std.iso_iec._24727.tech.schema.ExecuteActionResponse; import iso.std.iso_iec._24727.tech.schema.GetRandom; import iso.std.iso_iec._24727.tech.schema.GetRandomResponse; import iso.std.iso_iec._24727.tech.schema.Hash; import iso.std.iso_iec._24727.tech.schema.HashResponse; import iso.std.iso_iec._24727.tech.schema.Initialize; import iso.std.iso_iec._24727.tech.schema.InitializeResponse; import iso.std.iso_iec._24727.tech.schema.NamedDataServiceActionName; import iso.std.iso_iec._24727.tech.schema.Sign; import iso.std.iso_iec._24727.tech.schema.SignResponse; import iso.std.iso_iec._24727.tech.schema.TargetNameType; import iso.std.iso_iec._24727.tech.schema.Terminate; import iso.std.iso_iec._24727.tech.schema.TerminateResponse; import iso.std.iso_iec._24727.tech.schema.VerifyCertificate; import iso.std.iso_iec._24727.tech.schema.VerifyCertificateResponse; import iso.std.iso_iec._24727.tech.schema.VerifySignature; import iso.std.iso_iec._24727.tech.schema.VerifySignatureResponse; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import org.openecard.addon.AddonManager; import org.openecard.addon.AddonNotFoundException; import org.openecard.addon.AddonSelector; import org.openecard.addon.HighestVersionSelector; import org.openecard.addon.sal.FunctionType; import org.openecard.addon.sal.SALProtocol; import org.openecard.common.ECardConstants; import org.openecard.common.ECardException; import org.openecard.common.WSHelper; import org.openecard.common.apdu.DeleteFile; import org.openecard.common.apdu.EraseBinary; import org.openecard.common.apdu.EraseRecord; import org.openecard.common.apdu.Select; import org.openecard.common.apdu.UpdateBinary; import org.openecard.common.apdu.UpdateRecord; import org.openecard.common.apdu.WriteBinary; import org.openecard.common.apdu.WriteRecord; import org.openecard.common.apdu.common.CardCommandAPDU; import org.openecard.common.apdu.common.CardResponseAPDU; import org.openecard.common.apdu.utils.CardUtils; import org.openecard.common.interfaces.DispatcherException; import org.openecard.common.interfaces.Environment; import org.openecard.common.sal.Assert; import org.openecard.common.sal.anytype.CryptoMarkerType; import org.openecard.common.sal.exception.InappropriateProtocolForActionException; import org.openecard.common.sal.exception.IncorrectParameterException; import org.openecard.common.sal.exception.NameExistsException; import org.openecard.common.sal.exception.NamedEntityNotFoundException; import org.openecard.common.sal.exception.PrerequisitesNotSatisfiedException; import org.openecard.common.sal.exception.SecurityConditionNotSatisfiedException; import org.openecard.common.sal.exception.UnknownConnectionHandleException; import org.openecard.common.sal.exception.UnknownProtocolException; import org.openecard.common.sal.state.CardStateEntry; import org.openecard.common.sal.state.CardStateMap; import org.openecard.common.sal.state.cif.CardApplicationWrapper; import org.openecard.common.sal.state.cif.CardInfoWrapper; import org.openecard.common.sal.util.SALUtils; import org.openecard.common.tlv.iso7816.DataElements; import org.openecard.common.tlv.iso7816.FCP; import org.openecard.gui.UserConsent; import org.openecard.ws.SAL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TinySAL implements SAL { private static final Logger logger = LoggerFactory.getLogger(TinySAL.class); private final Environment env; private final CardStateMap states; private AddonSelector protocolSelector; private UserConsent userConsent; /** * Creates a new TinySAL. * * @param env Environment * @param states CardStateMap */ public TinySAL(Environment env, CardStateMap states) { this.env = env; this.states = states; } public void setAddonManager(AddonManager manager) { protocolSelector = new AddonSelector(manager); protocolSelector.setStrategy(new HighestVersionSelector()); } /** * The Initialize function is executed when the ISO24727-3-Interface is invoked for the first time. * The interface is initialised with this function. * See BSI-TR-03112-4, version 1.1.2, section 3.1.1. * * @param request Initialize * @return InitializeResponse */ @Override public InitializeResponse initialize(Initialize request) { return WSHelper.makeResponse(InitializeResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The Terminate function is executed when the ISO24727-3-Interface is terminated. * This function closes all established connections and open sessions. * See BSI-TR-03112-4, version 1.1.2, section 3.1.2. * * @param request Terminate * @return TerminateResponse */ @Override public TerminateResponse terminate(Terminate request) { return WSHelper.makeResponse(TerminateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationPath function determines a path between the client application and a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.1.3. * * @param request CardApplicationPath * @return CardApplicationPathResponse */ @Override public CardApplicationPathResponse cardApplicationPath(CardApplicationPath request) { CardApplicationPathResponse response = WSHelper.makeResponse(CardApplicationPathResponse.class, WSHelper.makeResultOK()); try { CardApplicationPathType cardAppPath = request.getCardAppPathRequest(); Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty."); Set<CardStateEntry> entries = states.getMatchingEntries(cardAppPath); // Copy entries to result set CardAppPathResultSet resultSet = new CardAppPathResultSet(); List<CardApplicationPathType> resultPaths = resultSet.getCardApplicationPathResult(); for (CardStateEntry entry : entries) { CardApplicationPathType pathCopy = entry.pathCopy(); if (cardAppPath.getCardApplication() != null) { pathCopy.setCardApplication(cardAppPath.getCardApplication()); } else { pathCopy.setCardApplication(entry.getImplicitlySelectedApplicationIdentifier()); } resultPaths.add(pathCopy); } response.setCardAppPathResultSet(resultSet); } catch (IncorrectParameterException e) { response.setResult(e.getResult()); } return response; } /** * The CardApplicationConnect function establishes an unauthenticated connection between the client * application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.1. * * @param request CardApplicationConnect * @return CardApplicationConnectResponse */ @Override public CardApplicationConnectResponse cardApplicationConnect(CardApplicationConnect request) { CardApplicationConnectResponse response = WSHelper.makeResponse(CardApplicationConnectResponse.class, WSHelper.makeResultOK()); try { CardApplicationPathType cardAppPath = request.getCardApplicationPath(); Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty."); Set<CardStateEntry> cardStateEntrySet = states.getMatchingEntries(cardAppPath, false); Assert.assertIncorrectParameter(cardStateEntrySet, "The given ConnectionHandle is invalid."); /* * [TR-03112-4] If the provided path fragments are valid for more than one card application * the eCard-API-Framework SHALL return any of the possible choices. */ CardStateEntry cardStateEntry = cardStateEntrySet.iterator().next(); byte[] applicationID = cardAppPath.getCardApplication(); if (applicationID == null) { applicationID = cardStateEntry.getImplicitlySelectedApplicationIdentifier(); } Assert.securityConditionApplication(cardStateEntry, applicationID, ConnectionServiceActionName.CARD_APPLICATION_CONNECT); // Connect to the card CardApplicationPathType cardApplicationPath = cardStateEntry.pathCopy(); Connect connect = new Connect(); connect.setContextHandle(cardApplicationPath.getContextHandle()); connect.setIFDName(cardApplicationPath.getIFDName()); connect.setSlot(cardApplicationPath.getSlotIndex()); ConnectResponse connectResponse = (ConnectResponse) env.getDispatcher().deliver(connect); WSHelper.checkResult(connectResponse); // Select the card application CardCommandAPDU select; // TODO: proper determination of path, file and app id if (applicationID.length == 2) { select = new Select.File(applicationID); } else { select = new Select.Application(applicationID); } select.transmit(env.getDispatcher(), connectResponse.getSlotHandle()); cardStateEntry.setCurrentCardApplication(applicationID); cardStateEntry.setSlotHandle(connectResponse.getSlotHandle()); // reset the ef FCP cardStateEntry.unsetFCPOfSelectedEF(); states.addEntry(cardStateEntry); response.setConnectionHandle(cardStateEntry.handleCopy()); response.getConnectionHandle().setCardApplication(applicationID); } catch (ECardException e) { response.setResult(e.getResult()); } catch (DispatcherException e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } catch (InvocationTargetException e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationDisconnect function terminates the connection to a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.2. * * @param request CardApplicationDisconnect * @return CardApplicationDisconnectResponse */ @Override public CardApplicationDisconnectResponse cardApplicationDisconnect(CardApplicationDisconnect request) { CardApplicationDisconnectResponse response = WSHelper.makeResponse(CardApplicationDisconnectResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] slotHandle = connectionHandle.getSlotHandle(); // check existence of required parameters if (slotHandle == null) { return WSHelper.makeResponse(CardApplicationDisconnectResponse.class, WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, "ConnectionHandle is null")); } Disconnect disconnect = new Disconnect(); disconnect.setSlotHandle(slotHandle); DisconnectResponse disconnectResponse = (DisconnectResponse) env.getDispatcher().deliver(disconnect); // remove entries associated with this handle states.removeSlotHandleEntry(slotHandle); response.setResult(disconnectResponse.getResult()); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * This CardApplicationStartSession function starts a session between the client application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.3. * * @param request CardApplicationStartSession * @return CardApplicationStartSessionResponse */ @Override public CardApplicationStartSessionResponse cardApplicationStartSession(CardApplicationStartSession request) { CardApplicationStartSessionResponse response = WSHelper.makeResponse(CardApplicationStartSessionResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); Assert.assertIncorrectParameter(didName, "The parameter didName is empty."); DIDAuthenticationDataType didAuthenticationProtocolData = request.getAuthenticationProtocolData(); Assert.assertIncorrectParameter(didAuthenticationProtocolData, "The parameter didAuthenticationProtocolData is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_START_SESSION); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.CardApplicationStartSession)) { response = protocol.cardApplicationStartSession(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("CardApplicationStartSession", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationEndSession function closes the session between the client application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.4. * * @param request CardApplicationEndSession * @return CardApplicationEndSessionResponse */ @Override public CardApplicationEndSessionResponse cardApplicationEndSession(CardApplicationEndSession request) { CardApplicationEndSessionResponse response = WSHelper.makeResponse(CardApplicationEndSessionResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_END_SESSION); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.CardApplicationEndSession)) { response = protocol.cardApplicationEndSession(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("CardApplicationEndSession", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationList function returns a list of the available card applications on an eCard. * See BSI-TR-03112-4, version 1.1.2, section 3.3.1. * * @param request CardApplicationList * @return CardApplicationListResponse */ @Override public CardApplicationListResponse cardApplicationList(CardApplicationList request) { CardApplicationListResponse response = WSHelper.makeResponse(CardApplicationListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); /* TR-03112-4 section 3.3.2 states that the alpha application have to be connected with CardApplicationConnect. In case of using CardInfo file descriptions this is not necessary because we just work on a file. */ // byte[] cardApplicationID = connectionHandle.getCardApplication(); // Assert.securityConditionApplication(cardStateEntry, cardApplicationID, // CardApplicationServiceActionName.CARD_APPLICATION_LIST); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); CardApplicationNameList cardApplicationNameList = new CardApplicationNameList(); cardApplicationNameList.getCardApplicationName().addAll(cardInfoWrapper.getCardApplicationNameList()); response.setCardApplicationNameList(cardApplicationNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } @Override public CardApplicationCreateResponse cardApplicationCreate(CardApplicationCreate request) { return WSHelper.makeResponse(CardApplicationCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationDelete function deletes a card application as well as all corresponding * data sets, DSIs, DIDs and services. * See BSI-TR-03112-4, version 1.1.2, section 3.3.3. * * @param request CardApplicationDelete * @return CardApplicationDeleteResponse */ @Override public CardApplicationDeleteResponse cardApplicationDelete(CardApplicationDelete request) { CardApplicationDeleteResponse response = WSHelper.makeResponse(CardApplicationDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationName = request.getCardApplicationName(); Assert.assertIncorrectParameter(cardApplicationName, "The parameter CardApplicationName is empty."); Assert.securityConditionApplication(cardStateEntry, connectionHandle.getCardApplication(), CardApplicationServiceActionName.CARD_APPLICATION_DELETE); DeleteFile delFile = new DeleteFile.Application(cardApplicationName); delFile.transmit(env.getDispatcher(), connectionHandle.getSlotHandle()); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationServiceList function returns a list of all available services of a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.4. * * @param request CardApplicationServiceList * @return CardApplicationServiceListResponse */ @Override public CardApplicationServiceListResponse cardApplicationServiceList(CardApplicationServiceList request) { CardApplicationServiceListResponse response = WSHelper.makeResponse(CardApplicationServiceListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); //Assert.securityConditionApplication(cardStateEntry, cardApplicationID, // CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_LIST); CardApplicationServiceNameList cardApplicationServiceNameList = new CardApplicationServiceNameList(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator(); while (it.hasNext()) { CardApplicationType next = it.next(); byte[] appName = next.getApplicationIdentifier(); if (Arrays.equals(appName, cardApplicationID)) { Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator(); while (itt.hasNext()) { CardApplicationServiceType nextt = itt.next(); cardApplicationServiceNameList.getCardApplicationServiceName().add(nextt.getCardApplicationServiceName()); } } } response.setCardApplicationServiceNameList(cardApplicationServiceNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationServiceCreate function creates a new service in the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.5. * * @param request CardApplicationServiceCreate * @return CardApplicationServiceCreateResponse */ @Override public CardApplicationServiceCreateResponse cardApplicationServiceCreate(CardApplicationServiceCreate request) { return WSHelper.makeResponse(CardApplicationServiceCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * Code for a specific card application service was loaded into the card application with the aid * of the CardApplicationServiceLoad function. * See BSI-TR-03112-4, version 1.1.2, section 3.3.6. * * @param request CardApplicationServiceLoad * @return CardApplicationServiceLoadResponse */ @Override public CardApplicationServiceLoadResponse cardApplicationServiceLoad(CardApplicationServiceLoad request) { return WSHelper.makeResponse(CardApplicationServiceLoadResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationServiceDelete function deletes a card application service in a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.7. * * @param request CardApplicationServiceDelete * @return CardApplicationServiceDeleteResponse */ @Override public CardApplicationServiceDeleteResponse cardApplicationServiceDelete(CardApplicationServiceDelete request) { return WSHelper.makeResponse(CardApplicationServiceDeleteResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationServiceDescribe function can be used to request an URI, an URL or a detailed description * of the selected card application service. * See BSI-TR-03112-4, version 1.1.2, section 3.3.8. * * @param request CardApplicationServiceDescribe * @return CardApplicationServiceDescribeResponse */ @Override public CardApplicationServiceDescribeResponse cardApplicationServiceDescribe(CardApplicationServiceDescribe request) { CardApplicationServiceDescribeResponse response = WSHelper.makeResponse(CardApplicationServiceDescribeResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String cardApplicationServiceName = request.getCardApplicationServiceName(); Assert.assertIncorrectParameter(cardApplicationServiceName, "The parameter CardApplicationServiceName is empty."); //Assert.securityConditionApplication(cardStateEntry, cardApplicationID, // CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_DESCRIBE); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator(); while (it.hasNext()) { CardApplicationType next = it.next(); byte[] appName = next.getApplicationIdentifier(); if (Arrays.equals(appName, cardApplicationID)){ Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator(); while (itt.hasNext()) { CardApplicationServiceType nextt = itt.next(); if (nextt.getCardApplicationServiceName().equals(cardApplicationServiceName)) { response.setServiceDescription(nextt.getCardApplicationServiceDescription()); } } } } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The ExecuteAction function permits use of additional card application services by the client application * which are not explicitly specified in [ISO24727-3] but which can be implemented by the eCard with additional code. * See BSI-TR-03112-4, version 1.1.2, section 3.3.9. * * @param request ExecuteAction * @return ExecuteActionResponse */ @Override public ExecuteActionResponse executeAction(ExecuteAction request) { return WSHelper.makeResponse(ExecuteActionResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The DataSetList function returns the list of the data sets in the card application addressed with the * ConnectionHandle. * See BSI-TR-03112-4, version 1.1.2, section 3.4.1. * * @param request DataSetList * @return DataSetListResponse */ @Override public DataSetListResponse dataSetList(DataSetList request) { DataSetListResponse response = WSHelper.makeResponse(DataSetListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); byte[] cardApplicationID = connectionHandle.getCardApplication(); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, NamedDataServiceActionName.DATA_SET_LIST); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetNameListType dataSetNameList = cardInfoWrapper.getDataSetNameList(cardApplicationID); response.setDataSetNameList(dataSetNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DataSetCreate function creates a new data set in the card application addressed with the * ConnectionHandle (or otherwise in a previously selected data set if this is implemented as a DF). * See BSI-TR-03112-4, version 1.1.2, section 3.4.2. * * @param request DataSetCreate * @return DataSetCreateResponse */ @Override public DataSetCreateResponse dataSetCreate(DataSetCreate request) { return WSHelper.makeResponse(DataSetCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The DataSetSelect function selects a data set in a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.4.3. * * @param request DataSetSelect * @return DataSetSelectResponse */ @Override public DataSetSelectResponse dataSetSelect(DataSetSelect request) { DataSetSelectResponse response = WSHelper.makeResponse(DataSetSelectResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dataSetName = request.getDataSetName(); Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dataSetName, applicationID); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dataSetName, NamedDataServiceActionName.DATA_SET_SELECT); byte[] fileID = dataSetInfo.getDataSetPath().getEfIdOrPath(); byte[] slotHandle = connectionHandle.getSlotHandle(); CardResponseAPDU result = CardUtils.selectFileWithOptions(env.getDispatcher(), slotHandle, fileID, null, CardUtils.FCP_RESPONSE_DATA); if (result != null) { cardStateEntry.setFCPOfSelectedEF(new FCP(result.getData())); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DataSetDelete function deletes a data set of a card application on an eCard. * See BSI-TR-03112-4, version 1.1.2, section 3.4.4. * * @param request DataSetDelete * @return DataSetDeleteResponse */ @Override public DataSetDeleteResponse dataSetDelete(DataSetDelete request) { DataSetDeleteResponse response = WSHelper.makeResponse(DataSetDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); String dataSetName = request.getDataSetName(); Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty."); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSetName, NamedDataServiceActionName.DATA_SET_DELETE); DataSetInfoType dataSet = cardInfoWrapper.getDataSet(dataSetName, cardApplicationID); if (dataSet == null) { throw new NamedEntityNotFoundException("The data set " + dataSetName + " does not exist."); } byte[] path = dataSet.getDataSetPath().getEfIdOrPath(); int len = path.length; byte[] fid = new byte[] {path[len - 2], path[len - 1]}; DeleteFile delFile = new DeleteFile.ChildFile(fid); delFile.transmit(env.getDispatcher(), connectionHandle.getSlotHandle()); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The function DSIList supplies the list of the DSI (Data Structure for Interoperability) which exist in the * selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.5. <br> * <br> * Prerequisites: <br> * - a connection to a card application has been established <br> * - a data set has been selected <br> * * @param request DSIList * @return DSIListResponse */ @Override public DSIListResponse dsiList(DSIList request) { DSIListResponse response = WSHelper.makeResponse(DSIListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] cardApplicationID = connectionHandle.getCardApplication(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No EF selected."); } DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid( cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(), NamedDataServiceActionName.DSI_LIST); DSINameListType dsiNameList = new DSINameListType(); for (DSIType dsi : dataSet.getDSI()) { dsiNameList.getDSIName().add(dsi.getDSIName()); } response.setDSINameList(dsiNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSICreate function creates a DSI (Data Structure for Interoperability) in the currently selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.6. * <br> * <br> * Preconditions: <br> * - Connection to a card application established via CardApplicationConnect <br> * - A data set has been selected with DataSetSelect <br> * - The DSI does not exist in the data set. <br> * * @param request DSICreate * @return DSICreateResponse */ @Override public DSICreateResponse dsiCreate(DSICreate request) { DSICreateResponse response = WSHelper.makeResponse(DSICreateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] cardApplicationID = connectionHandle.getCardApplication(); byte[] dsiContent = request.getDSIContent(); Assert.assertIncorrectParameter(dsiContent, "The parameter DSIContent is empty."); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); if (dsi != null) { throw new NameExistsException("There is already an DSI with the name " + dsiName + " in the current EF."); } byte[] slotHandle = connectionHandle.getSlotHandle(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No data set for writing selected."); } else { DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid( cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(), NamedDataServiceActionName.DSI_CREATE); DataElements dElements = cardStateEntry.getFCPOfSelectedEF().getDataElements(); if (dElements.isTransparent()) { WriteBinary writeBin = new WriteBinary(WriteBinary.INS_WRITE_BINARY_DATA, (byte) 0x00, (byte) 0x00, dsiContent); writeBin.transmit(env.getDispatcher(), slotHandle); } else if (dElements.isCyclic()) { WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_PREVIOUS, dsiContent); writeRec.transmit(env.getDispatcher(), slotHandle); } else { WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_LAST, dsiContent); writeRec.transmit(env.getDispatcher(), slotHandle); } } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIDelete function deletes a DSI (Data Structure for Interoperability) in the currently selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.7. * * @param request DSIDelete * @return DSIDeleteResponse */ @Override public DSIDeleteResponse dsiDelete(DSIDelete request) { DSIDeleteResponse response = WSHelper.makeResponse(DSIDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); DataSetInfoType dSet = cardInfoWrapper.getDataSetByFid(cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, connectionHandle.getCardApplication(), dSet.getDataSetName(), NamedDataServiceActionName.DSI_DELETE); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); // We have to define some allowed answers because if the file has an write operation counter we wont get an // 9000 response. ArrayList<byte[]> responses = new ArrayList<byte[]>() { { add(new byte[] {(byte) 0x90, (byte) 0x00}); add(new byte[] {(byte) 0x63, (byte) 0xC1}); add(new byte[] {(byte) 0x63, (byte) 0xC2}); add(new byte[] {(byte) 0x63, (byte) 0xC3}); add(new byte[] {(byte) 0x63, (byte) 0xC4}); add(new byte[] {(byte) 0x63, (byte) 0xC5}); add(new byte[] {(byte) 0x63, (byte) 0xC6}); add(new byte[] {(byte) 0x63, (byte) 0xC7}); add(new byte[] {(byte) 0x63, (byte) 0xC8}); add(new byte[] {(byte) 0x63, (byte) 0xC9}); add(new byte[] {(byte) 0x63, (byte) 0xCA}); add(new byte[] {(byte) 0x63, (byte) 0xCB}); add(new byte[] {(byte) 0x63, (byte) 0xCC}); add(new byte[] {(byte) 0x63, (byte) 0xCD}); add(new byte[] {(byte) 0x63, (byte) 0xCE}); add(new byte[] {(byte) 0x63, (byte) 0xCF}); } }; if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isLinear()) { EraseRecord rmRecord = new EraseRecord(dsi.getDSIPath().getIndex()[0], EraseRecord.ERASE_JUST_P1); rmRecord.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses); } else { // NOTE: Erase binary allows to erase only everything after the offset or everything in front of the offset. // currently erasing everything after the offset is used. EraseBinary rmBinary = new EraseBinary((byte) 0x00, (byte) 0x00, dsi.getDSIPath().getIndex()); rmBinary.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses); } } catch (ECardException e) { logger.error(e.getMessage(), e); response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIWrite function changes the content of a DSI (Data Structure for Interoperability). * See BSI-TR-03112-4, version 1.1.2, section 3.4.8. * For clarification this method updates an existing DSI and does not create a new one. * * The precondition for this method is that a connection to a card application was established and a data set was * selected. Furthermore the DSI exists already. * * @param request DSIWrite * @return DSIWriteResponse */ @Override public DSIWriteResponse dsiWrite(DSIWrite request) { DSIWriteResponse response = WSHelper.makeResponse(DSIWriteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dsiName = request.getDSIName(); byte[] updateData = request.getDSIContent(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); Assert.assertIncorrectParameter(updateData, "The parameter DSIContent is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dsiName, applicationID); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DSIName cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_WRITE); if (! Arrays.equals(dataSetInfo.getDataSetPath().getEfIdOrPath(), cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) { throw new PrerequisitesNotSatisfiedException("The currently selected data set does not contain the DSI " + "to be updated."); } byte[] slotHandle = connectionHandle.getSlotHandle(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No EF with DSI selected."); } else if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isTransparent()) { // currently assuming that the index encodes the offset byte[] index = dsi.getDSIPath().getIndex(); UpdateBinary updateBin = new UpdateBinary(index[0], index[1], updateData); updateBin.transmit(env.getDispatcher(), slotHandle); } else { // currently assuming that the index encodes the record number byte index = dsi.getDSIPath().getIndex()[0]; UpdateRecord updateRec = new UpdateRecord(index, updateData); updateRec.transmit(env.getDispatcher(), slotHandle); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIRead function reads out the content of a specific DSI (Data Structure for Interoperability). * See BSI-TR-03112-4, version 1.1.2, section 3.4.9. * * @param request DSIRead * @return DSIReadResponse */ @Override public DSIReadResponse dsiRead(DSIRead request) { DSIReadResponse response = WSHelper.makeResponse(DSIReadResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dsiName, applicationID); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DSIName cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_READ); byte[] slotHandle = connectionHandle.getSlotHandle(); // throws a null pointer if no ef is selected byte[] fileContent = CardUtils.readFile(cardStateEntry.getFCPOfSelectedEF(), env.getDispatcher(), slotHandle); response.setDSIContent(fileContent); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Encipher function encrypts a transmitted plain text. The detailed behaviour of this function depends on * the protocol of the DID. * See BSI-TR-03112-4, version 1.1.2, section 3.5.1. * * @param request Encipher * @return EncipherResponse */ @Override public EncipherResponse encipher(Encipher request) { EncipherResponse response = WSHelper.makeResponse(EncipherResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] plainText = request.getPlainText(); Assert.assertIncorrectParameter(plainText, "The parameter PlainText is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Encipher)) { response = protocol.encipher(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Encipher", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Decipher function decrypts a given cipher text. The detailed behaviour of this function depends on * the protocol of the DID. * See BSI-TR-03112-4, version 1.1.2, section 3.5.2. * * @param request Decipher * @return DecipherResponse */ @Override public DecipherResponse decipher(Decipher request) { DecipherResponse response = WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] cipherText = request.getCipherText(); Assert.assertIncorrectParameter(cipherText, "The parameter CipherText is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Decipher)) { response = protocol.decipher(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Decipher", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The GetRandom function returns a random number which is suitable for authentication with the DID addressed with * DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.5.3. * * @param request GetRandom * @return GetRandomResponse */ @Override public GetRandomResponse getRandom(GetRandom request) { GetRandomResponse response = WSHelper.makeResponse(GetRandomResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier(); String didName = SALUtils.getDIDName(request); DIDScopeType didScope = request.getDIDScope(); if (didScope == null) { didScope = DIDScopeType.LOCAL; } if (didScope.equals(DIDScopeType.LOCAL)) { byte[] necessaryApp = cardStateEntry.getInfo().getApplicationIdByDidName(didName, didScope); if (! Arrays.equals(necessaryApp, applicationID)) { throw new SecurityConditionNotSatisfiedException("The wrong application is selected for getRandom()"); } } DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.GetRandom)) { response = protocol.getRandom(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("GetRandom", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Hash function calculates the hash value of a transmitted message. * See BSI-TR-03112-4, version 1.1.2, section 3.5.4. * * @param request Hash * @return HashResponse */ @Override public HashResponse hash(Hash request) { HashResponse response = WSHelper.makeResponse(HashResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] message = request.getMessage(); Assert.assertIncorrectParameter(message, "The parameter Message is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Hash)) { response = protocol.hash(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Hash", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Sign function signs a transmitted message. * See BSI-TR-03112-4, version 1.1.2, section 3.5.5. * * @param request Sign * @return SignResponse */ @Override public SignResponse sign(Sign request) { SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] message = request.getMessage(); Assert.assertIncorrectParameter(message, "The parameter Message is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Sign)) { response = protocol.sign(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Sign", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The VerifySignature function verifies a digital signature. * See BSI-TR-03112-4, version 1.1.2, section 3.5.6. * * @param request VerifySignature * @return VerifySignatureResponse */ @Override public VerifySignatureResponse verifySignature(VerifySignature request) { VerifySignatureResponse response = WSHelper.makeResponse(VerifySignatureResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] signature = request.getSignature(); Assert.assertIncorrectParameter(signature, "The parameter Signature is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.VerifySignature)) { response = protocol.verifySignature(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("VerifySignature", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The VerifyCertificate function validates a given certificate. * See BSI-TR-03112-4, version 1.1.2, section 3.5.7. * * @param request VerifyCertificate * @return VerifyCertificateResponse */ @Override public VerifyCertificateResponse verifyCertificate(VerifyCertificate request) { VerifyCertificateResponse response = WSHelper.makeResponse(VerifyCertificateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] certificate = request.getCertificate(); Assert.assertIncorrectParameter(certificate, "The parameter Certificate is empty."); String certificateType = request.getCertificateType(); Assert.assertIncorrectParameter(certificateType, "The parameter CertificateType is empty."); String rootCert = request.getRootCert(); Assert.assertIncorrectParameter(rootCert, "The parameter RootCert is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.VerifyCertificate)) { response = protocol.verifyCertificate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("VerifyCertificate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDList function returns a list of the existing DIDs in the card application addressed by the * ConnectionHandle or the ApplicationIdentifier element within the Filter. * See BSI-TR-03112-4, version 1.1.2, section 3.6.1. * * @param request DIDList * @return DIDListResponse */ @Override public DIDListResponse didList(DIDList request) { DIDListResponse response = WSHelper.makeResponse(DIDListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] appId = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); Assert.securityConditionApplication(cardStateEntry, appId, DifferentialIdentityServiceActionName.DID_LIST); byte[] applicationIDFilter = null; String objectIDFilter = null; String applicationFunctionFilter = null; DIDQualifierType didQualifier = request.getFilter(); if (didQualifier != null) { applicationIDFilter = didQualifier.getApplicationIdentifier(); objectIDFilter = didQualifier.getObjectIdentifier(); applicationFunctionFilter = didQualifier.getApplicationFunction(); } /* * Filter by ApplicationIdentifier. * [TR-03112-4] Allows specifying an application identifier. If this element is present all * DIDs within the specified card application are returned no matter which card application * is currently selected. */ CardApplicationWrapper cardApplication; if (applicationIDFilter != null) { cardApplication = cardStateEntry.getInfo().getCardApplication(applicationIDFilter); Assert.assertIncorrectParameter(cardApplication, "The given CardApplication cannot be found."); } else { cardApplication = cardStateEntry.getCurrentCardApplication(); } List<DIDInfoType> didInfos = new ArrayList<DIDInfoType>(cardApplication.getDIDInfoList()); /* * Filter by ObjectIdentifier. * [TR-03112-4] Allows specifying a protocol OID (cf. [TR-03112-7]) such that only DIDs * which support a given protocol are listed. */ if (objectIDFilter != null) { Iterator<DIDInfoType> it = didInfos.iterator(); while (it.hasNext()) { DIDInfoType next = it.next(); if (!next.getDifferentialIdentity().getDIDProtocol().equals(objectIDFilter)) { it.remove(); } } } /* * Filter by ApplicationFunction. * [TR-03112-4] Allows filtering for DIDs, which support a specific cryptographic operation. * The bit string is coded as the SupportedOperations-element in [ISO7816-15]. */ if (applicationFunctionFilter != null) { Iterator<DIDInfoType> it = didInfos.iterator(); while (it.hasNext()) { DIDInfoType next = it.next(); if (next.getDifferentialIdentity().getDIDMarker().getCryptoMarker() == null) { it.remove(); } else { iso.std.iso_iec._24727.tech.schema.CryptoMarkerType rawMarker; rawMarker = next.getDifferentialIdentity().getDIDMarker().getCryptoMarker(); CryptoMarkerType cryptoMarker = new CryptoMarkerType(rawMarker); AlgorithmInfoType algInfo = cryptoMarker.getAlgorithmInfo(); if (! algInfo.getSupportedOperations().contains(applicationFunctionFilter)) { it.remove(); } } } } DIDNameListType didNameList = new DIDNameListType(); for (DIDInfoType didInfo : didInfos) { didNameList.getDIDName().add(didInfo.getDifferentialIdentity().getDIDName()); } response.setDIDNameList(didNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDCreate function creates a new differential identity in the card application addressed with ConnectionHandle. * See BSI-TR-03112-4, version 1.1.2, section 3.6.2. * * @param request DIDCreate * @return DIDCreateResponse */ @Override public DIDCreateResponse didCreate(DIDCreate request) { return WSHelper.makeResponse(DIDCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The public information for a DID is read with the DIDGet function. * See BSI-TR-03112-4, version 1.1.2, section 3.6.3. * * @param request DIDGet * @return DIDGetResponse */ @Override public DIDGetResponse didGet(DIDGet request) { DIDGetResponse response = WSHelper.makeResponse(DIDGetResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); // handle must be requested without application, as it is irrelevant for this call CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = SALUtils.getDIDName(request); DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle); response.setDIDStructure(didStructure); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDUpdate function creates a new key (marker) for the DID addressed with DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.4. * * @param request DIDUpdate * @return DIDUpdateResponse */ @Override public DIDUpdateResponse didUpdate(DIDUpdate request) { DIDUpdateResponse response = WSHelper.makeResponse(DIDUpdateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = request.getDIDName(); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDUpdateDataType didUpdateData = request.getDIDUpdateData(); Assert.assertIncorrectParameter(didUpdateData, "The parameter DIDUpdateData is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_UPDATE); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDUpdate)) { response = protocol.didUpdate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDUpdate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDDelete function deletes the DID addressed with DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.5. * * @param request DIDDelete * @return DIDDeleteResponse */ @Override public DIDDeleteResponse didDelete(DIDDelete request) { DIDDeleteResponse response = WSHelper.makeResponse(DIDDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = request.getDIDName(); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_DELETE); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDDelete)) { response = protocol.didDelete(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDDelete", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDAuthenticate function can be used to execute an authentication protocol using a DID addressed by DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.6. * * @param request DIDAuthenticate * @return DIDAuthenticateResponse */ @Override public DIDAuthenticateResponse didAuthenticate(DIDAuthenticate request) { DIDAuthenticateResponse response = WSHelper.makeResponse(DIDAuthenticateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); DIDAuthenticationDataType didAuthenticationData = request.getAuthenticationProtocolData(); Assert.assertIncorrectParameter(didAuthenticationData, "The parameter AuthenticationProtocolData is empty."); String protocolURI = didAuthenticationData.getProtocol(); // FIXME: workaround for missing protocol URI from eID-Servers if (protocolURI == null) { logger.warn("ProtocolURI was null"); protocolURI = ECardConstants.Protocol.EAC_GENERIC; } else if (protocolURI.equals("urn:oid:1.0.24727.3.0.0.7.2")) { logger.warn("ProtocolURI was urn:oid:1.0.24727.3.0.0.7.2"); protocolURI = ECardConstants.Protocol.EAC_GENERIC; } didAuthenticationData.setProtocol(protocolURI); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDAuthenticate)) { response = protocol.didAuthenticate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDAuthenticate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The ACLList function returns the access control list for the stated target object (card application, data set, DID). * See BSI-TR-03112-4, version 1.1.2, section 3.7.1. * * @param request ACLList * @return ACLListResponse */ @Override public ACLListResponse aclList(ACLList request) { ACLListResponse response = WSHelper.makeResponse(ACLListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); TargetNameType targetName = request.getTargetName(); Assert.assertIncorrectParameter(targetName, "The parameter TargetName is empty."); // get the target values, according to the schema only one must exist, we pick the first existing ;-) byte[] targetAppId = targetName.getCardApplicationName(); String targetDataSet = targetName.getDataSetName(); String targetDid = targetName.getDIDName(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] handleAppId = connectionHandle.getCardApplication(); if (targetDataSet != null) { DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(targetDataSet, handleAppId); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found."); response.setTargetACL(cardInfoWrapper.getDataSet(targetDataSet, handleAppId).getDataSetACL()); } else if (targetDid != null) { DIDInfoType didInfo = cardInfoWrapper.getDIDInfo(targetDid, handleAppId); Assert.assertNamedEntityNotFound(didInfo, "The given DIDInfo cannot be found."); //TODO Check security condition ? response.setTargetACL(cardInfoWrapper.getDIDInfo(targetDid, handleAppId).getDIDACL()); } else if (targetAppId != null) { CardApplicationWrapper cardApplication = cardInfoWrapper.getCardApplication(targetAppId); Assert.assertNamedEntityNotFound(cardApplication, "The given CardApplication cannot be found."); Assert.securityConditionApplication(cardStateEntry, targetAppId, AuthorizationServiceActionName.ACL_LIST); response.setTargetACL(cardInfoWrapper.getCardApplication(targetAppId).getCardApplicationACL()); } else { throw new IncorrectParameterException("The given TargetName is invalid."); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * An access rule in the access control list is modified with the ACLModify function. * See BSI-TR-03112-4, version 1.1.2, section 3.7.2. * * @param request ACLModify * @return ACLModifyResponse */ @Override public ACLModifyResponse aclModify(ACLModify request) { return WSHelper.makeResponse(ACLModifyResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * Sets the GUI. * * @param uc User consent */ public void setGUI(UserConsent uc) { this.userConsent = uc; } /** * Returns a list of ConnectionHandles. * * @return List of ConnectionHandles */ public List<ConnectionHandleType> getConnectionHandles() { ConnectionHandleType handle = new ConnectionHandleType(); Set<CardStateEntry> entries = states.getMatchingEntries(handle); ArrayList<ConnectionHandleType> result = new ArrayList<ConnectionHandleType>(entries.size()); for (CardStateEntry entry : entries) { result.add(entry.handleCopy()); } return result; } /** * Removes a finished protocol from the SAL instance. * * @param handle Connection Handle * @param protocolURI Protocol URI * @param protocol Protocol * @throws UnknownConnectionHandleException */ public void removeFinishedProtocol(ConnectionHandleType handle, String protocolURI, SALProtocol protocol) throws UnknownConnectionHandleException { if (protocol.isFinished()) { CardStateEntry entry = SALUtils.getCardStateEntry(states, handle); entry.removeProtocol(protocolURI); } } private SALProtocol getProtocol(ConnectionHandleType handle, String protocolURI) throws UnknownProtocolException, UnknownConnectionHandleException { CardStateEntry entry = SALUtils.getCardStateEntry(states, handle); SALProtocol protocol = entry.getProtocol(protocolURI); if (protocol == null) { try { protocol = protocolSelector.getSALProtocol(protocolURI); entry.setProtocol(protocolURI, protocol); } catch (AddonNotFoundException ex) { throw new UnknownProtocolException("The protocol URI '" + protocolURI + "' is not available."); } } protocol.getInternalData().put("cardState", entry); return protocol; } }
package com.github.weisj.darklaf.ui.menu; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.util.Arrays; import javax.swing.AbstractButton; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import com.github.weisj.darklaf.compatibility.MenuItemLayoutHelper; import com.github.weisj.darklaf.compatibility.SwingUtil; import com.github.weisj.darklaf.ui.util.DarkUIUtil; import com.github.weisj.darklaf.util.StringUtil; import com.github.weisj.darklaf.util.graphics.GraphicsContext; import com.github.weisj.darklaf.util.graphics.GraphicsUtil; public interface MenuItemUI { MenuItemLayoutHelper getMenuItemLayoutHelper(final Icon checkIcon, final Icon arrowIcon, final int defaultTextIconGap, final JMenuItem mi, final Rectangle viewRect); String getPropertyPrefix(); Color getDisabledForeground(); Color getSelectionForeground(); Color getAcceleratorSelectionForeground(); Color getAcceleratorForeground(); int getAcceleratorTextOffset(); boolean isUseEvenHeight(); default void paintMenuItemImpl(final Graphics g, final JComponent c, final Icon checkIcon, final Icon arrowIcon, final Color background, final Color foreground, final int defaultTextIconGap) { // Save original graphics font and color GraphicsContext context = new GraphicsContext(g); JMenuItem mi = (JMenuItem) c; g.setFont(mi.getFont()); Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight()); DarkUIUtil.applyInsets(viewRect, mi.getInsets()); MenuItemLayoutHelper lh = getMenuItemLayoutHelper(checkIcon, arrowIcon, defaultTextIconGap, mi, viewRect); MenuItemLayoutHelper.MILayoutResult lr = lh.layoutMenuItem(); paintBackgroundImpl(g, mi, background); context.restore(); paintCheckIcon(g, mi, lh, lr, foreground); context.restore(); paintIcon(g, mi, lh, lr); g.setColor(foreground); paintText(g, mi, lh, lr); paintAccText(g, mi, lh, lr); paintArrowIcon(g, mi, lh, lr, foreground); context.restore(); } default void paintBackgroundImpl(final Graphics g, final JMenuItem menuItem, final Color bgColor) { ButtonModel model = menuItem.getModel(); Color oldColor = g.getColor(); int menuWidth = menuItem.getWidth(); int menuHeight = menuItem.getHeight() + 1; boolean parentOpaque = menuItem.getParent().isOpaque(); if (menuItem.isOpaque() && parentOpaque) { if (model.isArmed() || (menuItem instanceof JMenu && model.isSelected())) { g.setColor(bgColor); } else { g.setColor(menuItem.getBackground()); } g.fillRect(0, 0, menuWidth, menuHeight); g.setColor(oldColor); } else if (model.isArmed() || (menuItem instanceof JMenu && model.isSelected())) { g.setColor(bgColor); g.fillRect(0, 0, menuWidth, menuHeight); g.setColor(oldColor); } } default void paintCheckIcon(final Graphics g, final JMenuItem mi, final MenuItemLayoutHelper lh, final MenuItemLayoutHelper.MILayoutResult lr, final Color foreground) { if (lh.getCheckIcon() != null) { ButtonModel model = mi.getModel(); if (model.isArmed() || (mi instanceof JMenu && model.isSelected())) { g.setColor(foreground); } if (lh.useCheckAndArrow()) { lh.getCheckIcon().paintIcon(mi, g, lr.getCheckRect().x, lr.getCheckRect().y); } } } default void paintIcon(final Graphics g, final JMenuItem mi, final MenuItemLayoutHelper lh, final MenuItemLayoutHelper.MILayoutResult lr) { if (lh.getIcon() != null) { Icon icon; ButtonModel model = mi.getModel(); if (!model.isEnabled()) { icon = mi.getDisabledIcon(); } else if (model.isPressed() && model.isArmed()) { icon = mi.getPressedIcon(); if (icon == null) { // Use default icon icon = mi.getIcon(); } } else { icon = mi.getIcon(); } if (icon != null) { icon.paintIcon(mi, g, lr.getIconRect().x, lr.getIconRect().y); } } } default void paintText(final Graphics g, final JMenuItem mi, final MenuItemLayoutHelper lh, final MenuItemLayoutHelper.MILayoutResult lr) { GraphicsContext config = GraphicsUtil.setupAntialiasing(g); if (!StringUtil.isBlank(lh.getText())) { if (lh.getHtmlView() != null) { // Text is HTML lh.getHtmlView().paint(g, lr.getTextRect()); } else { // Text isn't HTML paintItemText(g, mi, lr.getTextRect(), lh.getText()); } } config.restore(); } default void paintItemText(final Graphics g, final JMenuItem menuItem, final Rectangle textRect, final String text) { ButtonModel model = menuItem.getModel(); FontMetrics fm = SwingUtil.getFontMetrics(menuItem, g); int mnemIndex = menuItem.getDisplayedMnemonicIndex(); if (!model.isEnabled() || !menuItem.isEnabled()) { g.setColor(getDisabledForeground()); } else { if (model.isArmed() || (menuItem instanceof JMenu && model.isSelected())) { g.setColor(getSelectionForeground()); } } SwingUtil.drawStringUnderlineCharAt(menuItem, g, text, mnemIndex, textRect.x, textRect.y + fm.getAscent()); } default void paintAccText(final Graphics g, final JMenuItem mi, final MenuItemLayoutHelper lh, final MenuItemLayoutHelper.MILayoutResult lr) { GraphicsContext config = GraphicsUtil.setupAntialiasing(g); rightAlignAccText(lh, lr); if (!StringUtil.isBlank(lh.getAccText())) { g.setFont(lh.getAccFontMetrics().getFont()); g.setColor(getAcceleratorForeground(mi)); SwingUtil.drawString(mi, g, lh.getAccText(), lr.getAccRect().x, lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); } config.restore(); } default Color getAcceleratorForeground(final AbstractButton b) { ButtonModel model = b.getModel(); if (!model.isEnabled() || !b.isEnabled()) return getDisabledForeground(); if (model.isArmed() || (b instanceof JMenu && model.isSelected())) { return getAcceleratorSelectionForeground(); } else { return getAcceleratorForeground(); } } static void rightAlignAccText(final MenuItemLayoutHelper lh, final MenuItemLayoutHelper.MILayoutResult lr) { Rectangle accRect = lr.getAccRect(); ButtonModel model = lh.getMenuItem().getModel(); if (model.isEnabled()) { accRect.x = lh.getViewRect().x + lh.getViewRect().width - lh.getMenuItem().getIconTextGap() - lr.getAccRect().width; } } default void paintArrowIcon(final Graphics g, final JMenuItem mi, final MenuItemLayoutHelper lh, final MenuItemLayoutHelper.MILayoutResult lr, final Color foreground) { if (lh.getArrowIcon() != null) { ButtonModel model = mi.getModel(); if (model.isArmed() || (mi instanceof JMenu && model.isSelected())) { g.setColor(foreground); } if (lh.useCheckAndArrow()) { lh.getArrowIcon().paintIcon(mi, g, lr.getArrowRect().x, lr.getArrowRect().y); } } } default Dimension getPreferredMenuItemSizeImpl(final JComponent c, final Icon checkIcon, final Icon arrowIcon, final int defaultTextIconGap) { JMenuItem mi = (JMenuItem) c; MenuItemLayoutHelper lh = getMenuItemLayoutHelper(checkIcon, arrowIcon, defaultTextIconGap, mi, MenuItemLayoutHelper.createMaxRect()); Dimension result = new Dimension(); // Calculate the result width result.width = lh.getLeadingGap(); MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), lh.getAfterCheckIconGap(), result); // Take into account minimal text offset. if ((!lh.isTopLevelMenu()) && (lh.getMinTextOffset() > 0) && (result.width < lh.getMinTextOffset())) { result.width = lh.getMinTextOffset(); } int acceleratorTextOffset = getAcceleratorTextOffset(); MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), acceleratorTextOffset, result); MenuItemLayoutHelper.addMaxWidth(lh.getAccSize(), acceleratorTextOffset, result); MenuItemLayoutHelper.addMaxWidth(lh.getArrowSize(), lh.getGap(), result); // Calculate the result height result.height = Arrays.stream(new int[] {lh.getCheckSize().getHeight(), lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(), lh.getArrowSize().getHeight()}).max().orElse(Integer.MIN_VALUE); // Take into account menu item insets Insets insets = mi.getInsets(); if (insets != null) { result.width += insets.left + insets.right; result.height += insets.top + insets.bottom; } // if the height is even, bump it up one. This is critical. // for the text to center properly if (result.height % 2 == 0 && isUseEvenHeight()) { result.height++; } return result; } }
package id.gits.basosample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import id.gits.baso.BasoProgressView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { BasoProgressView mBasoProgressView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBasoProgressView = (BasoProgressView) findViewById(R.id.baso_ProgressView); findViewById(R.id.baso_btnStart).setOnClickListener(this); findViewById(R.id.baso_btnStopAndError).setOnClickListener(this); findViewById(R.id.baso_btnStopAndErrorNoImage).setOnClickListener(this); findViewById(R.id.baso_btnStopAndGone).setOnClickListener(this); mBasoProgressView.setOnButtonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBasoProgressView.startProgress(); } }); } @Override public void onClick(View v) { if (v.getId() == R.id.baso_btnStart) { mBasoProgressView.startProgress(); } else if (v.getId() == R.id.baso_btnStopAndError) { mBasoProgressView.setFinishedImageResource(R.drawable.baso_sample_error); mBasoProgressView.stop(); } else if (v.getId() == R.id.baso_btnStopAndErrorNoImage) { mBasoProgressView.setFinishedImageDrawable(null); mBasoProgressView.stopAndError("Something happened"); } else if (v.getId() == R.id.baso_btnStopAndGone) { mBasoProgressView.stopAndGone(); } } }
package com.headstartech.scheelite; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.headstartech.scheelite.exceptionmapper.ExceptionMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; class StateMachineImpl<T, U> implements StateMachine<T, U> { private static final Logger logger = LoggerFactory.getLogger(StateMachineImpl.class); private final StateTree<T, U> stateTree; private final TransitionMap<T, U> transitionMap; private final MultipleTransitionsTriggeredResolver<T, U> multipleTransitionsTriggeredResolver; private final StateMachineConfiguration<T, U> configuration; private final int maxTransitionsPerEvent; private final ExceptionMapper exceptionMapper; protected StateMachineImpl(StateMachineBuilder<T, U> builder) { this.stateTree = new ImmutableStateTree<T, U>(builder.getStateTree()); this.transitionMap = new ImmutableTransitionMap<T, U>(builder.getTransitionMap()); this.multipleTransitionsTriggeredResolver = builder.getMultipleTransitionsTriggeredResolver(); this.exceptionMapper = builder.getExceptionMapper(); this.maxTransitionsPerEvent = builder.getMaxTransitionsPerEvent(); this.configuration = new StateMachineConfiguration<T, U>(stateTree, transitionMap); } @Override public StateMachineConfiguration<T, U> getConfiguration() { return configuration; } @Override public U start(T context) { return handleInitialTransition(context); } @Override public U processEvent(T context, U stateId, Object event) { checkNotNull(context); checkNotNull(stateId); checkNotNull(event); int transitionCount = 0; ProcessEventResult<U> res = process(context, stateId, Optional.of(event), transitionCount++); while (res.isContinueProcessing()) { res = process(context, res.getNextStateId(), Optional.absent(), transitionCount++); } return res.getNextStateId(); } private void handleEvent(State<T, U> sourceState, T context, Optional<?> eventOpt) { if (eventOpt.isPresent()) { Object event = eventOpt.get(); boolean eventHandled = false; Optional<State<T, U>> stateOpt = Optional.of(sourceState); do { State<T, U> state = stateOpt.get(); logger.debug("handling event: context={}, state={}, event={}", context, state.getId(), event); try { eventHandled = state.onEvent(context, event); } catch(Exception e) { throw exceptionMapper.mapException(e); } stateOpt = stateTree.getParent(state); } while (!eventHandled && stateOpt.isPresent() && !stateOpt.get().equals(stateTree.getRootState())); } } private ProcessEventResult<U> process(T context, U stateId, Optional<?> eventOpt, int transitionCount) { checkNotNull(context); checkNotNull(stateId); checkNotNull(eventOpt); if (transitionCount >= maxTransitionsPerEvent) { throw new MaxTransitionsPerEventException(); } Optional<State<T, U>> currentStateOpt = stateTree.getState(stateId); if (!currentStateOpt.isPresent()) { throw new UnknownStateIdException(String.format("no state found for stateId: stateId=%s", stateId)); } State<T, U> currentState = currentStateOpt.get(); // handle event handleEvent(currentState, context, eventOpt); // processEvent triggered transition (if any) Optional<Transition<T, U>> triggeredTransitionOpt = getTriggeredTransition(currentState, context, eventOpt); if (triggeredTransitionOpt.isPresent()) { Transition<T, U> triggeredTransition = triggeredTransitionOpt.get(); logger.debug("transition triggered: context={}, state={}, transition={}, transitionType={}", context, currentState.getId(), triggeredTransition, triggeredTransition.getTransitionType().name()); State<T, U> mainSourceState = triggeredTransition.getMainSourceState(); State<T, U> mainTargetState = triggeredTransition.getMainTargetState(); // get lowest common ancestor (LCA) for main source state and main target state State<T, U> lowestCommonAncestor = stateTree.getLowestCommonAncestor(mainSourceState, mainTargetState); // exit sources states List<State<T, U>> sourceStates = getSourceStates(currentState, mainSourceState, mainTargetState, lowestCommonAncestor, triggeredTransition.getTransitionType()); for (State<T, U> state : sourceStates) { logger.debug("exiting state: context={}, state={}", context, state.getId()); try { state.onExit(context); } catch(Exception e) { throw exceptionMapper.mapException(e); } } // execute transition action (if any) Optional<? extends Action<T>> actionOpt = triggeredTransition.getAction(); if (actionOpt.isPresent()) { Action<T> action = actionOpt.get(); if(logger.isDebugEnabled()) { logger.debug("executing action: context={}, action={}", context, getActionName(action)); } try { action.execute(context, eventOpt); } catch(Exception e) { throw exceptionMapper.mapException(e); } } // enter target states List<State<T, U>> targetStates = getTargetStates(mainSourceState, mainTargetState, lowestCommonAncestor, triggeredTransition.getTransitionType()); for (State<T, U> state : targetStates) { logger.debug("entering state: context={}, state={}", context, state.getId()); try { state.onEntry(context); } catch(Exception e) { throw exceptionMapper.mapException(e); } } // handle initial transitions U nextStateId = handleInitialTransitions(mainTargetState, context); return new ProcessEventResult<U>(true, nextStateId); } else { return new ProcessEventResult<U>(false, currentState.getId()); } } private U handleInitialTransition(T context) { return handleInitialTransitions(stateTree.getRootState(), context); } private U handleInitialTransitions(State<T, U> startState, T context) { State<T, U> currentState = startState; Optional<Transition<T, U>> initialTransitionOpt = transitionMap.getInitialTransitionFromState(currentState); while (initialTransitionOpt.isPresent()) { Transition<T, U> it = initialTransitionOpt.get(); logger.debug("initial transition: transition={}", it); if (it.getAction().isPresent()) { Action<T> action = it.getAction().get(); if(logger.isDebugEnabled()) { logger.debug("executing action for initial transition: context={}, action={}", context, getActionName(action)); } try { action.execute(context, Optional.absent()); } catch(Exception e) { throw exceptionMapper.mapException(e); } } currentState = it.getMainTargetState(); logger.debug("entering state: context={}, state={}", context, currentState.getId()); try { currentState.onEntry(context); } catch(Exception e) { throw exceptionMapper.mapException(e); } initialTransitionOpt = transitionMap.getInitialTransitionFromState(currentState); } return currentState.getId(); } private List<State<T, U>> getSourceStates(State<T, U> currentState, State<T, U> mainSourceState, State<T, U> mainTargetState, State<T, U> lowestCommonAncestor, TransitionType transitionType) { List<State<T, U>> res = stateTree.getPathToAncestor(currentState, lowestCommonAncestor, false); if (TransitionType.EXTERNAL.equals(transitionType) && (mainSourceState.equals(lowestCommonAncestor) || mainTargetState.equals(lowestCommonAncestor))) { res.add(lowestCommonAncestor); } return res; } private List<State<T, U>> getTargetStates(State<T, U> mainSourceState, State<T, U> mainTargetState, State<T, U> lowestCommonAncestor, TransitionType transitionType) { List<State<T, U>> res = stateTree.getPathToAncestor(mainTargetState, lowestCommonAncestor, false); if (TransitionType.EXTERNAL.equals(transitionType) && (mainSourceState.equals(lowestCommonAncestor) || mainTargetState.equals(lowestCommonAncestor))) { res.add(lowestCommonAncestor); } Collections.reverse(res); return res; } private Optional<Transition<T, U>> getTriggeredTransition(State<T, U> currentState, T context, Optional<?> event) { List<State<T, U>> fromCurrentStateToRoot = stateTree.getPathToAncestor(currentState, stateTree.getRootState(), false); List<Transition<T, U>> transitions = Lists.newArrayList(); for (State<T, U> state : fromCurrentStateToRoot) { for(Transition<T, U> t : transitionMap.getTransitionsFromState(state)) { if(!t.getTransitionType().equals(TransitionType.INITIAL)) { transitions.add(t); } } } List<Transition<T, U>> triggeredTransitions = filterTransitions(transitions, context, event); if (triggeredTransitions.isEmpty()) { return Optional.absent(); } else if (triggeredTransitions.size() == 1) { return Optional.of(triggeredTransitions.get(0)); } else { try { return Optional.of(multipleTransitionsTriggeredResolver.resolve(currentState.getId(), context, event, triggeredTransitions)); } catch(Exception e) { throw exceptionMapper.mapException(e); } } } List<Transition<T, U>> filterTransitions(Collection<Transition<T, U>> transitions, T context, Optional<?> event) { List<Transition<T, U>> res = Lists.newArrayList(); for(Transition<T, U> t : transitions) { if(isTransitionTriggered(t, context, event)) { res.add(t); } } return res; } private boolean isTransitionTriggered(Transition<T, U> t, T context, Optional<?> event) { if (t.getTriggerEventClass().isPresent()) { Class<?> triggerEventClass = t.getTriggerEventClass().get(); if (event.isPresent()) { if (!triggerEventClass.isInstance(event.get())) { return false; } } else { return false; } } else { if(event.isPresent()) { return false; } } if (t.getGuard().isPresent()) { try { return t.getGuard().get().evaluate(context, event); } catch(Exception e) { throw exceptionMapper.mapException(e); } } else { // no guard present return true; } } private static class ProcessEventResult<U> { private final boolean continueProcessing; private final U nextStateId; private ProcessEventResult(boolean continueProcessing, U nextStateId) { this.continueProcessing = continueProcessing; this.nextStateId = nextStateId; } public boolean isContinueProcessing() { return continueProcessing; } public U getNextStateId() { return nextStateId; } } private String getActionName(Action<T> action) { return action.getClass().getName(); } }
// LIFReader.java package loci.formats.in; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import loci.common.DataTools; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.common.xml.XMLTools; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataStore; import loci.formats.services.OMEXMLService; import ome.xml.model.enums.DetectorType; import ome.xml.model.enums.LaserMedium; import ome.xml.model.enums.LaserType; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PercentFraction; import ome.xml.model.primitives.PositiveInteger; import org.xml.sax.SAXException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class LIFReader extends FormatReader { // -- Constants -- public static final byte LIF_MAGIC_BYTE = 0x70; public static final byte LIF_MEMORY_BYTE = 0x2a; private static final HashMap<String, Integer> CHANNEL_PRIORITIES = createChannelPriorities(); private static HashMap<String, Integer> createChannelPriorities() { HashMap<String, Integer> h = new HashMap<String, Integer>(); h.put("red", new Integer(0)); h.put("green", new Integer(1)); h.put("blue", new Integer(2)); h.put("cyan", new Integer(3)); h.put("magenta", new Integer(4)); h.put("yellow", new Integer(5)); h.put("black", new Integer(6)); h.put("gray", new Integer(7)); h.put("", new Integer(8)); return h; } private static final byte[][][] BYTE_LUTS = createByteLUTs(); private static byte[][][] createByteLUTs() { byte[][][] lut = new byte[9][3][256]; for (int i=0; i<256; i++) { // red lut[0][0][i] = (byte) (i & 0xff); // green lut[1][1][i] = (byte) (i & 0xff); // blue lut[2][2][i] = (byte) (i & 0xff); // cyan lut[3][1][i] = (byte) (i & 0xff); lut[3][2][i] = (byte) (i & 0xff); // magenta lut[4][0][i] = (byte) (i & 0xff); lut[4][2][i] = (byte) (i & 0xff); // yellow lut[5][0][i] = (byte) (i & 0xff); lut[5][1][i] = (byte) (i & 0xff); // gray lut[6][0][i] = (byte) (i & 0xff); lut[6][1][i] = (byte) (i & 0xff); lut[6][2][i] = (byte) (i & 0xff); lut[7][0][i] = (byte) (i & 0xff); lut[7][1][i] = (byte) (i & 0xff); lut[7][2][i] = (byte) (i & 0xff); lut[8][0][i] = (byte) (i & 0xff); lut[8][1][i] = (byte) (i & 0xff); lut[8][2][i] = (byte) (i & 0xff); } return lut; } private static final short[][][] SHORT_LUTS = createShortLUTs(); private static short[][][] createShortLUTs() { short[][][] lut = new short[9][3][65536]; for (int i=0; i<65536; i++) { // red lut[0][0][i] = (short) (i & 0xffff); // green lut[1][1][i] = (short) (i & 0xffff); // blue lut[2][2][i] = (short) (i & 0xffff); // cyan lut[3][1][i] = (short) (i & 0xffff); lut[3][2][i] = (short) (i & 0xffff); // magenta lut[4][0][i] = (short) (i & 0xffff); lut[4][2][i] = (short) (i & 0xffff); // yellow lut[5][0][i] = (short) (i & 0xffff); lut[5][1][i] = (short) (i & 0xffff); // gray lut[6][0][i] = (short) (i & 0xffff); lut[6][1][i] = (short) (i & 0xffff); lut[6][2][i] = (short) (i & 0xffff); lut[7][0][i] = (short) (i & 0xffff); lut[7][1][i] = (short) (i & 0xffff); lut[7][2][i] = (short) (i & 0xffff); lut[8][0][i] = (short) (i & 0xffff); lut[8][1][i] = (short) (i & 0xffff); lut[8][2][i] = (short) (i & 0xffff); } return lut; } // -- Fields -- /** Offsets to memory blocks, paired with their corresponding description. */ private Vector<Long> offsets; private int[][] realChannel; private int lastChannel = 0; private Vector<String> lutNames = new Vector<String>(); private Vector<Double> physicalSizeXs = new Vector<Double>(); private Vector<Double> physicalSizeYs = new Vector<Double>(); private String[] descriptions, microscopeModels, serialNumber; private Double[] pinholes, zooms, zSteps, tSteps, lensNA; private Double[][] expTimes, gains; private Vector[] detectorOffsets; private String[][] channelNames; private Vector[] detectorModels, voltages; private Integer[][] exWaves; private Vector[] activeDetector; private String[] immersions, corrections, objectiveModels; private Integer[] magnification; private Double[] posX, posY, posZ; private Double[] refractiveIndex; private Vector[] cutIns, cutOuts, filterModels; private double[][] timestamps; private Vector[] laserWavelength, laserIntensity; private ROI[][] imageROIs; private boolean alternateCenter = false; private String[] imageNames; private double[] acquiredDate; // -- Constructor -- /** Constructs a new Leica LIF reader. */ public LIFReader() { super("Leica Image File Format", "lif"); domains = new String[] {FormatTools.LM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); return getSizeY(); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 1; if (!FormatTools.validStream(stream, blockLen, true)) return false; return stream.read() == LIF_MAGIC_BYTE; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT8 || !isIndexed()) return null; return lastChannel < BYTE_LUTS.length ? BYTE_LUTS[lastChannel] : null; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT16 || !isIndexed()) return null; return lastChannel < SHORT_LUTS.length ? SHORT_LUTS[lastChannel] : null; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (!isRGB()) { int[] pos = getZCTCoords(no); lastChannel = realChannel[series][pos[1]]; } if (series >= offsets.size()) { // truncated file; imitate LAS AF and return black planes Arrays.fill(buf, (byte) 0); return buf; } long offset = offsets.get(series).longValue(); int bytes = FormatTools.getBytesPerPixel(getPixelType()); int bpp = bytes * getRGBChannelCount(); long planeSize = (long) getSizeX() * getSizeY() * bpp; long nextOffset = series + 1 < offsets.size() ? offsets.get(series + 1).longValue() : in.length(); int bytesToSkip = (int) (nextOffset - offset - planeSize * getImageCount()); bytesToSkip /= getSizeY(); if ((getSizeX() % 4) == 0) bytesToSkip = 0; if (offset + (planeSize + bytesToSkip * getSizeY()) * no >= in.length()) { // truncated file; imitate LAS AF and return black planes Arrays.fill(buf, (byte) 0); return buf; } in.seek(offset + planeSize * no); in.skipBytes(bytesToSkip * getSizeY() * no); if (bytesToSkip == 0) { readPlane(in, x, y, w, h, buf); } else { in.skipBytes(y * (getSizeX() * bpp + bytesToSkip)); for (int row=0; row<h; row++) { in.skipBytes(x * bpp); in.read(buf, row * w * bpp, w * bpp); in.skipBytes(bpp * (getSizeX() - w - x) + bytesToSkip); } } // color planes are stored in BGR order if (getRGBChannelCount() == 3) { ImageTools.bgrToRgb(buf, isInterleaved(), bytes, getRGBChannelCount()); } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { offsets = null; realChannel = null; lastChannel = 0; lutNames.clear(); physicalSizeXs.clear(); physicalSizeYs.clear(); descriptions = microscopeModels = serialNumber = null; pinholes = zooms = lensNA = null; zSteps = tSteps = null; expTimes = gains = null; detectorOffsets = null; channelNames = null; detectorModels = voltages = null; exWaves = null; activeDetector = null; immersions = corrections = null; magnification = null; objectiveModels = null; posX = posY = posZ = null; refractiveIndex = null; cutIns = cutOuts = filterModels = null; timestamps = null; laserWavelength = laserIntensity = null; imageROIs = null; alternateCenter = false; imageNames = null; acquiredDate = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); offsets = new Vector<Long>(); in.order(true); // read the header LOGGER.info("Reading header"); byte checkOne = in.readByte(); in.skipBytes(2); byte checkTwo = in.readByte(); if (checkOne != LIF_MAGIC_BYTE && checkTwo != LIF_MAGIC_BYTE) { throw new FormatException(id + " is not a valid Leica LIF file"); } in.skipBytes(4); // read and parse the XML description if (in.read() != LIF_MEMORY_BYTE) { throw new FormatException("Invalid XML description"); } // number of Unicode characters in the XML block int nc = in.readInt(); String xml = DataTools.stripString(in.readString(nc * 2)); LOGGER.info("Finding image offsets"); while (in.getFilePointer() < in.length()) { LOGGER.debug("Looking for a block at {}; {} blocks read", in.getFilePointer(), offsets.size()); int check = in.readInt(); if (check != LIF_MAGIC_BYTE) { throw new FormatException("Invalid Memory Block: found magic bytes " + check + ", expected " + LIF_MAGIC_BYTE); } in.skipBytes(4); check = in.read(); if (check != LIF_MEMORY_BYTE) { throw new FormatException("Invalid Memory Description: found magic " + "byte " + check + ", expected " + LIF_MEMORY_BYTE); } long blockLength = in.readInt(); if (in.read() != LIF_MEMORY_BYTE) { in.seek(in.getFilePointer() - 5); blockLength = in.readLong(); check = in.read(); if (check != LIF_MEMORY_BYTE) { throw new FormatException("Invalid Memory Description: found magic " + "byte " + check + ", expected " + LIF_MEMORY_BYTE); } } int descrLength = in.readInt() * 2; if (blockLength > 0) { offsets.add(new Long(in.getFilePointer() + descrLength)); } in.seek(in.getFilePointer() + descrLength + blockLength); } initMetadata(xml); xml = null; // correct offsets, if necessary if (offsets.size() > getSeriesCount()) { Long[] storedOffsets = offsets.toArray(new Long[offsets.size()]); offsets.clear(); int index = 0; for (int i=0; i<getSeriesCount(); i++) { setSeries(i); long nBytes = (long) FormatTools.getPlaneSize(this) * getImageCount(); long start = storedOffsets[index]; long end = index == storedOffsets.length - 1 ? in.length() : storedOffsets[index + 1]; while (end - start < nBytes && ((end - start) / nBytes) != 1) { index++; start = storedOffsets[index]; end = index == storedOffsets.length - 1 ? in.length() : storedOffsets[index + 1]; } offsets.add(storedOffsets[index]); index++; } setSeries(0); } } // -- Helper methods -- /** Parses a string of XML and puts the values in a Hashtable. */ private void initMetadata(String xml) throws FormatException, IOException { IMetadata omexml = null; try { ServiceFactory factory = new ServiceFactory(); OMEXMLService service = factory.getInstance(OMEXMLService.class); omexml = service.createOMEXMLMetadata(); } catch (DependencyException exc) { throw new FormatException("Could not create OME-XML store.", exc); } catch (ServiceException exc) { throw new FormatException("Could not create OME-XML store.", exc); } MetadataStore store = makeFilterMetadata(); MetadataLevel level = getMetadataOptions().getMetadataLevel(); // the XML blocks stored in a LIF file are invalid, // because they don't have a root node xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml + "</LEICA>"; xml = XMLTools.sanitizeXML(xml); translateMetadata(getMetadataRoot(xml)); for (int i=0; i<imageNames.length; i++) { setSeries(i); addSeriesMeta("Image name", imageNames[i]); } setSeries(0); // set up mapping to rearrange channels // for instance, the green channel may be #0, and the red channel may be #1 realChannel = new int[getSeriesCount()][]; int nextLut = 0; for (int i=0; i<getSeriesCount(); i++) { realChannel[i] = new int[core[i].sizeC]; for (int q=0; q<core[i].sizeC; q++) { String lut = lutNames.get(nextLut++).toLowerCase(); if (!CHANNEL_PRIORITIES.containsKey(lut)) lut = ""; realChannel[i][q] = CHANNEL_PRIORITIES.get(lut).intValue(); } int[] sorted = new int[core[i].sizeC]; Arrays.fill(sorted, -1); for (int q=0; q<sorted.length; q++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<core[i].sizeC; n++) { if (realChannel[i][n] < min && !DataTools.containsValue(sorted, n)) { min = realChannel[i][n]; minIndex = n; } } sorted[q] = minIndex; } } MetadataTools.populatePixels(store, this, true, false); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); String instrumentID = MetadataTools.createLSID("Instrument", i); store.setInstrumentID(instrumentID, i); store.setMicroscopeModel(microscopeModels[i], i); store.setMicroscopeType(getMicroscopeType("Unknown"), i); String objectiveID = MetadataTools.createLSID("Objective", i, 0); store.setObjectiveID(objectiveID, i, 0); store.setObjectiveLensNA(lensNA[i], i, 0); store.setObjectiveSerialNumber(serialNumber[i], i, 0); if (magnification[i] != null && magnification[i] > 0) { store.setObjectiveNominalMagnification( new PositiveInteger(magnification[i]), i, 0); } store.setObjectiveImmersion(getImmersion(immersions[i]), i, 0); store.setObjectiveCorrection(getCorrection(corrections[i]), i, 0); store.setObjectiveModel(objectiveModels[i], i, 0); if (cutIns[i] != null) { for (int filter=0; filter<cutIns[i].size(); filter++) { String filterID = MetadataTools.createLSID("Filter", i, filter); store.setFilterID(filterID, i, filter); if (filter < filterModels[i].size()) { store.setFilterModel( (String) filterModels[i].get(filter), i, filter); } int channel = filter - (cutIns[i].size() - getEffectiveSizeC()); if (channel >= 0 && channel < getEffectiveSizeC()) { store.setLightPathEmissionFilterRef(filterID, i, channel, 0); } store.setTransmittanceRangeCutIn( (PositiveInteger) cutIns[i].get(filter), i, filter); store.setTransmittanceRangeCutOut( (PositiveInteger) cutOuts[i].get(filter), i, filter); } } Vector lasers = laserWavelength[i]; Vector laserIntensities = laserIntensity[i]; int nextChannel = getEffectiveSizeC() - 1; if (lasers != null) { for (int laser=0; laser<lasers.size(); laser++) { String id = MetadataTools.createLSID("LightSource", i, laser); store.setLaserID(id, i, laser); store.setLaserType(LaserType.OTHER, i, laser); store.setLaserLaserMedium(LaserMedium.OTHER, i, laser); Integer wavelength = (Integer) lasers.get(laser); if (wavelength > 0) { store.setLaserWavelength(new PositiveInteger(wavelength), i, laser); } if (laser < laserIntensities.size()) { double intensity = (Double) laserIntensities.get(laser); if (intensity < 100 && nextChannel >= 0 && wavelength != 0) { store.setChannelLightSourceSettingsID(id, i, nextChannel); store.setChannelLightSourceSettingsAttenuation( new PercentFraction((float) intensity / 100f), i, nextChannel); store.setChannelExcitationWavelength( new PositiveInteger(wavelength), i, nextChannel); nextChannel } } } } store.setImageInstrumentRef(instrumentID, i); store.setImageObjectiveSettingsID(objectiveID, i); store.setImageObjectiveSettingsRefractiveIndex(refractiveIndex[i], i); store.setImageDescription(descriptions[i], i); if (acquiredDate[i] > 0) { store.setImageAcquiredDate(DateTools.convertDate( (long) (acquiredDate[i] * 1000), DateTools.COBOL), i); } store.setImageName(imageNames[i].trim(), i); store.setPixelsPhysicalSizeX(physicalSizeXs.get(i), i); store.setPixelsPhysicalSizeY(physicalSizeYs.get(i), i); store.setPixelsPhysicalSizeZ(zSteps[i], i); store.setPixelsTimeIncrement(tSteps[i], i); Vector detectors = detectorModels[i]; if (detectors != null) { nextChannel = 0; for (int detector=0; detector<detectors.size(); detector++) { String detectorID = MetadataTools.createLSID("Detector", i, detector); store.setDetectorID(detectorID, i, detector); store.setDetectorModel((String) detectors.get(detector), i, detector); store.setDetectorZoom(zooms[i], i, detector); store.setDetectorType(DetectorType.PMT, i, detector); if (voltages[i] != null && detector < voltages[i].size()) { store.setDetectorVoltage( (Double) voltages[i].get(detector), i, detector); } if (activeDetector[i] != null) { if (detector < activeDetector[i].size() && (Boolean) activeDetector[i].get(detector) && detectorOffsets[i] != null && nextChannel < detectorOffsets[i].size()) { store.setDetectorOffset( (Double) detectorOffsets[i].get(nextChannel++), i, detector); } } } } Vector activeDetectors = activeDetector[i]; int nextDetector = 0; for (int c=0; c<getEffectiveSizeC(); c++) { if (activeDetectors != null) { while (nextDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextDetector)) { nextDetector++; } if (nextDetector < activeDetectors.size()) { String detectorID = MetadataTools.createLSID("Detector", i, nextDetector); store.setDetectorSettingsID(detectorID, i, c); nextDetector++; if (detectorOffsets[i] != null && c < detectorOffsets[i].size()) { store.setDetectorSettingsOffset( (Double) detectorOffsets[i].get(c), i, c); } if (gains[i] != null) { store.setDetectorSettingsGain(gains[i][c], i, c); } } } if (channelNames[i] != null) { store.setChannelName(channelNames[i][c], i, c); } store.setChannelPinholeSize(pinholes[i], i, c); if (exWaves[i] != null && exWaves[i][c] != null && exWaves[i][c] > 0) { store.setChannelExcitationWavelength( new PositiveInteger(exWaves[i][c]), i, c); } if (expTimes[i] != null) { store.setPlaneExposureTime(expTimes[i][c], i, c); } } for (int image=0; image<getImageCount(); image++) { store.setPlanePositionX(posX[i], i, image); store.setPlanePositionY(posY[i], i, image); store.setPlanePositionZ(posZ[i], i, image); if (timestamps[i] != null) { double timestamp = timestamps[i][image]; if (timestamps[i][0] == acquiredDate[i]) { timestamp -= acquiredDate[i]; } store.setPlaneDeltaT(timestamp, i, image); } } if (imageROIs[i] != null) { for (int roi=0; roi<imageROIs[i].length; roi++) { if (imageROIs[i][roi] != null) { imageROIs[i][roi].storeROI(store, i, roi); } } } } } private Element getMetadataRoot(String xml) throws FormatException, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); ByteArrayInputStream s = new ByteArrayInputStream(xml.getBytes()); Element root = parser.parse(s).getDocumentElement(); s.close(); return root; } catch (ParserConfigurationException e) { throw new FormatException(e); } catch (SAXException e) { throw new FormatException(e); } } private void translateMetadata(Element root) throws FormatException { Element realRoot = (Element) root.getChildNodes().item(0); NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master"); if (toPrune != null) { for (int i=0; i<toPrune.getLength(); i++) { Element prune = (Element) toPrune.item(i); Element parent = (Element) prune.getParentNode(); parent.removeChild(prune); } } NodeList imageNodes = getNodes(realRoot, "Image"); core = new CoreMetadata[imageNodes.getLength()]; acquiredDate = new double[imageNodes.getLength()]; descriptions = new String[imageNodes.getLength()]; laserWavelength = new Vector[imageNodes.getLength()]; laserIntensity = new Vector[imageNodes.getLength()]; timestamps = new double[imageNodes.getLength()][]; activeDetector = new Vector[imageNodes.getLength()]; voltages = new Vector[imageNodes.getLength()]; detectorOffsets = new Vector[imageNodes.getLength()]; serialNumber = new String[imageNodes.getLength()]; lensNA = new Double[imageNodes.getLength()]; magnification = new Integer[imageNodes.getLength()]; immersions = new String[imageNodes.getLength()]; corrections = new String[imageNodes.getLength()]; objectiveModels = new String[imageNodes.getLength()]; posX = new Double[imageNodes.getLength()]; posY = new Double[imageNodes.getLength()]; posZ = new Double[imageNodes.getLength()]; refractiveIndex = new Double[imageNodes.getLength()]; cutIns = new Vector[imageNodes.getLength()]; cutOuts = new Vector[imageNodes.getLength()]; filterModels = new Vector[imageNodes.getLength()]; microscopeModels = new String[imageNodes.getLength()]; detectorModels = new Vector[imageNodes.getLength()]; zSteps = new Double[imageNodes.getLength()]; tSteps = new Double[imageNodes.getLength()]; pinholes = new Double[imageNodes.getLength()]; zooms = new Double[imageNodes.getLength()]; expTimes = new Double[imageNodes.getLength()][]; gains = new Double[imageNodes.getLength()][]; channelNames = new String[imageNodes.getLength()][]; exWaves = new Integer[imageNodes.getLength()][]; imageROIs = new ROI[imageNodes.getLength()][]; imageNames = new String[imageNodes.getLength()]; for (int i=0; i<imageNodes.getLength(); i++) { Element image = (Element) imageNodes.item(i); setSeries(i); translateImageNames(image, i); translateImageNodes(image, i); translateAttachmentNodes(image, i); translateScannerSettings(image, i); translateFilterSettings(image, i); translateTimestamps(image, i); translateLaserLines(image, i); translateROIs(image, i); translateSingleROIs(image, i); translateDetectors(image, i); Stack<String> nameStack = new Stack<String>(); HashMap<String, Integer> indexes = new HashMap<String, Integer>(); populateOriginalMetadata(image, nameStack, indexes); indexes.clear(); } setSeries(0); } private void populateOriginalMetadata(Element root, Stack<String> nameStack, HashMap<String, Integer> indexes) { String name = root.getNodeName(); if (root.hasAttributes() && !name.equals("Element") && !name.equals("Attachment") && !name.equals("LMSDataContainerHeader")) { nameStack.push(name); String suffix = root.getAttribute("Identifier"); String value = root.getAttribute("Variant"); if (suffix == null || suffix.trim().length() == 0) { suffix = root.getAttribute("Description"); } StringBuffer key = new StringBuffer(); for (String k : nameStack) { key.append(k); key.append("|"); } if (suffix != null && value != null && suffix.length() > 0 && value.length() > 0 && !suffix.equals("HighInteger") && !suffix.equals("LowInteger")) { Integer i = indexes.get(key.toString() + suffix); String storedKey = key.toString() + suffix + " " + (i == null ? 0 : i); indexes.put(key.toString() + suffix, i == null ? 1 : i + 1); addSeriesMeta(storedKey, value); } else { NamedNodeMap attributes = root.getAttributes(); for (int i=0; i<attributes.getLength(); i++) { Attr attr = (Attr) attributes.item(i); if (!attr.getName().equals("HighInteger") && !attr.getName().equals("LowInteger")) { Integer index = indexes.get(key.toString() + attr.getName()); if (index == null) { index = 0; } String storedKey = key.toString() + attr.getName() + " " + index; indexes.put(key.toString() + attr.getName(), index + 1); addSeriesMeta(storedKey, attr.getValue()); } } } } NodeList children = root.getChildNodes(); for (int i=0; i<children.getLength(); i++) { Object child = children.item(i); if (child instanceof Element) { populateOriginalMetadata((Element) child, nameStack, indexes); } } if (root.hasAttributes() && !name.equals("Element") && !name.equals("Attachment") && !name.equals("LMSDataContainerHeader")) { nameStack.pop(); } } private void translateImageNames(Element imageNode, int image) { Vector<String> names = new Vector<String>(); Element parent = imageNode; while (true) { parent = (Element) parent.getParentNode(); if (parent == null || parent.getNodeName().equals("LEICA")) { break; } if (parent.getNodeName().equals("Element")) { names.add(parent.getAttribute("Name")); } } imageNames[image] = ""; for (int i=names.size() - 2; i>=0; i imageNames[image] += names.get(i); if (i > 0) imageNames[image] += "/"; } } private void translateDetectors(Element imageNode, int image) throws FormatException { NodeList definitions = getNodes(imageNode, "ATLConfocalSettingDefinition"); if (definitions == null) return; int nextChannel = 0; for (int definition=0; definition<definitions.getLength(); definition++) { Element definitionNode = (Element) definitions.item(definition); NodeList detectors = getNodes(definitionNode, "Detector"); if (detectors == null) return; for (int d=0; d<detectors.getLength(); d++) { Element detector = (Element) detectors.item(d); NodeList multibands = getNodes(definitionNode, "MultiBand"); String v = detector.getAttribute("Gain"); Double gain = v == null || v.trim().length() == 0 ? null : new Double(v); v = detector.getAttribute("Offset"); Double offset = v == null || v.trim().length() == 0 ? null : new Double(v); boolean active = "1".equals(detector.getAttribute("IsActive")); if (active) { String c = detector.getAttribute("Channel"); int channel = c == null ? 0 : Integer.parseInt(c); Element multiband = null; if (multibands != null) { for (int i=0; i<multibands.getLength(); i++) { Element mb = (Element) multibands.item(i); if (channel == Integer.parseInt(mb.getAttribute("Channel"))) { multiband = mb; break; } } } if (multiband != null) { if (nextChannel < channelNames[image].length) { channelNames[image][nextChannel] = multiband.getAttribute("DyeName"); } double cutIn = new Double(multiband.getAttribute("LeftWorld")); double cutOut = new Double(multiband.getAttribute("RightWorld")); cutIns[image].add(new PositiveInteger((int) Math.round(cutIn))); cutOuts[image].add(new PositiveInteger((int) Math.round(cutOut))); } if (nextChannel < getEffectiveSizeC()) { gains[image][nextChannel] = gain; detectorOffsets[image].add(offset); } nextChannel++; } if (active) { detectorModels[image].add(""); activeDetector[image].add(active); } } } } private void translateROIs(Element imageNode, int image) throws FormatException { NodeList rois = getNodes(imageNode, "Annotation"); if (rois == null) return; imageROIs[image] = new ROI[rois.getLength()]; for (int r=0; r<rois.getLength(); r++) { Element roiNode = (Element) rois.item(r); ROI roi = new ROI(); String type = roiNode.getAttribute("type"); if (type != null) { roi.type = Integer.parseInt(type); } String color = roiNode.getAttribute("color"); if (color != null) { roi.color = Long.parseLong(color); } roi.name = roiNode.getAttribute("name"); roi.fontName = roiNode.getAttribute("fontName"); roi.fontSize = roiNode.getAttribute("fontSize"); roi.transX = parseDouble(roiNode.getAttribute("transTransX")); roi.transY = parseDouble(roiNode.getAttribute("transTransY")); roi.scaleX = parseDouble(roiNode.getAttribute("transScalingX")); roi.scaleY = parseDouble(roiNode.getAttribute("transScalingY")); roi.rotation = parseDouble(roiNode.getAttribute("transRotation")); String linewidth = roiNode.getAttribute("linewidth"); if (linewidth != null) { try { roi.linewidth = Integer.parseInt(linewidth); } catch (NumberFormatException e) { } } roi.text = roiNode.getAttribute("text"); NodeList vertices = getNodes(roiNode, "Vertex"); for (int v=0; v<vertices.getLength(); v++) { Element vertex = (Element) vertices.item(v); String xx = vertex.getAttribute("x"); String yy = vertex.getAttribute("y"); if (xx != null) { roi.x.add(parseDouble(xx)); } if (yy != null) { roi.y.add(parseDouble(yy)); } } imageROIs[image][r] = roi; if (getNodes(imageNode, "ROI") != null) { alternateCenter = true; } } } private void translateSingleROIs(Element imageNode, int image) throws FormatException { if (imageROIs[image] != null) return; NodeList children = getNodes(imageNode, "ROI"); if (children == null) return; children = getNodes((Element) children.item(0), "Children"); if (children == null) return; children = getNodes((Element) children.item(0), "Element"); if (children == null) return; imageROIs[image] = new ROI[children.getLength()]; for (int r=0; r<children.getLength(); r++) { NodeList rois = getNodes((Element) children.item(r), "ROISingle"); Element roiNode = (Element) rois.item(0); ROI roi = new ROI(); String type = roiNode.getAttribute("RoiType"); if (type != null) { roi.type = Integer.parseInt(type); } String color = roiNode.getAttribute("Color"); if (color != null) { roi.color = Long.parseLong(color); } Element parent = (Element) roiNode.getParentNode(); parent = (Element) parent.getParentNode(); roi.name = parent.getAttribute("Name"); NodeList vertices = getNodes(roiNode, "P"); double sizeX = physicalSizeXs.get(image); double sizeY = physicalSizeYs.get(image); for (int v=0; v<vertices.getLength(); v++) { Element vertex = (Element) vertices.item(v); String xx = vertex.getAttribute("X"); String yy = vertex.getAttribute("Y"); if (xx != null) { roi.x.add(parseDouble(xx) / sizeX); } if (yy != null) { roi.y.add(parseDouble(yy) / sizeY); } } Element transform = (Element) getNodes(roiNode, "Transformation").item(0); roi.rotation = parseDouble(transform.getAttribute("Rotation")); Element scaling = (Element) getNodes(transform, "Scaling").item(0); roi.scaleX = parseDouble(scaling.getAttribute("XScale")); roi.scaleY = parseDouble(scaling.getAttribute("YScale")); Element translation = (Element) getNodes(transform, "Translation").item(0); roi.transX = parseDouble(translation.getAttribute("X")) / sizeX; roi.transY = parseDouble(translation.getAttribute("Y")) / sizeY; imageROIs[image][r] = roi; } } private void translateLaserLines(Element imageNode, int image) throws FormatException { NodeList laserLines = getNodes(imageNode, "LaserLineSetting"); if (laserLines == null) return; laserWavelength[image] = new Vector<Integer>(); laserIntensity[image] = new Vector<Double>(); for (int laser=0; laser<laserLines.getLength(); laser++) { Element laserLine = (Element) laserLines.item(laser); String lineIndex = laserLine.getAttribute("LineIndex"); String qual = laserLine.getAttribute("Qualifier"); int index = lineIndex == null ? 0 : Integer.parseInt(lineIndex); int qualifier = qual == null ? 0: Integer.parseInt(qual); index += (2 - (qualifier / 10)); if (index < 0) index = 0; Integer wavelength = new Integer(laserLine.getAttribute("LaserLine")); if (index < laserWavelength[image].size()) { laserWavelength[image].setElementAt(wavelength, index); } else { for (int i=laserWavelength[image].size(); i<index; i++) { laserWavelength[image].add(new Integer(0)); } laserWavelength[image].add(wavelength); } String intensity = laserLine.getAttribute("IntensityDev"); double realIntensity = intensity == null ? 0d : new Double(intensity); if (realIntensity > 0) { realIntensity = 100d - realIntensity; if (index < laserIntensity[image].size()) { laserIntensity[image].setElementAt(realIntensity, index); } else { for (int i=laserIntensity[image].size(); i<index; i++) { laserIntensity[image].add(new Double(0)); } laserIntensity[image].add(realIntensity); } } } } private void translateTimestamps(Element imageNode, int image) throws FormatException { NodeList timestampNodes = getNodes(imageNode, "TimeStamp"); if (timestampNodes == null) return; timestamps[image] = new double[getImageCount()]; if (timestampNodes != null) { for (int stamp=0; stamp<timestampNodes.getLength(); stamp++) { if (stamp < getImageCount()) { Element timestamp = (Element) timestampNodes.item(stamp); String stampHigh = timestamp.getAttribute("HighInteger"); String stampLow = timestamp.getAttribute("LowInteger"); long high = stampHigh == null ? 0 : Long.parseLong(stampHigh); long low = stampLow == null ? 0 : Long.parseLong(stampLow); long ms = DateTools.getMillisFromTicks(high, low); timestamps[image][stamp] = ms / 1000.0; } } } acquiredDate[image] = timestamps[image][0]; NodeList relTimestampNodes = getNodes(imageNode, "RelTimeStamp"); if (relTimestampNodes != null) { for (int stamp=0; stamp<relTimestampNodes.getLength(); stamp++) { if (stamp < getImageCount()) { Element timestamp = (Element) relTimestampNodes.item(stamp); timestamps[image][stamp] = new Double(timestamp.getAttribute("Time")); } } } } private void translateFilterSettings(Element imageNode, int image) throws FormatException { NodeList filterSettings = getNodes(imageNode, "FilterSettingRecord"); if (filterSettings == null) return; activeDetector[image] = new Vector<Boolean>(); voltages[image] = new Vector<Double>(); detectorOffsets[image] = new Vector<Double>(); cutIns[image] = new Vector<PositiveInteger>(); cutOuts[image] = new Vector<PositiveInteger>(); filterModels[image] = new Vector<String>(); for (int i=0; i<filterSettings.getLength(); i++) { Element filterSetting = (Element) filterSettings.item(i); String object = filterSetting.getAttribute("ObjectName"); String attribute = filterSetting.getAttribute("Attribute"); String objectClass = filterSetting.getAttribute("ClassName"); String variant = filterSetting.getAttribute("Variant"); if (attribute.equals("NumericalAperture")) { lensNA[image] = new Double(variant); } else if (attribute.equals("OrderNumber")) { serialNumber[image] = variant; } else if (objectClass.equals("CDetectionUnit")) { if (attribute.equals("State")) { int channel = getChannelIndex(filterSetting); if (channel < 0) continue; detectorModels[image].add(object); activeDetector[image].add(variant.equals("Active")); } else if (attribute.equals("HighVoltage")) { int channel = getChannelIndex(filterSetting); if (channel < 0) continue; if (channel < voltages[image].size()) { voltages[image].setElementAt(new Double(variant), channel); } else { while (channel > voltages[image].size()) { voltages[image].add(new Double(0)); } voltages[image].add(new Double(variant)); } } else if (attribute.equals("VideoOffset")) { int channel = getChannelIndex(filterSetting); if (channel < 0) continue; detectorOffsets[image].add(new Double(variant)); } } else if (attribute.equals("Objective")) { StringTokenizer tokens = new StringTokenizer(variant, " "); boolean foundMag = false; StringBuffer model = new StringBuffer(); while (!foundMag) { String token = tokens.nextToken(); int x = token.indexOf("x"); if (x != -1) { foundMag = true; int mag = (int) Double.parseDouble(token.substring(0, x)); String na = token.substring(x + 1); magnification[image] = mag; lensNA[image] = new Double(na); } else { model.append(token); model.append(" "); } } String immersion = "Other"; if (tokens.hasMoreTokens()) { immersion = tokens.nextToken(); if (immersion == null || immersion.trim().equals("")) { immersion = "Other"; } } immersions[image] = immersion; String correction = "Other"; if (tokens.hasMoreTokens()) { correction = tokens.nextToken(); if (correction == null || correction.trim().equals("")) { correction = "Other"; } } corrections[image] = correction; objectiveModels[image] = model.toString().trim(); } else if (attribute.equals("RefractionIndex")) { refractiveIndex[image] = new Double(variant); } else if (attribute.equals("XPos")) { posX[image] = new Double(variant); } else if (attribute.equals("YPos")) { posY[image] = new Double(variant); } else if (attribute.equals("ZPos")) { posZ[image] = new Double(variant); } else if (objectClass.equals("CSpectrophotometerUnit")) { Integer v = null; try { v = new Integer((int) Double.parseDouble(variant)); } catch (NumberFormatException e) { } String description = filterSetting.getAttribute("Description"); if (description.endsWith("(left)")) { filterModels[image].add(object); if (v != null) { cutIns[image].add(new PositiveInteger(v)); } } else if (description.endsWith("(right)")) { if (v != null) { cutOuts[image].add(new PositiveInteger(v)); } } } } } private void translateScannerSettings(Element imageNode, int image) throws FormatException { NodeList scannerSettings = getNodes(imageNode, "ScannerSettingRecord"); if (scannerSettings == null) return; expTimes[image] = new Double[getEffectiveSizeC()]; gains[image] = new Double[getEffectiveSizeC()]; channelNames[image] = new String[getEffectiveSizeC()]; exWaves[image] = new Integer[getEffectiveSizeC()]; detectorModels[image] = new Vector<String>(); for (int i=0; i<scannerSettings.getLength(); i++) { Element scannerSetting = (Element) scannerSettings.item(i); String id = scannerSetting.getAttribute("Identifier"); if (id == null) id = ""; String suffix = scannerSetting.getAttribute("Identifier"); String value = scannerSetting.getAttribute("Variant"); if (id.equals("SystemType")) { microscopeModels[image] = value; } else if (id.equals("dblPinhole")) { pinholes[image] = Double.parseDouble(value) * 1000000; } else if (id.equals("dblZoom")) { zooms[image] = new Double(value); } else if (id.equals("dblStepSize")) { zSteps[image] = Double.parseDouble(value) * 1000000; } else if (id.equals("nDelayTime_s")) { tSteps[image] = new Double(value); } else if (id.equals("CameraName")) { detectorModels[image].add(value); } else if (id.indexOf("WFC") == 1) { int c = 0; try { c = Integer.parseInt(id.replaceAll("\\D", "")); } catch (NumberFormatException e) { } if (c < 0 || c >= getEffectiveSizeC()) { continue; } if (id.endsWith("ExposureTime")) { expTimes[image][c] = new Double(value); } else if (id.endsWith("Gain")) { gains[image][c] = new Double(value); } else if (id.endsWith("WaveLength")) { Integer exWave = new Integer(value); if (exWave > 0) { exWaves[image][c] = exWave; } } // NB: "UesrDefName" is not a typo. else if (id.endsWith("UesrDefName") && !value.equals("None")) { channelNames[image][c] = value; } } } } private void translateAttachmentNodes(Element imageNode, int image) throws FormatException { NodeList attachmentNodes = getNodes(imageNode, "Attachment"); if (attachmentNodes == null) return; for (int i=0; i<attachmentNodes.getLength(); i++) { Element attachment = (Element) attachmentNodes.item(i); if ("ContextDescription".equals(attachment.getAttribute("Name"))) { descriptions[image] = attachment.getAttribute("Content"); } } } private void translateImageNodes(Element imageNode, int i) throws FormatException { core[i] = new CoreMetadata(); core[i].orderCertain = true; core[i].metadataComplete = true; core[i].littleEndian = true; core[i].falseColor = true; NodeList channels = getChannelDescriptionNodes(imageNode); NodeList dimensions = getDimensionDescriptionNodes(imageNode); HashMap<Long, String> bytesPerAxis = new HashMap<Long, String>(); Double physicalSizeX = null; Double physicalSizeY = null; core[i].sizeC = channels.getLength(); for (int ch=0; ch<channels.getLength(); ch++) { Element channel = (Element) channels.item(ch); lutNames.add(channel.getAttribute("LUTName")); String bytesInc = channel.getAttribute("BytesInc"); long bytes = bytesInc == null ? 0 : Long.parseLong(bytesInc); if (bytes > 0) { bytesPerAxis.put(bytes, "C"); } } int extras = 1; for (int dim=0; dim<dimensions.getLength(); dim++) { Element dimension = (Element) dimensions.item(dim); int id = Integer.parseInt(dimension.getAttribute("DimID")); int len = Integer.parseInt(dimension.getAttribute("NumberOfElements")); long nBytes = Long.parseLong(dimension.getAttribute("BytesInc")); Double physicalLen = new Double(dimension.getAttribute("Length")); String unit = dimension.getAttribute("Unit"); physicalLen /= len; if (unit.equals("Ks")) { physicalLen /= 1000; } else if (unit.equals("m")) { physicalLen *= 1000000; } switch (id) { case 1: // X axis core[i].sizeX = len; core[i].rgb = (nBytes % 3) == 0; if (core[i].rgb) nBytes /= 3; core[i].pixelType = FormatTools.pixelTypeFromBytes((int) nBytes, false, true); physicalSizeX = physicalLen; break; case 2: // Y axis if (core[i].sizeY != 0) { if (core[i].sizeZ == 1) { core[i].sizeZ = len; bytesPerAxis.put(nBytes, "Z"); } else if (core[i].sizeT == 1) { core[i].sizeT = len; bytesPerAxis.put(nBytes, "T"); } } else { core[i].sizeY = len; physicalSizeY = physicalLen; } break; case 3: // Z axis if (core[i].sizeY == 0) { // XZ scan - swap Y and Z core[i].sizeY = len; core[i].sizeZ = 1; bytesPerAxis.put(nBytes, "Y"); physicalSizeY = physicalLen; } else { core[i].sizeZ = len; bytesPerAxis.put(nBytes, "Z"); } break; case 4: // T axis if (core[i].sizeY == 0) { // XT scan - swap Y and T core[i].sizeY = len; core[i].sizeT = 1; bytesPerAxis.put(nBytes, "Y"); physicalSizeY = physicalLen; } else { core[i].sizeT = len; bytesPerAxis.put(nBytes, "T"); } break; default: extras *= len; } } physicalSizeXs.add(physicalSizeX); physicalSizeYs.add(physicalSizeY); if (extras > 1) { if (core[i].sizeZ == 1) core[i].sizeZ = extras; else { if (core[i].sizeT == 0) core[i].sizeT = extras; else core[i].sizeT *= extras; } } if (core[i].sizeC == 0) core[i].sizeC = 1; if (core[i].sizeZ == 0) core[i].sizeZ = 1; if (core[i].sizeT == 0) core[i].sizeT = 1; core[i].interleaved = core[i].rgb; core[i].indexed = !core[i].rgb; core[i].imageCount = core[i].sizeZ * core[i].sizeT; if (!core[i].rgb) core[i].imageCount *= core[i].sizeC; Long[] bytes = bytesPerAxis.keySet().toArray(new Long[0]); Arrays.sort(bytes); core[i].dimensionOrder = "XY"; for (Long nBytes : bytes) { String axis = bytesPerAxis.get(nBytes); if (core[i].dimensionOrder.indexOf(axis) == -1) { core[i].dimensionOrder += axis; } } if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } } private NodeList getNodes(Element root, String nodeName) { NodeList nodes = root.getElementsByTagName(nodeName); if (nodes.getLength() == 0) { NodeList children = root.getChildNodes(); for (int i=0; i<children.getLength(); i++) { Object child = children.item(i); if (child instanceof Element) { NodeList childNodes = getNodes((Element) child, nodeName); if (childNodes != null) { return childNodes; } } } return null; } else return nodes; } private Element getImageDescription(Element root) { return (Element) root.getElementsByTagName("ImageDescription").item(0); } private NodeList getChannelDescriptionNodes(Element root) { Element imageDescription = getImageDescription(root); Element channels = (Element) imageDescription.getElementsByTagName("Channels").item(0); return channels.getElementsByTagName("ChannelDescription"); } private NodeList getDimensionDescriptionNodes(Element root) { Element imageDescription = getImageDescription(root); Element channels = (Element) imageDescription.getElementsByTagName("Dimensions").item(0); return channels.getElementsByTagName("DimensionDescription"); } private int getChannelIndex(Element filterSetting) { String data = filterSetting.getAttribute("data"); if (data == null || data.equals("")) { data = filterSetting.getAttribute("Data"); } int channel = data == null || data.equals("") ? 0 : Integer.parseInt(data); if (channel < 0) return -1; return channel - 1; } // -- Helper class -- class ROI { // -- Constants -- public static final int TEXT = 512; public static final int SCALE_BAR = 8192; public static final int POLYGON = 32; public static final int RECTANGLE = 16; public static final int LINE = 256; public static final int ARROW = 2; // -- Fields -- public int type; public Vector<Double> x = new Vector<Double>(); public Vector<Double> y = new Vector<Double>(); // center point of the ROI public double transX, transY; // transformation parameters public double scaleX, scaleY; public double rotation; public long color; public int linewidth; public String text; public String fontName; public String fontSize; public String name; private boolean normalized = false; // -- ROI API methods -- public void storeROI(MetadataStore store, int series, int roi) { MetadataLevel level = getMetadataOptions().getMetadataLevel(); if (level == MetadataLevel.NO_OVERLAYS || level == MetadataLevel.MINIMUM) { return; } // keep in mind that vertices are given relative to the center // point of the ROI and the transX/transY values are relative to // the center point of the image store.setROIID(MetadataTools.createLSID("ROI", roi), roi); store.setTextID(MetadataTools.createLSID("Shape", roi, 0), roi, 0); if (text == null) { text = name; } store.setTextValue(text, roi, 0); if (fontSize != null) { try { int size = (int) Double.parseDouble(fontSize); store.setTextFontSize(new NonNegativeInteger(size), roi, 0); } catch (NumberFormatException e) { } } store.setTextStrokeWidth(new Double(linewidth), roi, 0); if (!normalized) normalize(); double cornerX = x.get(0).doubleValue(); double cornerY = y.get(0).doubleValue(); store.setTextX(cornerX, roi, 0); store.setTextY(cornerY, roi, 0); int centerX = (core[series].sizeX / 2) - 1; int centerY = (core[series].sizeY / 2) - 1; double roiX = centerX + transX; double roiY = centerY + transY; if (alternateCenter) { roiX = transX - 2 * cornerX; roiY = transY - 2 * cornerY; } // TODO : rotation/scaling not populated String shapeID = MetadataTools.createLSID("Shape", roi, 1); switch (type) { case POLYGON: StringBuffer points = new StringBuffer(); for (int i=0; i<x.size(); i++) { points.append(x.get(i).doubleValue() + roiX); points.append(","); points.append(y.get(i).doubleValue() + roiY); if (i < x.size() - 1) points.append(" "); } store.setPolylineID(shapeID, roi, 1); store.setPolylinePoints(points.toString(), roi, 1); store.setPolylineClosed(Boolean.TRUE, roi, 1); break; case TEXT: case RECTANGLE: store.setRectangleID(shapeID, roi, 1); store.setRectangleX(roiX - Math.abs(cornerX), roi, 1); store.setRectangleY(roiY - Math.abs(cornerY), roi, 1); double width = 2 * Math.abs(cornerX); double height = 2 * Math.abs(cornerY); store.setRectangleWidth(width, roi, 1); store.setRectangleHeight(height, roi, 1); break; case SCALE_BAR: case ARROW: case LINE: store.setLineID(shapeID, roi, 1); store.setLineX1(roiX + x.get(0), roi, 1); store.setLineY1(roiY + y.get(0), roi, 1); store.setLineX2(roiX + x.get(1), roi, 1); store.setLineY2(roiY + y.get(1), roi, 1); break; } } // -- Helper methods -- /** * Vertices and transformation values are not stored in pixel coordinates. * We need to convert them from physical coordinates to pixel coordinates * so that they can be stored in a MetadataStore. */ private void normalize() { if (normalized) return; // coordinates are in meters transX *= 1000000; transY *= 1000000; transX *= 1; transY *= 1; for (int i=0; i<x.size(); i++) { double coordinate = x.get(i).doubleValue() * 1000000; coordinate *= 1; x.setElementAt(coordinate, i); } for (int i=0; i<y.size(); i++) { double coordinate = y.get(i).doubleValue() * 1000000; coordinate *= 1; y.setElementAt(coordinate, i); } normalized = true; } } private double parseDouble(String number) { if (number != null) { number = number.replaceAll(",", "."); return Double.parseDouble(number); } return 0; } }
// LIFReader.java package loci.formats.in; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.common.xml.XMLTools; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.services.OMEXMLService; import ome.xml.model.Channel; import ome.xml.model.OME; import ome.xml.model.Pixels; public class LIFReader extends FormatReader { // -- Constants -- public static final byte LIF_MAGIC_BYTE = 0x70; public static final byte LIF_MEMORY_BYTE = 0x2a; private static final Hashtable<String, Integer> CHANNEL_PRIORITIES = createChannelPriorities(); private static Hashtable<String, Integer> createChannelPriorities() { Hashtable<String, Integer> h = new Hashtable<String, Integer>(); h.put("red", new Integer(0)); h.put("green", new Integer(1)); h.put("blue", new Integer(2)); h.put("cyan", new Integer(3)); h.put("magenta", new Integer(4)); h.put("yellow", new Integer(5)); h.put("black", new Integer(6)); h.put("gray", new Integer(7)); h.put("", new Integer(8)); return h; } private static final byte[][][] BYTE_LUTS = createByteLUTs(); private static byte[][][] createByteLUTs() { byte[][][] lut = new byte[9][3][256]; for (int i=0; i<256; i++) { // red lut[0][0][i] = (byte) (i & 0xff); // green lut[1][1][i] = (byte) (i & 0xff); // blue lut[2][2][i] = (byte) (i & 0xff); // cyan lut[3][1][i] = (byte) (i & 0xff); lut[3][2][i] = (byte) (i & 0xff); // magenta lut[4][0][i] = (byte) (i & 0xff); lut[4][2][i] = (byte) (i & 0xff); // yellow lut[5][0][i] = (byte) (i & 0xff); lut[5][1][i] = (byte) (i & 0xff); // gray lut[6][0][i] = (byte) (i & 0xff); lut[6][1][i] = (byte) (i & 0xff); lut[6][2][i] = (byte) (i & 0xff); lut[7][0][i] = (byte) (i & 0xff); lut[7][1][i] = (byte) (i & 0xff); lut[7][2][i] = (byte) (i & 0xff); lut[8][0][i] = (byte) (i & 0xff); lut[8][1][i] = (byte) (i & 0xff); lut[8][2][i] = (byte) (i & 0xff); } return lut; } private static final short[][][] SHORT_LUTS = createShortLUTs(); private static short[][][] createShortLUTs() { short[][][] lut = new short[9][3][65536]; for (int i=0; i<65536; i++) { // red lut[0][0][i] = (short) (i & 0xffff); // green lut[1][1][i] = (short) (i & 0xffff); // blue lut[2][2][i] = (short) (i & 0xffff); // cyan lut[3][1][i] = (short) (i & 0xffff); lut[3][2][i] = (short) (i & 0xffff); // magenta lut[4][0][i] = (short) (i & 0xffff); lut[4][2][i] = (short) (i & 0xffff); // yellow lut[5][0][i] = (short) (i & 0xffff); lut[5][1][i] = (short) (i & 0xffff); // gray lut[6][0][i] = (short) (i & 0xffff); lut[6][1][i] = (short) (i & 0xffff); lut[6][2][i] = (short) (i & 0xffff); lut[7][0][i] = (short) (i & 0xffff); lut[7][1][i] = (short) (i & 0xffff); lut[7][2][i] = (short) (i & 0xffff); lut[8][0][i] = (short) (i & 0xffff); lut[8][1][i] = (short) (i & 0xffff); lut[8][2][i] = (short) (i & 0xffff); } return lut; } // -- Fields -- /** Offsets to memory blocks, paired with their corresponding description. */ private Vector<Long> offsets; private int[][] realChannel; private int lastChannel = 0; // -- Constructor -- /** Constructs a new Leica LIF reader. */ public LIFReader() { super("Leica Image File Format", "lif"); domains = new String[] {FormatTools.LM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 1; if (!FormatTools.validStream(stream, blockLen, true)) return false; return stream.read() == LIF_MAGIC_BYTE; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT8 || !isIndexed()) return null; return lastChannel < BYTE_LUTS.length ? BYTE_LUTS[lastChannel] : null; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT16 || !isIndexed()) return null; return lastChannel < SHORT_LUTS.length ? SHORT_LUTS[lastChannel] : null; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (!isRGB()) { int[] pos = getZCTCoords(no); lastChannel = realChannel[series][pos[1]]; } long offset = offsets.get(series).longValue(); int bytes = FormatTools.getBytesPerPixel(getPixelType()); int bpp = bytes * getRGBChannelCount(); long planeSize = (long) getSizeX() * getSizeY() * bpp; long nextOffset = series + 1 < offsets.size() ? offsets.get(series + 1).longValue() : in.length(); int bytesToSkip = (int) (nextOffset - offset - planeSize * getImageCount()); bytesToSkip /= getSizeY(); if ((getSizeX() % 4) == 0) bytesToSkip = 0; in.seek(offset + planeSize * no); in.skipBytes(bytesToSkip * getSizeY() * no); if (bytesToSkip == 0) { readPlane(in, x, y, w, h, buf); } else { in.skipBytes(y * (getSizeX() * bpp + bytesToSkip)); for (int row=0; row<h; row++) { in.skipBytes(x * bpp); in.read(buf, row * w * bpp, w * bpp); in.skipBytes(bpp * (getSizeX() - w - x) + bytesToSkip); } } // color planes are stored in BGR order if (getRGBChannelCount() == 3) { ImageTools.bgrToRgb(buf, isInterleaved(), bytes, getRGBChannelCount()); } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { offsets = null; realChannel = null; lastChannel = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); offsets = new Vector<Long>(); in.order(true); // read the header LOGGER.info("Reading header"); byte checkOne = in.readByte(); in.skipBytes(2); byte checkTwo = in.readByte(); if (checkOne != LIF_MAGIC_BYTE && checkTwo != LIF_MAGIC_BYTE) { throw new FormatException(id + " is not a valid Leica LIF file"); } in.skipBytes(4); // read and parse the XML description if (in.read() != LIF_MEMORY_BYTE) { throw new FormatException("Invalid XML description"); } // number of Unicode characters in the XML block int nc = in.readInt(); String xml = DataTools.stripString(in.readString(nc * 2)); LOGGER.info("Finding image offsets"); while (in.getFilePointer() < in.length()) { LOGGER.debug("Looking for a block at {}; {} blocks read", in.getFilePointer(), offsets.size()); int check = in.readInt(); if (check != LIF_MAGIC_BYTE) { throw new FormatException("Invalid Memory Block: found magic bytes " + check + ", expected " + LIF_MAGIC_BYTE); } in.skipBytes(4); check = in.read(); if (check != LIF_MEMORY_BYTE) { throw new FormatException("Invalid Memory Description: found magic " + "byte " + check + ", expected " + LIF_MEMORY_BYTE); } long blockLength = in.readInt(); if (in.read() != LIF_MEMORY_BYTE) { in.seek(in.getFilePointer() - 5); blockLength = in.readLong(); check = in.read(); if (check != LIF_MEMORY_BYTE) { throw new FormatException("Invalid Memory Description: found magic " + "byte " + check + ", expected " + LIF_MEMORY_BYTE); } } int descrLength = in.readInt() * 2; if (blockLength > 0) { offsets.add(new Long(in.getFilePointer() + descrLength)); } in.seek(in.getFilePointer() + descrLength + blockLength); } initMetadata(xml); xml = null; } // -- Helper methods -- /** Parses a string of XML and puts the values in a Hashtable. */ private void initMetadata(String xml) throws FormatException, IOException { MetadataStore store = makeFilterMetadata(); MetadataLevel level = getMetadataOptions().getMetadataLevel(); LeicaHandler handler = new LeicaHandler(store, level); // the XML blocks stored in a LIF file are invalid, // because they don't have a root node xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml + "</LEICA>"; xml = XMLTools.sanitizeXML(xml); try { XMLTools.parseXML(xml, handler); } catch (IOException e) { } metadata = handler.getGlobalMetadata(); Vector<String> lutNames = handler.getLutNames(); core = handler.getCoreMetadata().toArray(new CoreMetadata[0]); // set up mapping to rearrange channels // for instance, the green channel may be #0, and the red channel may be #1 realChannel = new int[getSeriesCount()][]; int nextLut = 0; for (int i=0; i<getSeriesCount(); i++) { realChannel[i] = new int[core[i].sizeC]; for (int q=0; q<core[i].sizeC; q++) { String lut = lutNames.get(nextLut++).toLowerCase(); if (!CHANNEL_PRIORITIES.containsKey(lut)) lut = ""; realChannel[i][q] = CHANNEL_PRIORITIES.get(lut).intValue(); } int[] sorted = new int[core[i].sizeC]; Arrays.fill(sorted, -1); for (int q=0; q<sorted.length; q++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<core[i].sizeC; n++) { if (realChannel[i][n] < min && !DataTools.containsValue(sorted, n)) { min = realChannel[i][n]; minIndex = n; } } sorted[q] = minIndex; } } MetadataTools.populatePixels(store, this, true, false); // remove any Channels that do not have an ID OMEXMLService service = null; try { service = new ServiceFactory().getInstance(OMEXMLService.class); if (service.isOMEXMLRoot(store.getRoot())) { OME root = (OME) store.getRoot(); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); Pixels img = root.getImage(i).getPixels(); for (int c=0; c<img.sizeOfChannelList(); c++) { Channel channel = img.getChannel(c); if (channel.getID() == null || c >= getEffectiveSizeC()) { img.removeChannel(channel); } } } setSeries(0); } } catch (DependencyException e) { LOGGER.trace("Failed to remove channels", e); } } }
package ome.scifio.ics; import java.io.IOException; import ome.scifio.io.Location; import ome.scifio.AbstractParser; import ome.scifio.FormatException; import ome.scifio.SCIFIO; import ome.scifio.io.RandomAccessInputStream; /** * SCIFIO file format Parser for ICS images. * */ public class ICSParser extends AbstractParser<ICSMetadata> { // -- Constructor -- public ICSParser() { this(null); } public ICSParser(final SCIFIO ctx) { super(ctx, ICSMetadata.class); } // -- Parser API Methods -- /* @see Parser#parse(RandomAccessInputStream) */ @Override public ICSMetadata parse(final RandomAccessInputStream stream) throws IOException, FormatException { super.parse(stream); if (stream.getFileName() != null) findCompanion(stream.getFileName()); final RandomAccessInputStream reader = new RandomAccessInputStream(metadata.getIcsId()); reader.seek(0); reader.readString(ICSUtils.NL); String line = reader.readString(ICSUtils.NL); // Extracts the keys, value pairs from each line and inserts them into the ICSMetadata object while (line != null && !line.trim().equals("end") && reader.getFilePointer() < reader.length() - 1) { line = line.trim(); final String[] tokens = line.split("[ \t]"); final StringBuffer key = new StringBuffer(); for (int q = 0; q < tokens.length; q++) { tokens[q] = tokens[q].trim(); if (tokens[q].length() == 0) continue; boolean foundValue = true; for (int i = 0; i < ICSUtils.CATEGORIES.length; i++) { if (tokens[q].matches(ICSUtils.CATEGORIES[i])) { foundValue = false; break; } } if (!foundValue) { key.append(tokens[q]); key.append(" "); continue; } final StringBuffer value = new StringBuffer(tokens[q++]); for (; q < tokens.length; q++) { value.append(" "); value.append(tokens[q].trim()); } final String k = key.toString().trim().replaceAll("\t", " "); final String v = value.toString().trim(); addGlobalMeta(k, v); metadata.keyValPairs.put(k.toLowerCase(), v); } line = reader.readString(ICSUtils.NL); } reader.close(); if (metadata.versionTwo) { String s = in.readString(ICSUtils.NL); while (!s.trim().equals("end")) s = in.readString(ICSUtils.NL); } metadata.offset = in.getFilePointer(); metadata.hasInstrumentData = nullKeyCheck(new String[] { "history cube emm nm", "history cube exc nm", "history objective NA", "history stage xyzum", "history objective magnification", "history objective mag", "history objective WorkingDistance", "history objective type", "history objective", "history objective immersion"}); return metadata; } // -- Helper Methods -- /* Returns true if any of the keys in testKeys has a non-null value */ private boolean nullKeyCheck(final String[] testKeys) { for (final String key : testKeys) { if (metadata.get(key) != null) { return true; } } return false; } /* Finds the companion file (ICS and IDS are companions) */ private void findCompanion(final String id) throws IOException, FormatException { metadata.icsId = id; metadata.idsId = id; String icsId = id, idsId = id; final int dot = id.lastIndexOf("."); final String ext = dot < 0 ? "" : id.substring(dot + 1).toLowerCase(); if (ext.equals("ics")) { // convert C to D regardless of case final char[] c = idsId.toCharArray(); c[c.length - 2]++; idsId = new String(c); } else if (ext.equals("ids")) { // convert D to C regardless of case final char[] c = icsId.toCharArray(); c[c.length - 2] icsId = new String(c); } if (icsId == null) throw new FormatException("No ICS file found."); final Location icsFile = new Location(icsId); if (!icsFile.exists()) throw new FormatException("ICS file not found."); // check if we have a v2 ICS file - means there is no companion IDS file final RandomAccessInputStream f = new RandomAccessInputStream(icsId); if (f.readString(17).trim().equals("ics_version\t2.0")) { in = new RandomAccessInputStream(icsId); metadata.versionTwo = true; } else { if (idsId == null) throw new FormatException("No IDS file found."); final Location idsFile = new Location(idsId); if (!idsFile.exists()) throw new FormatException("IDS file not found."); //currentIdsId = idsId; metadata.idsId = idsId; in = new RandomAccessInputStream(idsId); } f.close(); } }
package org.kohsuke.stapler.interceptor; import java.io.IOException; import java.io.PrintWriter; import org.kohsuke.stapler.ForwardToView; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.InvocationTargetException; import java.util.ServiceLoader; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import javax.annotation.CheckForNull; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.verb.POST; /** * Requires the request to be a POST. * * <p> * When the current request has a non-matching HTTP method (such as 'GET'), this annotation * will send a failure response instead of searching for other matching web methods. * * @author Kohsuke Kawaguchi * @since 1.180 * @see POST */ @Retention(RUNTIME) @Target({METHOD,FIELD}) @InterceptorAnnotation(RequirePOST.Processor.class) public @interface RequirePOST { /** * Allows customizing the error page shown when an annotated method is called with the wrong HTTP method. */ interface ErrorCustomizer { /** * Return the {@link ForwardToView} showing a custom error page for {@link RequirePOST} annotated methods. This is * typically used to show a form with a "Try again using POST" button. * * <p>Implementations are looked up using {@link java.util.ServiceLoader}, the first implementation to return a non-null value will be used.</p> */ @CheckForNull ForwardToView getForwardView(); } public static class Processor extends Interceptor { @Override public Object invoke(StaplerRequest request, StaplerResponse response, Object instance, Object[] arguments) throws IllegalAccessException, InvocationTargetException, ServletException { if (!request.getMethod().equals("POST")) { for (ErrorCustomizer handler : ServiceLoader.load(ErrorCustomizer.class, request.getWebApp().getClassLoader())) { ForwardToView forwardToView = handler.getForwardView(); if (forwardToView != null) { throw new InvocationTargetException(forwardToView.with("requestURL", request.getRequestURLWithQueryString().toString())); } } throw new InvocationTargetException(new HttpResponses.HttpResponseException() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); rsp.addHeader("Allow", "POST"); rsp.setContentType("text/html"); PrintWriter w = rsp.getWriter(); w.println("<html><head><title>POST required</title></head><body>"); w.println("POST is required for " + target.getQualifiedName() + "<br>"); w.println("<form method='POST'><input type='submit' value='Try POSTing'></form>"); w.println("</body></html>"); } }); } return target.invoke(request, response, instance, arguments); } } }
package bbth.game; import android.app.Activity; import bbth.engine.core.Game; import bbth.engine.core.GameActivity; import bbth.engine.net.bluetooth.Bluetooth; import bbth.engine.net.simulation.LockStepProtocol; import bbth.game.BeatTrack.Song; public class BBTHGame extends Game { // This is the viewport width and height public static final float WIDTH = 320; public static final float HEIGHT = 530; public static final boolean DEBUG = true; /** * This is static because it would require a lot of changes otherwise :( */ public static boolean IS_SINGLE_PLAYER = DEBUG; public BBTHGame(Activity activity) { // currentScreen = new TitleScreen(null); // currentScreen = new BBTHAITest(this); // currentScreen = new MusicTestScreen(activity); // currentScreen = new NetworkTestScreen(); // currentScreen = new TransitionTest(); // currentScreen = new GameSetupScreen(); // currentScreen = new CombatTest(this); if (IS_SINGLE_PLAYER) { currentScreen = new InGameScreen(Team.SERVER, new Bluetooth( GameActivity.instance, new LockStepProtocol()), Song.DONKEY_KONG, new LockStepProtocol()); } else { currentScreen = new GameSetupScreen(); } } @Override public float getWidth() { return WIDTH; } @Override public float getHeight() { return HEIGHT; } }
package org.ocelotds.web; import org.ocelotds.core.SessionManager; import org.ocelotds.Constants; import org.ocelotds.configuration.OcelotRequestConfigurator; import org.ocelotds.core.services.CallServiceManager; import org.ocelotds.encoders.MessageToClientEncoder; import java.io.IOException; import org.ocelotds.messaging.MessageFromClient; import java.util.Map; import javax.inject.Inject; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.ocelotds.core.CDIBeanResolver; import org.ocelotds.logger.OcelotLogger; import org.slf4j.Logger; /** * WebSocket endpoint * * @author hhfrancois */ @ServerEndpoint(value = "/ocelot-endpoint", encoders = {MessageToClientEncoder.class}, configurator = OcelotRequestConfigurator.class) public class OcelotEndpoint { @Inject @OcelotLogger private Logger logger; @Inject private SessionManager sessionManager; @Inject private CallServiceManager callServiceManager; /** * A connection is open * * @param session * @param config * @throws IOException */ @OnOpen public void handleOpenConnexion(Session session, EndpointConfig config) throws IOException { Map<String, Object> configProperties = config.getUserProperties(); Map<String, Object> sessionProperties = session.getUserProperties(); // Get subject from config and set in session, only one time by connexion sessionProperties.put(Constants.SECURITY_CONTEXT, configProperties.get(Constants.SECURITY_CONTEXT)); sessionProperties.put(Constants.LOCALE, configProperties.get(Constants.LOCALE)); sessionProperties.put(Constants.PRINCIPAL, configProperties.get(Constants.PRINCIPAL)); } @OnError public void onError(Session session, Throwable t) { logger.error("Unknow error for session " + session.getId(), t); } /** * Close a session * * @param session * @param closeReason */ @OnClose public void handleClosedConnection(Session session, CloseReason closeReason) { logger.debug("Close connexion for session '{}' : '{}'", session.getId(), closeReason.getCloseCode()); if (session.isOpen()) { try { session.close(); } catch (IllegalStateException | IOException ex) { } getSessionManager().removeSessionToTopics(session); } } /** * A message is a call service request or subscribe/unsubscribe topic * * @param client * @param json */ @OnMessage public void receiveCommandMessage(Session client, String json) { MessageFromClient message = MessageFromClient.createFromJson(json); logger.debug("Receive call message '{}' for session '{}'", message.getId(), client.getId()); getCallServiceManager().sendMessageToClient(message, client); } SessionManager getSessionManager() { if (null == sessionManager) { sessionManager = getCDIBeanResolver().getBean(SessionManager.class); } return sessionManager; } CallServiceManager getCallServiceManager() { if (null == callServiceManager) { callServiceManager = getCDIBeanResolver().getBean(CallServiceManager.class); } return callServiceManager; } CDIBeanResolver getCDIBeanResolver() { return new CDIBeanResolver(); // Tomcat exploit } }
// Revision 1.1 1999-01-31 13:33:08+00 sm11td // Initial revision package Debrief.Wrappers; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.beans.IntrospectionException; import java.beans.MethodDescriptor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import Debrief.ReaderWriter.Replay.FormatTracks; import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeSetWrapper; import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeWrapper; import Debrief.Wrappers.Formatters.CoreFormatItemListener; import Debrief.Wrappers.Track.AbsoluteTMASegment; import Debrief.Wrappers.Track.CoreTMASegment; import Debrief.Wrappers.Track.PlanningSegment; import Debrief.Wrappers.Track.RelativeTMASegment; import Debrief.Wrappers.Track.SplittableLayer; import Debrief.Wrappers.Track.TrackSegment; import Debrief.Wrappers.Track.TrackWrapper_Support; import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter; import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList; import Debrief.Wrappers.Track.WormInHoleOffset; import MWC.GUI.BaseLayer; import MWC.GUI.CanvasType; import MWC.GUI.DynamicPlottable; import MWC.GUI.Editable; import MWC.GUI.FireExtended; import MWC.GUI.FireReformatted; import MWC.GUI.Layer; import MWC.GUI.Layer.ProvidesContiguousElements; import MWC.GUI.Layers; import MWC.GUI.Layers.INewItemListener; import MWC.GUI.Layers.NeedsToKnowAboutLayers; import MWC.GUI.MessageProvider; import MWC.GUI.PlainWrapper; import MWC.GUI.Plottable; import MWC.GUI.Canvas.CanvasTypeUtilities; import MWC.GUI.Properties.LineStylePropertyEditor; import MWC.GUI.Properties.TimeFrequencyPropertyEditor; import MWC.GUI.Shapes.DraggableItem; import MWC.GUI.Shapes.HasDraggableComponents; import MWC.GUI.Shapes.TextLabel; import MWC.GUI.Shapes.Symbols.Vessels.WorldScaledSym; import MWC.GenericData.HiResDate; import MWC.GenericData.TimePeriod; import MWC.GenericData.Watchable; import MWC.GenericData.WatchableList; import MWC.GenericData.WorldArea; import MWC.GenericData.WorldDistance; import MWC.GenericData.WorldDistance.ArrayLength; import MWC.GenericData.WorldLocation; import MWC.GenericData.WorldSpeed; import MWC.GenericData.WorldVector; import MWC.TacticalData.Fix; import MWC.Utilities.TextFormatting.FormatRNDateTime; /** * the TrackWrapper maintains the GUI and data attributes of the whole track iteself, but the * responsibility for the fixes within the track are demoted to the FixWrapper */ public class TrackWrapper extends MWC.GUI.PlainWrapper implements WatchableList, MWC.GUI.Layer, DraggableItem, HasDraggableComponents, ProvidesContiguousElements, ISecondaryTrack, DynamicPlottable, NeedsToKnowAboutLayers { // member variables /** * class containing editable details of a track */ public final class trackInfo extends Editable.EditorType implements Editable.DynamicDescriptors { /** * constructor for this editor, takes the actual track as a parameter * * @param data * track being edited */ public trackInfo(final TrackWrapper data) { super(data, data.getName(), ""); } @Override public final MethodDescriptor[] getMethodDescriptors() { // just add the reset color field first final Class<TrackWrapper> c = TrackWrapper.class; final MethodDescriptor[] mds = { method(c, "exportThis", null, "Export Shape"), method(c, "resetLabels", null, "Reset DTG Labels"), method(c, "calcCourseSpeed", null/* no params */, "Generate calculated Course and Speed")}; return mds; } @Override public final String getName() { return super.getName(); } @Override public final PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor[] res = { displayExpertProp("SymbolType", "Symbol type", "the type of symbol plotted for this label", FORMAT), displayExpertProp("LineThickness", "Line thickness", "the width to draw this track", FORMAT), expertProp("Name", "the track name"), displayExpertProp("InterpolatePoints", "Interpolate points", "whether to interpolate points between known data points", SPATIAL), expertProp("Color", "the track color", FORMAT), displayExpertProp("SymbolColor", "Symbol color", "the color of the symbol (when used)", FORMAT), displayExpertProp( "PlotArrayCentre", "Plot array centre", "highlight the sensor array centre when non-zero array length provided", FORMAT), displayExpertProp("TrackFont", "Track font", "the track label font", FORMAT), displayExpertProp("NameVisible", "Name visible", "show the track label", VISIBILITY), displayExpertProp("PositionsVisible", "Positions visible", "show individual Positions", VISIBILITY), displayExpertProp("NameAtStart", "Name at start", "whether to show the track name at the start (or end)", VISIBILITY), displayExpertProp("LinkPositions", "Link positions", "whether to join the track points", FORMAT), expertProp("Visible", "whether the track is visible", VISIBILITY), displayExpertLongProp("NameLocation", "Name location", "relative location of track label", MWC.GUI.Properties.LocationPropertyEditor.class), displayExpertLongProp("LabelFrequency", "Label frequency", "the label frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("SymbolFrequency", "Symbol frequency", "the symbol frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("ResampleDataAt", "Resample data at", "the data sample rate", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("ArrowFrequency", "Arrow frequency", "the direction marker frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("LineStyle", "Line style", "the line style used to join track points", MWC.GUI.Properties.LineStylePropertyEditor.class), }; res[0] .setPropertyEditorClass(MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor.class); res[1] .setPropertyEditorClass(MWC.GUI.Properties.LineWidthPropertyEditor.class); // SPECIAL CASE: if we have a world scaled symbol, provide // editors for // the symbol size final TrackWrapper item = (TrackWrapper) this.getData(); if (item._theSnailShape instanceof WorldScaledSym) { // yes = better create height/width editors final PropertyDescriptor[] res2 = new PropertyDescriptor[res.length + 2]; System.arraycopy(res, 0, res2, 2, res.length); res2[0] = displayExpertProp("SymbolLength", "Symbol length", "Length of symbol", FORMAT); res2[1] = displayExpertProp("SymbolWidth", "Symbol width", "Width of symbol", FORMAT); // and now use the new value res = res2; } return res; } catch (final IntrospectionException e) { return super.getPropertyDescriptors(); } } } private static final String SOLUTIONS_LAYER_NAME = "Solutions"; public static final String SENSORS_LAYER_NAME = "Sensors"; public static final String DYNAMIC_SHAPES_LAYER_NAME = "Dynamic Shapes"; /** * keep track of versions - version id */ static final long serialVersionUID = 1; /** * put the other objects into this one as children * * @param wrapper * whose going to receive it * @param theLayers * the top level layers object * @param parents * the track wrapppers containing the children * @param subjects * the items to insert. */ public static void groupTracks(final TrackWrapper target, final Layers theLayers, final Layer[] parents, final Editable[] subjects) { // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; final TrackWrapper thisP = (TrackWrapper) parents[i]; if (thisL != target) { // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment ts = (TrackSegment) segs.nextElement(); // reset the name if we need to if (ts.getName().startsWith("Posi")) { ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate() .getTime())); } target.add(ts); } } else { if (obj instanceof TrackSegment) { final TrackSegment ts = (TrackSegment) obj; // reset the name if we need to if (ts.getName().startsWith("Posi")) { ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate() .getTime())); } // and remember it target.add(ts); } } } } else { // get it's data, and add it to the target target.add(thisL); } // and remove the layer from it's parent if (thisL instanceof TrackSegment) { thisP.removeElement(thisL); // does this just leave an empty husk? if (thisP.numFixes() == 0) { // may as well ditch it anyway theLayers.removeThisLayer(thisP); } } else { // we'll just remove it from the top level layer theLayers.removeThisLayer(thisL); } } } } /** * perform a merge of the supplied tracks. * * @param target * the final recipient of the other items * @param theLayers * @param parents * the parent tracks for the supplied items * @param subjects * the actual selected items * @return sufficient information to undo the merge */ public static int mergeTracksInPlace(final Editable target, final Layers theLayers, final Layer[] parents, final Editable[] subjects) { // where we dump the new data points Layer receiver = (Layer) target; // check that the legs don't overlap String failedMsg = checkTheyAreNotOverlapping(subjects); // how did we get on? if (failedMsg != null) { MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg + " overlap in time. Please correct this and retry", MessageProvider.ERROR); return MessageProvider.ERROR; } // right, if the target is a TMA track, we have to change it into a // proper // track, since // the merged tracks probably contain manoeuvres if (target instanceof CoreTMASegment) { final CoreTMASegment tma = (CoreTMASegment) target; final TrackSegment newSegment = new TrackSegment(tma); // now do some fancy footwork to remove the target from the wrapper, // and // replace it with our new segment newSegment.getWrapper().removeElement(target); newSegment.getWrapper().add(newSegment); // store the new segment into the receiver receiver = newSegment; } // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; final TrackWrapper thisP = (TrackWrapper) parents[i]; // is this the target item (note we're comparing against the item // passed // in, not our // temporary receiver, since the receiver may now be a tracksegment, // not a // TMA segment if (thisL != target) { // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment ts = (TrackSegment) segs.nextElement(); receiver.add(ts); } } else { final Layer ts = (Layer) obj; receiver.append(ts); } } } else { // get it's data, and add it to the target receiver.append(thisL); } // and remove the layer from it's parent if (thisL instanceof TrackSegment) { thisP.removeElement(thisL); // does this just leave an empty husk? if (thisP.numFixes() == 0) { // may as well ditch it anyway theLayers.removeThisLayer(thisP); } } else { // we'll just remove it from the top level layer theLayers.removeThisLayer(thisL); } } } return MessageProvider.OK; } /** * perform a merge of the supplied tracks. * * @param target * the final recipient of the other items * @param theLayers * @param parents * the parent tracks for the supplied items * @param subjects * the actual selected items * @param _newName * name to give to the merged object * @return sufficient information to undo the merge */ public static int mergeTracks(final TrackWrapper recipient, final Layers theLayers, final Editable[] subjects) { // where we dump the new data points TrackWrapper newTrack = (TrackWrapper) recipient; // check that the legs don't overlap String failedMsg = checkTheyAreNotOverlapping(subjects); // how did we get on? if (failedMsg != null) { MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg + " overlap in time. Please correct this and retry", MessageProvider.ERROR); return MessageProvider.ERROR; } // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; TrackSegment newT = new TrackSegment(); duplicateFixes(sl, newT); newTrack.add(newT); } else if (obj instanceof TrackSegment) { TrackSegment ts = (TrackSegment) obj; // ok, duplicate the fixes in this segment TrackSegment newT = new TrackSegment(); duplicateFixes(ts, newT); // and add it to the new track newTrack.append(newT); } } } else if (thisL instanceof TrackSegment) { TrackSegment ts = (TrackSegment) thisL; // ok, duplicate the fixes in this segment TrackSegment newT = new TrackSegment(); duplicateFixes(ts, newT); // and add it to the new track newTrack.append(newT); } else if (thisL instanceof SegmentList) { SegmentList sl = (SegmentList) thisL; TrackSegment newT = new TrackSegment(); // ok, duplicate the fixes in this segment duplicateFixes(sl, newT); // and add it to the new track newTrack.append(newT); } } // and store the new track theLayers.addThisLayer(newTrack); return MessageProvider.OK; } private static void duplicateFixes(SegmentList sl, TrackSegment target) { final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment segment = (TrackSegment) segs.nextElement(); if (segment instanceof CoreTMASegment) { CoreTMASegment ct = (CoreTMASegment) segment; TrackSegment newSeg = new TrackSegment(ct); duplicateFixes(newSeg, target); } else { duplicateFixes(segment, target); } } } private static void duplicateFixes(TrackSegment source, TrackSegment target) { // ok, retrieve the points in the track segment Enumeration<Editable> tsPts = source.elements(); while (tsPts.hasMoreElements()) { FixWrapper existingFix = (FixWrapper) tsPts.nextElement(); FixWrapper newF = new FixWrapper(existingFix.getFix()); // also duplicate the label newF.setLabel(existingFix.getLabel()); target.addFix(newF); } } private static String checkTheyAreNotOverlapping(final Editable[] subjects) { // first, check they don't overlap. // start off by collecting the periods final TimePeriod[] _periods = new TimePeriod.BaseTimePeriod[subjects.length]; for (int i = 0; i < subjects.length; i++) { final Editable editable = subjects[i]; TimePeriod thisPeriod = null; if (editable instanceof TrackWrapper) { final TrackWrapper tw = (TrackWrapper) editable; thisPeriod = new TimePeriod.BaseTimePeriod(tw.getStartDTG(), tw.getEndDTG()); } else if (editable instanceof TrackSegment) { final TrackSegment ts = (TrackSegment) editable; thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG()); } _periods[i] = thisPeriod; } // now test them. String failedMsg = null; for (int i = 0; i < _periods.length; i++) { final TimePeriod timePeriod = _periods[i]; for (int j = 0; j < _periods.length; j++) { final TimePeriod timePeriod2 = _periods[j]; // check it's not us if (timePeriod2 != timePeriod) { if (timePeriod.overlaps(timePeriod2)) { failedMsg = "'" + subjects[i].getName() + "' and '" + subjects[j].getName() + "'"; break; } } } } return failedMsg; } /** * whether to interpolate points in this track */ private boolean _interpolatePoints = false; /** * the end of the track to plot the label */ private boolean _LabelAtStart = true; private HiResDate _lastLabelFrequency = null; private HiResDate _lastSymbolFrequency = null; private HiResDate _lastArrowFrequency = null; private HiResDate _lastDataFrequency = new HiResDate(0, TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY); /** * the width of this track */ private int _lineWidth = 3; /** * the style of this line * */ private int _lineStyle = CanvasType.SOLID; /** * whether or not to link the Positions */ private boolean _linkPositions; /** * whether to show a highlight for the array centre * */ private boolean _plotArrayCentre; /** * our editable details */ protected transient Editable.EditorType _myEditor = null; /** * keep a list of points waiting to be plotted * */ transient int[] _myPts; /** * the sensor tracks for this vessel */ final private BaseLayer _mySensors; /** * the dynamic shapes for this vessel */ final private BaseLayer _myDynamicShapes; /** * the TMA solutions for this vessel */ final private BaseLayer _mySolutions; /** * keep track of how far we are through our array of points * */ transient int _ptCtr = 0; /** * whether or not to show the Positions */ private boolean _showPositions; /** * the label describing this track */ private final MWC.GUI.Shapes.TextLabel _theLabel; /** * the list of wrappers we hold */ protected SegmentList _thePositions; /** * the symbol to pass on to a snail plotter */ private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape; /** * working ZERO location value, to reduce number of working values */ final private WorldLocation _zeroLocation = new WorldLocation(0, 0, 0); // member functions transient private FixWrapper finisher; transient private HiResDate lastDTG; transient private FixWrapper lastFix; // for getNearestTo transient private FixWrapper nearestFix; /** * working parameters */ // for getFixesBetween transient private FixWrapper starter; transient private TimePeriod _myTimePeriod; transient private WorldArea _myWorldArea; transient private final PropertyChangeListener _locationListener; private Layers _myLayers; // constructors /** * Wrapper for a Track (a series of position fixes). It combines the data with the formatting * details */ public TrackWrapper() { _mySensors = new SplittableLayer(true); _mySensors.setName(SENSORS_LAYER_NAME); _myDynamicShapes = new SplittableLayer(true); _myDynamicShapes.setName(DYNAMIC_SHAPES_LAYER_NAME); _mySolutions = new BaseLayer(true); _mySolutions.setName(SOLUTIONS_LAYER_NAME); // create a property listener for when fixes are moved _locationListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent arg0) { fixMoved(); } }; _linkPositions = true; // start off with positions showing (although the default setting for a // fix // is to not show a symbol anyway). We need to make this "true" so that // when a fix position is set to visible it is not over-ridden by this // setting _showPositions = true; _theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null); // set an initial location for the label _theLabel.setRelativeLocation(new Integer( MWC.GUI.Properties.LocationPropertyEditor.RIGHT)); // initialise the symbol to use for plotting this track in snail mode _theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol("Submarine"); // declare our arrays _thePositions = new TrackWrapper_Support.SegmentList(); _thePositions.setWrapper(this); } /** * add the indicated point to the track * * @param point * the point to add */ @Override public void add(final MWC.GUI.Editable point) { boolean done = false; // see what type of object this is if (point instanceof FixWrapper) { final FixWrapper fw = (FixWrapper) point; fw.setTrackWrapper(this); addFix(fw); done = true; } // is this a sensor? else if (point instanceof SensorWrapper) { final SensorWrapper swr = (SensorWrapper) point; // see if we already have a sensor with this name SensorWrapper existing = null; Enumeration<Editable> enumer = _mySensors.elements(); while (enumer.hasMoreElements()) { SensorWrapper oldS = (SensorWrapper) enumer.nextElement(); // does this have the same name? if (oldS.getName().equals(swr.getName())) { // yes - ok, remember it existing = oldS; // and append the data points existing.append(swr); } } // did we find it already? if (existing == null) { // nope, so store it _mySensors.add(swr); } // tell the sensor about us swr.setHost(this); // and the track name (if we're loading from REP it will already // know // the name, but if this data is being pasted in, it may start with // a different // parent track name - so override it here) swr.setTrackName(this.getName()); // indicate success done = true; } // is this a dynamic shape? else if (point instanceof DynamicTrackShapeSetWrapper) { final DynamicTrackShapeSetWrapper swr = (DynamicTrackShapeSetWrapper) point; // just check we don't alraedy have it if (_myDynamicShapes.contains(swr)) { MWC.Utilities.Errors.Trace .trace("Don't allow duplicate shape set name:" + swr.getName()); } else { // add to our list _myDynamicShapes.add(swr); // tell the sensor about us swr.setHost(this); // indicate success done = true; } } // is this a TMA solution track? else if (point instanceof TMAWrapper) { final TMAWrapper twr = (TMAWrapper) point; // add to our list _mySolutions.add(twr); // tell the sensor about us twr.setHost(this); // and the track name (if we're loading from REP it will already // know // the name, but if this data is being pasted in, it may start with // a different // parent track name - so override it here) twr.setTrackName(this.getName()); // indicate success done = true; } else if (point instanceof TrackSegment) { final TrackSegment seg = (TrackSegment) point; seg.setWrapper(this); _thePositions.addSegment((TrackSegment) point); done = true; // hey, sort out the positions sortOutRelativePositions(); } if (!done) { MWC.GUI.Dialogs.DialogFactory.showMessage("Add point", "Sorry it is not possible to add:" + point.getName() + " to " + this.getName()); } } /** * add the fix wrapper to the track * * @param theFix * the Fix to be added */ public void addFix(final FixWrapper theFix) { // do we have any track segments if (_thePositions.size() == 0) { // nope, add one final TrackSegment firstSegment = new TrackSegment(); firstSegment.setName("Positions"); _thePositions.addSegment(firstSegment); } // add fix to last track segment final TrackSegment last = (TrackSegment) _thePositions.last(); last.addFix(theFix); // tell the fix about it's daddy theFix.setTrackWrapper(this); // and extend the start/end DTGs if (_myTimePeriod == null) { _myTimePeriod = new TimePeriod.BaseTimePeriod(theFix.getDateTimeGroup(), theFix .getDateTimeGroup()); } else { _myTimePeriod.extend(theFix.getDateTimeGroup()); } if (_myWorldArea == null) { _myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation()); } else { _myWorldArea.extend(theFix.getLocation()); } // we want to listen out for the fix being moved. better listen in to it // theFix.addPropertyChangeListener(PlainWrapper.LOCATION_CHANGED, // _locationListener); // tell any layer-level listeners about it List<INewItemListener> itemListeners = _myLayers.getNewItemListeners(); Iterator<INewItemListener> iter = itemListeners.iterator(); while (iter.hasNext()) { Layers.INewItemListener newI = (Layers.INewItemListener) iter.next(); newI.newItem(this, theFix); } } /** * append this other layer to ourselves (although we don't really bother with it) * * @param other * the layer to add to ourselves */ @Override public void append(final Layer other) { // is it a track? if ((other instanceof TrackWrapper) || (other instanceof TrackSegment)) { // yes, break it down. final java.util.Enumeration<Editable> iter = other.elements(); while (iter.hasMoreElements()) { final Editable nextItem = iter.nextElement(); if (nextItem instanceof Layer) { append((Layer) nextItem); } else { add(nextItem); } } } else { // nope, just add it to us. add(other); } } /** * instruct this object to clear itself out, ready for ditching */ @Override public final void closeMe() { // and my objects // first ask them to close themselves final Enumeration<Editable> it = getPositions(); while (it.hasMoreElements()) { final Object val = it.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _thePositions.removeAllElements(); _thePositions = null; // and my objects // first ask the sensors to close themselves if (_mySensors != null) { final Enumeration<Editable> it2 = _mySensors.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _mySensors.removeAllElements(); } // and my objects // first ask the sensors to close themselves if (_myDynamicShapes != null) { final Enumeration<Editable> it2 = _myDynamicShapes.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _myDynamicShapes.removeAllElements(); } // now ask the solutions to close themselves if (_mySolutions != null) { final Enumeration<Editable> it2 = _mySolutions.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _mySolutions.removeAllElements(); } // and our utility objects finisher = null; lastFix = null; nearestFix = null; starter = null; // and our editor _myEditor = null; // now get the parent to close itself super.closeMe(); } /** * switch the two track sections into one track section * * @param res * the previously split track sections */ public void combineSections(final Vector<TrackSegment> res) { // ok, remember the first final TrackSegment keeper = res.firstElement(); // now remove them all, adding them to the first final Iterator<TrackSegment> iter = res.iterator(); while (iter.hasNext()) { final TrackSegment pl = iter.next(); if (pl != keeper) { keeper.append((Layer) pl); } _thePositions.removeElement(pl); } // and put the keepers back in _thePositions.addSegment(keeper); } /** * return our tiered data as a single series of elements * * @return */ @Override public Enumeration<Editable> contiguousElements() { final Vector<Editable> res = new Vector<Editable>(0, 1); if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // is it visible? if (sw.getVisible()) { res.addAll(sw._myContacts); } } } if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); // is it visible? if (sw.getVisible()) { res.addAll(sw.getData()); } } } if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); if (sw.getVisible()) { res.addAll(sw._myContacts); } } } if (_thePositions != null) { res.addAll(getRawPositions()); } return res.elements(); } /** * get an enumeration of the points in this track * * @return the points in this track */ @Override public Enumeration<Editable> elements() { final TreeSet<Editable> res = new TreeSet<Editable>(); if (_mySensors.size() > 0) { res.add(_mySensors); } if (_myDynamicShapes.size() > 0) { res.add(_myDynamicShapes); } if (_mySolutions.size() > 0) { res.add(_mySolutions); } // ok, we want to wrap our fast-data as a set of plottables // see how many track segments we have if (_thePositions.size() == 1) { // just the one, insert it res.add(_thePositions.first()); } else { // more than one, insert them as a tree res.add(_thePositions); } return new TrackWrapper_Support.IteratorWrapper(res.iterator()); } /** * export this track to REPLAY file */ @Override public final void exportShape() { // call the method in PlainWrapper this.exportThis(); } /** * filter the list to the specified time period, then inform any listeners (such as the time * stepper) * * @param start * the start dtg of the period * @param end * the end dtg of the period */ @Override public final void filterListTo(final HiResDate start, final HiResDate end) { final Enumeration<Editable> fixWrappers = getPositions(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); final HiResDate dtg = fw.getTime(); if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end))) { fw.setVisible(true); } else { fw.setVisible(false); } } // now do the same for our sensor data if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensors } // whether we have any sensors // now do the same for our sensor arc data if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensor arcs } // whether we have any sensor arcs if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensors } // whether we have any sensors // do we have any property listeners? if (getSupport() != null) { final Debrief.GUI.Tote.StepControl.somePeriod newPeriod = new Debrief.GUI.Tote.StepControl.somePeriod(start, end); getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null, newPeriod); } } @Override public void findNearestHotSpotIn(final Point cursorPos, final WorldLocation cursorLoc, final ComponentConstruct currentNearest, final Layer parentLayer) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS); // cycle through the fixes final Enumeration<Editable> fixes = getPositions(); while (fixes.hasMoreElements()) { final FixWrapper thisF = (FixWrapper) fixes.nextElement(); // only check it if it's visible if (thisF.getVisible()) { // how far away is it? thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist); final WorldLocation fixLocation = new WorldLocation(thisF.getLocation()) { private static final long serialVersionUID = 1L; @Override public void addToMe(final WorldVector delta) { super.addToMe(delta); thisF.setFixLocation(this); } }; // try range currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation); } } } @Override public void findNearestHotSpotIn(final Point cursorPos, final WorldLocation cursorLoc, final LocationConstruct currentNearest, final Layer parentLayer, final Layers theData) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS); // cycle through the fixes final Enumeration<Editable> fixes = getPositions(); while (fixes.hasMoreElements()) { final FixWrapper thisF = (FixWrapper) fixes.nextElement(); if (thisF.getVisible()) { // how far away is it? thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist); // is it closer? currentNearest.checkMe(this, thisDist, null, parentLayer); } } } public void findNearestSegmentHotspotFor(final WorldLocation cursorLoc, final Point cursorPt, final LocationConstruct currentNearest) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist; // cycle through the track segments final Collection<Editable> segments = _thePositions.getData(); for (final Iterator<Editable> iterator = segments.iterator(); iterator .hasNext();) { final TrackSegment thisSeg = (TrackSegment) iterator.next(); if (thisSeg.getVisible()) { // how far away is it? thisDist = new WorldDistance(thisSeg.rangeFrom(cursorLoc), WorldDistance.DEGS); // is it closer? currentNearest.checkMe(thisSeg, thisDist, null, this); } } } /** * one of our fixes has moved. better tell any bits that rely on the locations of our bits * * @param theFix * the fix that moved */ public void fixMoved() { if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper nextS = (SensorWrapper) iter.nextElement(); nextS.setHost(this); } } if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper nextS = (DynamicTrackShapeSetWrapper) iter.nextElement(); nextS.setHost(this); } } } /** * return the arrow frequencies for the track * * @return frequency in seconds */ public final HiResDate getArrowFrequency() { return _lastArrowFrequency; } /** * calculate a position the specified distance back along the ownship track (note, we always * interpolate the parent track position) * * @param searchTime * the time we're looking at * @param sensorOffset * how far back the sensor should be * @param wormInHole * whether to plot a straight line back, or make sensor follow ownship * @return the location */ public FixWrapper getBacktraceTo(final HiResDate searchTime, final ArrayLength sensorOffset, final boolean wormInHole) { FixWrapper res = null; if (wormInHole && sensorOffset != null) { res = WormInHoleOffset.getWormOffsetFor(this, searchTime, sensorOffset); } else { final boolean parentInterpolated = getInterpolatePoints(); setInterpolatePoints(true); final MWC.GenericData.Watchable[] list = getNearestTo(searchTime); // and restore the interpolated value setInterpolatePoints(parentInterpolated); FixWrapper wa = null; if (list.length > 0) { wa = (FixWrapper) list[0]; } // did we find it? if (wa != null) { // yes, store it res = new FixWrapper(wa.getFix().makeCopy()); // ok, are we dealing with an offset? if (sensorOffset != null) { // get the current heading final double hdg = wa.getCourse(); // and calculate where it leaves us final WorldVector vector = new WorldVector(hdg, sensorOffset, null); // now apply this vector to the origin res.setLocation(new WorldLocation(res.getLocation().add(vector))); } } } return res; } // editing parameters /** * what geographic area is covered by this track? * * @return get the outer bounds of the area */ @Override public final WorldArea getBounds() { // we no longer just return the bounds of the track, because a portion // of the track may have been made invisible. // instead, we will pass through the full dataset and find the outer // bounds // of the visible area WorldArea res = null; if (!getVisible()) { // hey, we're invisible, return null } else { final Enumeration<Editable> it = getPositions(); while (it.hasMoreElements()) { final FixWrapper fw = (FixWrapper) it.nextElement(); // is this point visible? if (fw.getVisible()) { // has our data been initialised? if (res == null) { // no, initialise it res = new WorldArea(fw.getLocation(), fw.getLocation()); } else { // yes, extend to include the new area res.extend(fw.getLocation()); } } } // also extend to include our sensor data if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final PlainWrapper sw = (PlainWrapper) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // whether we have any sensors // also extend to include our sensor data if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final Plottable sw = (Plottable) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // and our solution data if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final PlainWrapper sw = (PlainWrapper) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // whether we have any sensors } // whether we're visible // SPECIAL CASE: if we're a DR track, the positions all // have the same value if (res != null) { // have we ended up with an empty area? if (res.getHeight() == 0) { // ok - force a bounds update sortOutRelativePositions(); // and retrieve the bounds of hte first segment res = this.getSegments().first().getBounds(); } } return res; } /** * the time of the last fix * * @return the DTG */ @Override public final HiResDate getEndDTG() { HiResDate dtg = null; final TimePeriod res = getTimePeriod(); if (res != null) { dtg = res.getEndDTG(); } return dtg; } /** * the editable details for this track * * @return the details */ @Override public Editable.EditorType getInfo() { if (_myEditor == null) { _myEditor = new trackInfo(this); } return _myEditor; } /** * create a new, interpolated point between the two supplied * * @param previous * the previous point * @param next * the next point * @return and interpolated point */ private final FixWrapper getInterpolatedFix(final FixWrapper previous, final FixWrapper next, final HiResDate requestedDTG) { FixWrapper res = null; // do we have a start point if (previous == null) { res = next; } // hmm, or do we have an end point? if (next == null) { res = previous; } // did we find it? if (res == null) { res = FixWrapper.interpolateFix(previous, next, requestedDTG); } return res; } @Override public final boolean getInterpolatePoints() { return _interpolatePoints; } /** * get the set of fixes contained within this time period (inclusive of both end values) * * @param start * start DTG * @param end * end DTG * @return series of fixes */ @Override public final Collection<Editable> getItemsBetween(final HiResDate start, final HiResDate end) { SortedSet<Editable> set = null; // does our track contain any data at all if (_thePositions.size() > 0) { // see if we have _any_ points in range if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start))) { // don't bother with it. } else { // SPECIAL CASE! If we've been asked to show interpolated data // points, // then // we should produce a series of items between the indicated // times. How // about 1 minute resolution? if (getInterpolatePoints()) { final long ourInterval = 1000 * 60; // one minute set = new TreeSet<Editable>(); for (long newTime = start.getDate().getTime(); newTime < end .getDate().getTime(); newTime += ourInterval) { final HiResDate newD = new HiResDate(newTime); final Watchable[] nearestOnes = getNearestTo(newD); if (nearestOnes.length > 0) { final FixWrapper nearest = (FixWrapper) nearestOnes[0]; set.add(nearest); } } } else { // bugger that - get the real data // have a go.. if (starter == null) { starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0)); } else { starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1)); } if (finisher == null) { finisher = new FixWrapper(new Fix(new HiResDate(0, end.getMicros() + 1), _zeroLocation, 0.0, 0.0)); } else { finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1)); } // ok, ready, go for it. set = getPositionsBetween(starter, finisher); } } } return set; } /** * method to allow the setting of label frequencies for the track * * @return frequency to use */ public final HiResDate getLabelFrequency() { return this._lastLabelFrequency; } /** * what is the style used for plotting this track? * * @return */ public int getLineStyle() { return _lineStyle; } /** * the line thickness (convenience wrapper around width) * * @return */ @Override public int getLineThickness() { return _lineWidth; } /** * whether to link points * * @return */ public boolean getLinkPositions() { return _linkPositions; } /** * just have the one property listener - rather than an anonymous class * * @return */ public PropertyChangeListener getLocationListener() { return _locationListener; } /** * name of this Track (normally the vessel name) * * @return the name */ @Override public final String getName() { return _theLabel.getString(); } /** * get our child segments * * @return */ public SegmentList getSegments() { return _thePositions; } /** * whether to show the track label at the start or end of the track * * @return yes/no to indicate <I>At Start</I> */ public final boolean getNameAtStart() { return _LabelAtStart; } /** * the relative location of the label * * @return the relative location */ public final Integer getNameLocation() { return _theLabel.getRelativeLocation(); } /** * whether the track label is visible or not * * @return yes/no */ public final boolean getNameVisible() { return _theLabel.getVisible(); } /** * find the fix nearest to this time (or the first fix for an invalid time) * * @param DTG * the time of interest * @return the nearest fix */ @Override public final Watchable[] getNearestTo(final HiResDate srchDTG) { /** * we need to end up with a watchable, not a fix, so we need to work our way through the fixes */ FixWrapper res = null; // check that we do actually contain some data if (_thePositions.size() == 0) { return new MWC.GenericData.Watchable[] {}; } // special case - if we've been asked for an invalid time value if (srchDTG == TimePeriod.INVALID_DATE) { final TrackSegment seg = (TrackSegment) _thePositions.first(); final FixWrapper fix = (FixWrapper) seg.first(); // just return our first location return new MWC.GenericData.Watchable[] {fix}; } // see if this is the DTG we have just requestsed if ((srchDTG.equals(lastDTG)) && (lastFix != null)) { res = lastFix; } else { final TrackSegment firstSeg = (TrackSegment) _thePositions.first(); final TrackSegment lastSeg = (TrackSegment) _thePositions.last(); if ((firstSeg != null) && (firstSeg.size() > 0)) { // see if this DTG is inside our data range // in which case we will just return null final FixWrapper theFirst = (FixWrapper) firstSeg.first(); final FixWrapper theLast = (FixWrapper) lastSeg.last(); if ((srchDTG.greaterThan(theFirst.getTime())) && (srchDTG.lessThanOrEqualTo(theLast.getTime()))) { // yes it's inside our data range, find the first fix // after the indicated point // right, increment the time, since we want to allow matching // points // HiResDate DTG = new HiResDate(0, srchDTG.getMicros() + 1); // see if we have to create our local temporary fix if (nearestFix == null) { nearestFix = new FixWrapper(new Fix(srchDTG, _zeroLocation, 0.0, 0.0)); } else { nearestFix.getFix().setTime(srchDTG); } // right, we really should be filtering the list according to if // the // points are visible. // how do we do filters? // get the data. use tailSet, since it's inclusive... SortedSet<Editable> set = getRawPositions().tailSet(nearestFix); // see if the requested DTG was inside the range of the data if (!set.isEmpty() && (set.size() > 0)) { res = (FixWrapper) set.first(); // is this one visible? if (!res.getVisible()) { // right, the one we found isn't visible. duplicate the // set, so that // we can remove items // without affecting the parent TreeSet<Editable> tmpSet = new TreeSet<Editable>(set); // ok, start looping back until we find one while ((!res.getVisible()) && (tmpSet.size() > 0)) { // the first one wasn't, remove it tmpSet.remove(res); if (tmpSet.size() > 0) { res = (FixWrapper) tmpSet.first(); } } // SPECIAL CASE: when the time period is after // the end of the filtered period, the above logic will // result in the very last point on the list being // selected. In truth, the first point on the // list is closer to the requested time. // when this happens, return the first item in the // original list. if (tmpSet.size() == 0) { res = (FixWrapper) set.first(); } } } // right, that's the first points on or before the indicated // DTG. Are we // meant // to be interpolating? if (res != null) { if (getInterpolatePoints()) { // right - just check that we aren't actually on the // correct time // point. // HEY, USE THE ORIGINAL SEARCH TIME, NOT THE // INCREMENTED ONE, // SINCE WE DON'T WANT TO COMPARE AGAINST A MODIFIED // TIME if (!res.getTime().equals(srchDTG)) { // right, we haven't found an actual data point. // Better calculate // one // hmm, better also find the point before our one. // the // headSet operation is exclusive - so we need to // find the one // after the first final SortedSet<Editable> otherSet = getRawPositions().headSet(nearestFix); FixWrapper previous = null; if (!otherSet.isEmpty()) { previous = (FixWrapper) otherSet.last(); } // did it work? if (previous != null) { // cool, sort out the interpolated point USING // THE ORIGINAL // SEARCH TIME res = getInterpolatedFix(previous, res, srchDTG); } } } } } else if (srchDTG.equals(theFirst.getDTG())) { // aaah, special case. just see if we're after a data point // that's the // same // as our start time res = theFirst; } } // and remember this fix lastFix = res; lastDTG = srchDTG; } if (res != null) { return new MWC.GenericData.Watchable[] {res}; } else { return new MWC.GenericData.Watchable[] {}; } } public boolean getPlotArrayCentre() { return _plotArrayCentre; } /** * get the position data, not all the sensor/contact/position data mixed together * * @return */ public final Enumeration<Editable> getPositions() { final SortedSet<Editable> res = getRawPositions(); return new TrackWrapper_Support.IteratorWrapper(res.iterator()); } private SortedSet<Editable> getPositionsBetween(final FixWrapper starter2, final FixWrapper finisher2) { // first get them all as one list final SortedSet<Editable> pts = getRawPositions(); // now do the sort return pts.subSet(starter2, finisher2); } /** * whether positions are being shown * * @return */ public final boolean getPositionsVisible() { return _showPositions; } private SortedSet<Editable> getRawPositions() { SortedSet<Editable> res = null; // do we just have the one list? if (_thePositions.size() == 1) { final TrackSegment p = (TrackSegment) _thePositions.first(); res = (SortedSet<Editable>) p.getData(); } else { // loop through them res = new TreeSet<Editable>(); final Enumeration<Editable> segs = _thePositions.elements(); while (segs.hasMoreElements()) { // get this segment final TrackSegment seg = (TrackSegment) segs.nextElement(); // add all the points res.addAll(seg.getData()); } } return res; } /** * method to allow the setting of data sampling frequencies for the track & sensor data * * @return frequency to use */ public final HiResDate getResampleDataAt() { return this._lastDataFrequency; } /** * get the list of sensors for this track */ public final BaseLayer getSensors() { return _mySensors; } /** * get the list of sensor arcs for this track */ public final BaseLayer getDynamicShapes() { return _myDynamicShapes; } /** * return the symbol to be used for plotting this track in snail mode */ @Override public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape() { return _theSnailShape; } /** * get the list of sensors for this track */ public final BaseLayer getSolutions() { return _mySolutions; } // watchable (tote related) parameters /** * the earliest fix in the track * * @return the DTG */ @Override public final HiResDate getStartDTG() { HiResDate res = null; final TimePeriod period = getTimePeriod(); if (period != null) { res = period.getStartDTG(); } return res; } /** * get the color used to plot the symbol * * @return the color */ public final Color getSymbolColor() { return _theSnailShape.getColor(); } /** * return the symbol frequencies for the track * * @return frequency in seconds */ public final HiResDate getSymbolFrequency() { return _lastSymbolFrequency; } public WorldDistance getSymbolLength() { WorldDistance res = null; if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; res = sym.getLength(); } return res; } /** * get the type of this symbol */ public final String getSymbolType() { return _theSnailShape.getType(); } public WorldDistance getSymbolWidth() { WorldDistance res = null; if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; res = sym.getWidth(); } return res; } private TimePeriod getTimePeriod() { TimePeriod res = null; final Enumeration<Editable> segs = _thePositions.elements(); while (segs.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segs.nextElement(); // do we have a dtg? if ((seg.startDTG() != null) && (seg.endDTG() != null)) { // yes, get calculating if (res == null) { res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG()); } else { res.extend(seg.startDTG()); res.extend(seg.endDTG()); } } } return res; } /** * the colour of the points on the track * * @return the colour */ public final Color getTrackColor() { return getColor(); } /** * font handler * * @return the font to use for the label */ public final java.awt.Font getTrackFont() { return _theLabel.getFont(); } /** * get the set of fixes contained within this time period which haven't been filtered, and which * have valid depths. The isVisible flag indicates whether a track has been filtered or not. We * also have the getVisibleFixesBetween method (below) which decides if a fix is visible if it is * set to Visible, and it's label or symbol are visible. * <p/> * We don't have to worry about a valid depth, since 3d doesn't show points with invalid depth * values * * @param start * start DTG * @param end * end DTG * @return series of fixes */ public final Collection<Editable> getUnfilteredItems(final HiResDate start, final HiResDate end) { // see if we have _any_ points in range if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start))) { return null; } if (this.getVisible() == false) { return null; } // get ready for the output final Vector<Editable> res = new Vector<Editable>(0, 1); // put the data into a period final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end); // step through our fixes final Enumeration<Editable> iter = getPositions(); while (iter.hasMoreElements()) { final FixWrapper fw = (FixWrapper) iter.nextElement(); if (fw.getVisible()) { // is it visible? if (thePeriod.contains(fw.getTime())) { // hey, it's valid - continue res.add(fw); } } } return res; } /** * whether this object has editor details * * @return yes/no */ @Override public final boolean hasEditor() { return true; } @Override public boolean hasOrderedChildren() { return false; } /** * quick accessor for how many fixes we have * * @return */ public int numFixes() { return getRawPositions().size(); } private void checkPointsArray() { // is our points store long enough? if ((_myPts == null) || (_myPts.length < numFixes() * 2)) { _myPts = new int[numFixes() * 2]; } // reset the points counter _ptCtr = 0; } private boolean paintFixes(final CanvasType dest) { // we need an array to store the polyline of points in. Check it's big // enough checkPointsArray(); // keep track of if we have plotted any points (since // we won't be plotting the name if none of the points are visible). // this typically occurs when filtering is applied and a short // track is completely outside the time period boolean plotted_anything = false; // java.awt.Point lastP = null; Color lastCol = null; final int defaultlineStyle = getLineStyle(); boolean locatedTrack = false; WorldLocation lastLocation = null; FixWrapper lastFix = null; final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); // how shall we plot this segment? final int thisLineStyle; // is the parent using the default style? if (defaultlineStyle == CanvasType.SOLID) { // yes, let's override it, if the segment wants to thisLineStyle = seg.getLineStyle(); } else { // no, we're using a custom style - don't override it. thisLineStyle = defaultlineStyle; } // SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN // RELATIVE MODE final boolean isRelative = seg.getPlotRelative(); WorldLocation tmaLastLoc = null; long tmaLastDTG = 0; // if it's not a relative track, and it's not visible, we don't // need to work with ut if (!getVisible() && !isRelative) { continue; } // is this segment visible? if (!seg.getVisible()) { continue; } final Enumeration<Editable> fixWrappers = seg.elements(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); // now there's a chance that our fix has forgotten it's // parent, // particularly if it's the victim of a // copy/paste operation. Tell it about it's children fw.setTrackWrapper(this); // is this fix visible? if (!fw.getVisible()) { // nope. Don't join it to the last position. // ok, if we've built up a polygon, we need to write it // now paintSetOfPositions(dest, lastCol, thisLineStyle); } // Note: we're carrying on working with this position even // if it isn't visible, // since we need to use non-visible positions to build up a // DR track. // ok, so we have plotted something plotted_anything = true; // ok, are we in relative? if (isRelative) { final long thisTime = fw.getDateTimeGroup().getDate().getTime(); // ok, is this our first location? if (tmaLastLoc == null) { tmaLastLoc = new WorldLocation(seg.getTrackStart()); lastLocation = tmaLastLoc; } else { // calculate a new vector final long timeDelta = thisTime - tmaLastDTG; if (lastFix != null) { final double speedKts = lastFix.getSpeed(); final double courseRads = lastFix.getCourse(); final double depthM = lastFix.getDepth(); // use the value of depth as read in from the // file tmaLastLoc.setDepth(depthM); final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts, courseRads); tmaLastLoc.addToMe(thisVec); lastLocation = tmaLastLoc; } } lastFix = fw; tmaLastDTG = thisTime; // dump the location into the fix fw.setFixLocationSilent(new WorldLocation(tmaLastLoc)); } else { // this is an absolute position lastLocation = fw.getLocation(); } // ok, we only do this writing to screen if the actual // position is visible if (!fw.getVisible()) continue; final java.awt.Point thisP = dest.toScreen(lastLocation); // just check that there's enough GUI to create the plot // (i.e. has a point been returned) if (thisP == null) { return false; } // so, we're looking at the first data point. Do // we want to use this to locate the track name? // or have we already sorted out the location if (_LabelAtStart && !locatedTrack) { locatedTrack = true; _theLabel.setLocation(new WorldLocation(lastLocation)); } // are we if (getLinkPositions() && (getLineStyle() != LineStylePropertyEditor.UNCONNECTED)) { // right, just check if we're a different colour to // the previous one final Color thisCol = fw.getColor(); // do we know the previous colour if (lastCol == null) { lastCol = thisCol; } // is this to be joined to the previous one? if (fw.getLineShowing()) { // so, grow the the polyline, unless we've got a // colour change... if (thisCol != lastCol) { // add our position to the list - so it // finishes on us _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; // yup, better get rid of the previous // polygon paintSetOfPositions(dest, lastCol, thisLineStyle); } // add our position to the list - we'll output // the polyline at the end _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; } else { // nope, output however much line we've got so // far - since this // line won't be joined to future points paintSetOfPositions(dest, thisCol, thisLineStyle); // start off the next line _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; } /* * set the colour of the track from now on to this colour, so that the "link" to the next * fix is set to this colour if left unchanged */ dest.setColor(fw.getColor()); // and remember the last colour lastCol = thisCol; } if (_showPositions && fw.getVisible()) { // this next method just paints the fix. we've put the // call into paintThisFix so we can override the painting // in the CompositeTrackWrapper class paintThisFix(dest, lastLocation, fw); } }// while fixWrappers has more elements // SPECIAL HANDLING, IF IT'S A TMA SEGMENT PLOT THE VECTOR LABEL if (seg instanceof CoreTMASegment) { CoreTMASegment tma = (CoreTMASegment) seg; WorldLocation firstLoc = seg.first().getBounds().getCentre(); WorldLocation lastLoc = seg.last().getBounds().getCentre(); Font f = new Font("Sans Serif", Font.PLAIN, 11); Color c = _theLabel.getColor(); // tell the segment it's being stretched final String spdTxt = MWC.Utilities.TextFormatting.GeneralFormat .formatOneDecimalPlace(tma.getSpeed() .getValueIn(WorldSpeed.Kts)); // copied this text from RelativeTMASegment double courseVal = tma.getCourse(); if (courseVal < 0) courseVal += 360; String textLabel = "[" + spdTxt + " kts " + (int) courseVal + "\u00B0]"; // ok, now plot it CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc, lastLoc, 1.2, true); textLabel = tma.getName().replace(TextLabel.NEWLINE_MARKER, " "); CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc, lastLoc, 1.2, false); } // ok, just see if we have any pending polylines to paint paintSetOfPositions(dest, lastCol, thisLineStyle); } // are we trying to put the label at the end of the track? // have we found at least one location to plot? if (!_LabelAtStart && lastLocation != null) { _theLabel.setLocation(new WorldLocation(lastLocation)); } return plotted_anything; } private void paintSingleTrackLabel(final CanvasType dest) { // check that we have found a location for the label if (_theLabel.getLocation() == null) return; // is the first track a DR track? // NO - CHANGED: we only initialise the track font in italics // for a DR track. Then we let the user change it // final TrackSegment t1 = (TrackSegment) _thePositions.first(); // if (t1.getPlotRelative()) // _theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC)); // else if (_theLabel.getFont().isItalic()) // _theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN)); // check that we have set the name for the label if (_theLabel.getString() == null) { _theLabel.setString(getName()); } // does the first label have a colour? if (_theLabel.getColor() == null) { // check we have a colour Color labelColor = getColor(); // did we ourselves have a colour? if (labelColor == null) { // nope - do we have any legs? final Enumeration<Editable> numer = this.getPositions(); if (numer.hasMoreElements()) { // ok, use the colour of the first point final FixWrapper pos = (FixWrapper) numer.nextElement(); labelColor = pos.getColor(); } } _theLabel.setColor(labelColor); } // and paint it _theLabel.paint(dest); } private void paintMultipleSegmentLabel(final CanvasType dest) { final Enumeration<Editable> posis = _thePositions.elements(); while (posis.hasMoreElements()) { final TrackSegment thisE = (TrackSegment) posis.nextElement(); // is this segment visible? if (!thisE.getVisible()) { continue; } // does it have visible data points? if (thisE.size() == 0) { continue; } // if this is a TMA segment, we plot the name 1/2 way along. If it isn't // we plot it at the start if (thisE instanceof CoreTMASegment) { // just move along - we plot the name // a the mid-point } else { // is the first track a DR track? if (thisE.getPlotRelative()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC)); } else if (_theLabel.getFont().isItalic()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN)); } final WorldLocation theLoc = thisE.getTrackStart(); final String oldTxt = _theLabel.getString(); _theLabel.setString(thisE.getName()); // just see if this is a planning segment, with its own colors if (thisE instanceof PlanningSegment) { final PlanningSegment ps = (PlanningSegment) thisE; _theLabel.setColor(ps.getColor()); } else { _theLabel.setColor(getColor()); } _theLabel.setLocation(theLoc); _theLabel.paint(dest); _theLabel.setString(oldTxt); } } } /** * draw this track (we can leave the Positions to draw themselves) * * @param dest * the destination */ @Override public final void paint(final CanvasType dest) { // check we are visible and have some track data, else we won't work if (!getVisible() || this.getStartDTG() == null) { return; } // set the thickness for this track dest.setLineWidth(_lineWidth); // and set the initial colour for this track if (getColor() != null) dest.setColor(getColor()); // firstly plot the solutions if (_mySolutions.getVisible()) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); // just check that the sensor knows we're it's parent if (sw.getHost() == null) { sw.setHost(this); } // and do the paint sw.paint(dest); } // through the solutions } // whether the solutions are visible // now plot the sensors if (_mySensors.getVisible()) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // just check that the sensor knows we're it's parent if (sw.getHost() == null) { sw.setHost(this); } // and do the paint sw.paint(dest); } // through the sensors } // whether the sensor layer is visible // now plot the sensor arcs // if (_mySensorArcs.getVisible()) // final Enumeration<Editable> iter = _mySensorArcs.elements(); // while (iter.hasMoreElements()) // final SensorArcWrapper sw = (SensorArcWrapper) iter.nextElement(); // // just check that the sensor knows we're it's parent // if (sw.getHost() == null) // sw.setHost(this); // // and do the paint // sw.paint(dest); // and now the track itself // just check if we are drawing anything at all if ((!getLinkPositions() || getLineStyle() == LineStylePropertyEditor.UNCONNECTED) && (!_showPositions)) { return; } // let the fixes draw themselves in final boolean plotted_anything = paintFixes(dest); // and draw the track label // still, we only plot the track label if we have plotted any // points if (_theLabel.getVisible() && plotted_anything) { // just see if we have multiple segments. if we do, // name them individually if (this._thePositions.size() <= 1) { paintSingleTrackLabel(dest); } else { // we've got multiple segments, name them paintMultipleSegmentLabel(dest); } } // if the label is visible // paint vector label if (plotted_anything) { paintVectorLabel(dest); } } private void paintVectorLabel(final CanvasType dest) { if (getVisible()) { final Enumeration<Editable> posis = _thePositions.elements(); while (posis.hasMoreElements()) { final TrackSegment thisE = (TrackSegment) posis.nextElement(); // paint only visible planning segments if ((thisE instanceof PlanningSegment) && thisE.getVisible()) { PlanningSegment ps = (PlanningSegment) thisE; ps.paintLabel(dest); } } } } /** * get the fix to paint itself * * @param dest * @param lastLocation * @param fw */ protected void paintThisFix(final CanvasType dest, final WorldLocation lastLocation, final FixWrapper fw) { fw.paintMe(dest, lastLocation, fw.getColor()); } /** * this accessor is present for debug/testing purposes only. Do not use outside testing! * * @return the list of screen locations about to be plotted */ public int[] debug_GetPoints() { return _myPts; } /** * this accessor is present for debug/testing purposes only. Do not use outside testing! * * @return the length of the list of screen points waiting to be plotted */ public int debug_GetPointCtr() { return _ptCtr; } /** * paint any polyline that we've built up * * @param dest * - where we're painting to * @param thisCol * @param lineStyle */ private void paintSetOfPositions(final CanvasType dest, final Color thisCol, final int lineStyle) { if (_ptCtr > 0) { dest.setColor(thisCol); dest.setLineStyle(lineStyle); final int[] poly = new int[_ptCtr]; System.arraycopy(_myPts, 0, poly, 0, _ptCtr); dest.drawPolyline(poly); dest.setLineStyle(CanvasType.SOLID); // and reset the counter _ptCtr = 0; } } /** * return the range from the nearest corner of the track * * @param other * the other location * @return the range */ @Override public final double rangeFrom(final WorldLocation other) { double nearest = -1; // do we have a track? if (_myWorldArea != null) { // find the nearest point on the track nearest = _myWorldArea.rangeFrom(other); } return nearest; } /** * remove the requested item from the track * * @param point * the point to remove */ @Override public final void removeElement(final Editable point) { // just see if it's a sensor which is trying to be removed if (point instanceof SensorWrapper) { _mySensors.removeElement(point); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) point; sw.setHost(null); } else if (point instanceof TMAWrapper) { _mySolutions.removeElement(point); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) point; sw.setHost(null); } else if (point instanceof SensorContactWrapper) { // ok, cycle through our sensors, try to remove this contact... final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // try to remove it from this one... sw.removeElement(point); } } else if (point instanceof DynamicTrackShapeWrapper) { // ok, cycle through our sensors, try to remove this contact... final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); // try to remove it from this one... sw.removeElement(point); } } else if (point instanceof TrackSegment) { _thePositions.removeElement(point); // and clear the parent item final TrackSegment ts = (TrackSegment) point; ts.setWrapper(null); } else if (point == _mySensors) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) editable; sw.setHost(null); } // and empty them out _mySensors.removeAllElements(); } else if (point == _myDynamicShapes) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) editable; sw.setHost(null); } // and empty them out _myDynamicShapes.removeAllElements(); } else if (point == _mySolutions) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) editable; sw.setHost(null); } // and empty them out _mySolutions.removeAllElements(); } else { // loop through the segments final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); seg.removeElement(point); // and stop listening to it (if it's a fix) if (point instanceof FixWrapper) { final FixWrapper fw = (FixWrapper) point; fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED, _locationListener); } } } } // LAYER support methods /** * pass through the track, resetting the labels back to their original DTG */ @FireReformatted public void resetLabels() { FormatTracks.formatTrack(this); } /** * how frequently symbols are placed on the track * * @param theVal * frequency in seconds */ public final void setArrowFrequency(final HiResDate theVal) { this._lastArrowFrequency = theVal; // set the "showPositions" parameter, as long as we are // not setting the symbols off if (theVal.getMicros() != 0.0) { this.setPositionsVisible(true); } final FixSetter setSymbols = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setArrowShowing(val); } }; setFixes(setSymbols, theVal); } /** * set the colour of this track label * * @param theCol * the colour */ @Override @FireReformatted public final void setColor(final Color theCol) { // do the parent super.setColor(theCol); // now do our processing _theLabel.setColor(theCol); } /** * the setter function which passes through the track */ private void setFixes(final FixSetter setter, final HiResDate theVal) { if (theVal == null) { return; } final long freq = theVal.getMicros(); // briefly check if we are revealing/hiding all times (ie if freq is 1 // or 0) if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY) { // show all of the labels final Enumeration<Editable> iter = getPositions(); while (iter.hasMoreElements()) { final FixWrapper fw = (FixWrapper) iter.nextElement(); setter.execute(fw, true); } } else { // no, we're not just blindly doing all of them. do them at the // correct // frequency // hide all of the labels/symbols first final Enumeration<Editable> enumA = getPositions(); while (enumA.hasMoreElements()) { final FixWrapper fw = (FixWrapper) enumA.nextElement(); setter.execute(fw, false); } if (freq == 0) { // we can ignore this, since we have just hidden all of the // points } else { if (getStartDTG() != null) { // pass through the track setting the values // sort out the start and finish times long start_time = getStartDTG().getMicros(); final long end_time = getEndDTG().getMicros(); // first check that there is a valid time period between start // time // and end time if (start_time + freq < end_time) { long num = start_time / freq; // we need to add one to the quotient if it has rounded down if (start_time % freq == 0) { // start is at our freq, so we don't need to increment } else { num++; } // calculate new start time start_time = num * freq; } else { // there is not one of our 'intervals' between the start and // the end, // so use the start time } while (start_time <= end_time) { // right, increment the start time by one, because we were // getting the // fix immediately before the requested time final HiResDate thisDTG = new HiResDate(0, start_time); final MWC.GenericData.Watchable[] list = this.getNearestTo(thisDTG); // check we found some if (list.length > 0) { final FixWrapper fw = (FixWrapper) list[0]; setter.execute(fw, true); } // produce the next time step start_time += freq; } } } } } @Override public final void setInterpolatePoints(final boolean val) { _interpolatePoints = val; } /** * set the label frequency (in seconds) * * @param theVal * frequency to use */ public final void setLabelFrequency(final HiResDate theVal) { this._lastLabelFrequency = theVal; final FixSetter setLabel = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setLabelShowing(val); } }; setFixes(setLabel, theVal); } // track-shifting operation // support for dragging the track around /** * set the style used for plotting the lines for this track * * @param val */ public void setLineStyle(final int val) { _lineStyle = val; } /** * the line thickness (convenience wrapper around width) */ public void setLineThickness(final int val) { _lineWidth = val; } /** * whether to link points * * @param linkPositions */ public void setLinkPositions(final boolean linkPositions) { _linkPositions = linkPositions; } /** * set the name of this track (normally the name of the vessel * * @param theName * the name as a String */ @Override @FireReformatted public final void setName(final String theName) { _theLabel.setString(theName); } /** * whether to show the track name at the start or end of the track * * @param val * yes no for <I>show label at start</I> */ public final void setNameAtStart(final boolean val) { _LabelAtStart = val; } /** * the relative location of the label * * @param val * the relative location */ public final void setNameLocation(final Integer val) { _theLabel.setRelativeLocation(val); } /** * whether to show the track name * * @param val * yes/no */ public final void setNameVisible(final boolean val) { _theLabel.setVisible(val); } public void setPlotArrayCentre(final boolean plotArrayCentre) { _plotArrayCentre = plotArrayCentre; } /** * whether to show the position fixes * * @param val * yes/no */ public final void setPositionsVisible(final boolean val) { _showPositions = val; } /** * set the data frequency (in seconds) for the track & sensor data * * @param theVal * frequency to use */ @FireExtended public final void setResampleDataAt(final HiResDate theVal) { this._lastDataFrequency = theVal; // have a go at trimming the start time to a whole number of intervals final long interval = theVal.getMicros(); // do we have a start time (we may just be being tested...) if (this.getStartDTG() == null) { return; } final long currentStart = this.getStartDTG().getMicros(); long startTime = (currentStart / interval) * interval; // just check we're in the range if (startTime < currentStart) { startTime += interval; } // just check it's not a barking frequency if (theVal.getDate().getTime() <= 0) { // ignore, we don't need to do anything for a zero or a -1 } else { final SegmentList segments = _thePositions; final Enumeration<Editable> theEnum = segments.elements(); while (theEnum.hasMoreElements()) { final TrackSegment seg = (TrackSegment) theEnum.nextElement(); seg.decimate(theVal, this, startTime); } // start off with the sensor data if (_mySensors != null) { for (final Enumeration<Editable> iterator = _mySensors.elements(); iterator .hasMoreElements();) { final SensorWrapper thisS = (SensorWrapper) iterator.nextElement(); thisS.decimate(theVal, startTime); } } // now the solutions if (_mySolutions != null) { for (final Enumeration<Editable> iterator = _mySolutions.elements(); iterator .hasMoreElements();) { final TMAWrapper thisT = (TMAWrapper) iterator.nextElement(); thisT.decimate(theVal, startTime); } } } } public final void setSymbolColor(final Color col) { _theSnailShape.setColor(col); } /** * how frequently symbols are placed on the track * * @param theVal * frequency in seconds */ public final void setSymbolFrequency(final HiResDate theVal) { this._lastSymbolFrequency = theVal; // set the "showPositions" parameter, as long as we are // not setting the symbols off if (theVal == null) { return; } if (theVal.getMicros() != 0.0) { this.setPositionsVisible(true); } final FixSetter setSymbols = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setSymbolShowing(val); } }; setFixes(setSymbols, theVal); } public void setSymbolLength(final WorldDistance symbolLength) { if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; sym.setLength(symbolLength); } } public final void setSymbolType(final String val) { // is this the type of our symbol? if (val.equals(_theSnailShape.getType())) { // don't bother we're using it already } else { // remember the size of the symbol final double scale = _theSnailShape.getScaleVal(); // remember the color of the symbol final Color oldCol = _theSnailShape.getColor(); // replace our symbol with this new one _theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val); _theSnailShape.setColor(oldCol); _theSnailShape.setScaleVal(scale); } } public void setSymbolWidth(final WorldDistance symbolWidth) { if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; sym.setHeight(symbolWidth); } } // note we are putting a track-labelled wrapper around the colour // parameter, to make the properties window less confusing /** * the colour of the points on the track * * @param theCol * the colour to use */ @FireReformatted public final void setTrackColor(final Color theCol) { setColor(theCol); } /** * font handler * * @param font * the font to use for the label */ public final void setTrackFont(final java.awt.Font font) { _theLabel.setFont(font); } @Override public void shift(final WorldLocation feature, final WorldVector vector) { feature.addToMe(vector); // right, one of our fixes has moved. get the sensors to update // themselves fixMoved(); } @Override public void shift(final WorldVector vector) { this.shiftTrack(elements(), vector); } /** * move the whole of the track be the provided offset */ public final void shiftTrack(final Enumeration<Editable> theEnum, final WorldVector offset) { Enumeration<Editable> enumA = theEnum; // keep track of if the track contains something that doesn't get // dragged boolean handledData = false; if (enumA == null) { enumA = elements(); } while (enumA.hasMoreElements()) { final Object thisO = enumA.nextElement(); if (thisO instanceof TrackSegment) { final TrackSegment seg = (TrackSegment) thisO; seg.shift(offset); // ok - job well done handledData = true; } else if (thisO instanceof SegmentList) { final SegmentList list = (SegmentList) thisO; final Collection<Editable> items = list.getData(); for (final Iterator<Editable> iterator = items.iterator(); iterator .hasNext();) { final TrackSegment segment = (TrackSegment) iterator.next(); segment.shift(offset); } handledData = true; } else if (thisO instanceof SensorWrapper) { final SensorWrapper sw = (SensorWrapper) thisO; final Enumeration<Editable> enumS = sw.elements(); while (enumS.hasMoreElements()) { final SensorContactWrapper scw = (SensorContactWrapper) enumS.nextElement(); // does this fix have it's own origin? final WorldLocation sensorOrigin = scw.getOrigin(); if (sensorOrigin != null) { // create new object to contain the updated location final WorldLocation newSensorLocation = new WorldLocation(sensorOrigin); newSensorLocation.addToMe(offset); // so the contact did have an origin, change it scw.setOrigin(newSensorLocation); } } // looping through the contacts // ok - job well done handledData = true; } // whether this is a sensor wrapper else if (thisO instanceof TrackSegment) { final TrackSegment tw = (TrackSegment) thisO; final Enumeration<Editable> enumS = tw.elements(); // fire recursively, smart-arse. shiftTrack(enumS, offset); // ok - job well done handledData = true; } // whether this is a sensor wrapper } // looping through this track // ok, did we handle the data? if (!handledData) { System.err.println("TrackWrapper problem; not able to shift:" + enumA); } } /** * if we've got a relative track segment, it only learns where its individual fixes are once * they've been initialised. This is where we do it. */ public void sortOutRelativePositions() { final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); // SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN // RELATIVE MODE final boolean isRelative = seg.getPlotRelative(); WorldLocation tmaLastLoc = null; long tmaLastDTG = 0; // if it's not a relative track, and it's not visible, we don't // need to // work with ut if (!isRelative) { continue; } final Enumeration<Editable> fixWrappers = seg.elements(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); // now there's a chance that our fix has forgotten it's parent, // particularly if it's the victim of a // copy/paste operation. Tell it about it's children fw.setTrackWrapper(this); // ok, are we in relative? if (isRelative) { final long thisTime = fw.getDateTimeGroup().getDate().getTime(); // ok, is this our first location? if (tmaLastLoc == null) { tmaLastLoc = new WorldLocation(seg.getTrackStart()); } else { // calculate a new vector final long timeDelta = thisTime - tmaLastDTG; if (lastFix != null) { final double speedKts = lastFix.getSpeed(); final double courseRads = lastFix.getCourse(); final double depthM = lastFix.getDepth(); // use the value of depth as read in from the file tmaLastLoc.setDepth(depthM); final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts, courseRads); tmaLastLoc.addToMe(thisVec); } } lastFix = fw; tmaLastDTG = thisTime; // dump the location into the fix fw.setFixLocationSilent(new WorldLocation(tmaLastLoc)); } } } } /** * split this whole track into two sub-tracks * * @param splitPoint * the point at which we perform the split * @param splitBeforePoint * whether to put split before or after specified point * @return a list of the new track segments (used for subsequent undo operations) */ public Vector<TrackSegment> splitTrack(final FixWrapper splitPoint, final boolean splitBeforePoint) { FixWrapper splitPnt = splitPoint; Vector<TrackSegment> res = null; TrackSegment relevantSegment = null; // are we still in one section? if (_thePositions.size() == 1) { relevantSegment = (TrackSegment) _thePositions.first(); // yup, looks like we're going to be splitting it. // better give it a proper name relevantSegment.setName(relevantSegment.startDTG().getDate().toString()); } else { // ok, find which segment contains our data final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); if (seg.getData().contains(splitPnt)) { relevantSegment = seg; break; } } } if (relevantSegment == null) { throw new RuntimeException( "failed to provide relevant segment, alg will break"); } // hmm, if we're splitting after the point, we need to move along the // bus by // one if (!splitBeforePoint) { final Collection<Editable> items = relevantSegment.getData(); final Iterator<Editable> theI = items.iterator(); Editable previous = null; while (theI.hasNext()) { final Editable thisE = theI.next(); // have we chosen to remember the previous item? if (previous != null) { // yes, this must be the one we're after splitPnt = (FixWrapper) thisE; break; } // is this the one we're looking for? if (thisE == splitPnt) { // yup, remember it - we want to use the next value previous = thisE; } } } // yup, do our first split final SortedSet<Editable> p1 = relevantSegment.headSet(splitPnt); final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPnt); // get our results ready final TrackSegment ts1, ts2; // aaah, just sort out if we are splitting a TMA segment, in which case // want to create two // tma segments, not track segments if (relevantSegment instanceof RelativeTMASegment) { final RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment; // find the ownship location at the relevant time WorldLocation secondLegOrigin = null; // get the time of the split final HiResDate splitTime = splitPnt.getDateTimeGroup(); // aah, sort out if we are splitting before or after. SensorWrapper sensor = theTMA.getReferenceSensor(); if (sensor != null) { Watchable[] nearestF = sensor.getNearestTo(splitTime); if ((nearestF != null) && (nearestF.length > 0)) { SensorContactWrapper scw = (SensorContactWrapper) nearestF[0]; secondLegOrigin = scw.getCalculatedOrigin(null); } } // if we couldn't get a sensor origin, try for the track origin if (secondLegOrigin == null) { final Watchable firstMatch = theTMA.getReferenceTrack().getNearestTo(splitTime)[0]; secondLegOrigin = firstMatch.getLocation(); } final WorldVector secondOffset = splitPnt.getLocation().subtract(secondLegOrigin); // put the lists back into plottable layers final RelativeTMASegment tr1 = new RelativeTMASegment(theTMA, p1, theTMA.getOffset()); final RelativeTMASegment tr2 = new RelativeTMASegment(theTMA, p2, secondOffset); // update the freq's tr1.setBaseFrequency(theTMA.getBaseFrequency()); tr2.setBaseFrequency(theTMA.getBaseFrequency()); // and store them ts1 = tr1; ts2 = tr2; } else if (relevantSegment instanceof AbsoluteTMASegment) { final AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment; // aah, sort out if we are splitting before or after. // find out the offset at the split point, so we can initiate it for // the // second part of the track final Watchable[] matches = this.getNearestTo(splitPnt.getDateTimeGroup()); final WorldLocation origin = matches[0].getLocation(); final FixWrapper t1Start = (FixWrapper) p1.first(); // put the lists back into plottable layers final AbsoluteTMASegment tr1 = new AbsoluteTMASegment(theTMA, p1, t1Start.getLocation(), null, null); final AbsoluteTMASegment tr2 = new AbsoluteTMASegment(theTMA, p2, origin, null, null); // update the freq's tr1.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); tr2.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); // and store them ts1 = tr1; ts2 = tr2; } else { // put the lists back into plottable layers ts1 = new TrackSegment(p1); ts2 = new TrackSegment(p2); } // now clear the positions _thePositions.removeElement(relevantSegment); // and put back our new layers _thePositions.addSegment(ts1); _thePositions.addSegment(ts2); // remember them res = new Vector<TrackSegment>(); res.add(ts1); res.add(ts2); return res; } /** * extra parameter, so that jvm can produce a sensible name for this * * @return the track name, as a string */ @Override public final String toString() { return "Track:" + getName(); } /** * is this track visible between these time periods? * * @param start * start DTG * @param end * end DTG * @return yes/no */ public final boolean visibleBetween(final HiResDate start, final HiResDate end) { boolean visible = false; if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start))) { visible = true; } return visible; } /** * Calculates Course & Speed for the track. */ public void calcCourseSpeed() { // step through our fixes final Enumeration<Editable> iter = getPositions(); FixWrapper prevFw = null; while (iter.hasMoreElements()) { final FixWrapper currFw = (FixWrapper) iter.nextElement(); if (prevFw == null) prevFw = currFw; else { // calculate the course final WorldVector wv = currFw.getLocation().subtract(prevFw.getLocation()); prevFw.getFix().setCourse(wv.getBearing()); // also, set the correct label alignment currFw.resetLabelLocation(); // calculate the speed // get distance in meters final WorldDistance wd = new WorldDistance(wv); final double distance = wd.getValueIn(WorldDistance.METRES); // get time difference in seconds final long timeDifference = (currFw.getTime().getMicros() - prevFw.getTime().getMicros()) / 1000000; // get speed in meters per second and convert it to knots final WorldSpeed speed = new WorldSpeed(distance / timeDifference, WorldSpeed.M_sec); final double knots = WorldSpeed.convert(WorldSpeed.M_sec, WorldSpeed.Kts, speed .getValue()); prevFw.setSpeed(knots); prevFw = currFw; } } } public void trimTo(TimePeriod period) { if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); sw.trimTo(period); } } if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); sw.trimTo(period); } } if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); sw.trimTo(period); } } if (_thePositions != null) { final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); seg.trimTo(period); } } } @Override public Enumeration<Editable> segments() { return elements(); } /** * accessor to determine if this is a relative track * * @return */ public boolean isTMATrack() { boolean res = false; if (_thePositions != null) if (_thePositions.size() > 0) if (_thePositions.first() instanceof CoreTMASegment) { res = true; } return res; } @Override public int compareTo(Plottable arg0) { Integer answer = null; // SPECIAL PROCESSING: we wish to push TMA tracks to the top of any // tracks shown in the outline view. // is he a track? if (arg0 instanceof TrackWrapper) { TrackWrapper other = (TrackWrapper) arg0; // yes, he's a track. See if we're a relative track boolean iAmTMA = isTMATrack(); // is he relative? boolean heIsTMA = other.isTMATrack(); if (heIsTMA) { // ok, he's a TMA segment. now we need to sort out if we are. if (iAmTMA) { // we're both relative, compare names answer = getName().compareTo(other.getName()); } else { // only he is relative, he comes first answer = 1; } } else { // he's not relative. am I? if (iAmTMA) { // I am , so go first answer = -1; } } } else { // we're a track, they're not - put us at the end! answer = 1; } // if we haven't worked anything out yet, just use the parent implementation if (answer == null) answer = super.compareTo(arg0); return answer; } @Override public void paint(CanvasType dest, long time) { if (!getVisible()) return; // set the thickness for this track dest.setLineWidth(_lineWidth); // and set the initial colour for this track if (getColor() != null) dest.setColor(getColor()); // we plot only the dynamic arcs because they are MovingPlottable if (_myDynamicShapes.getVisible()) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); // and do the paint sw.paint(dest, time); } } } @SuppressWarnings("serial") @Override public void setLayers(Layers parent) { _myLayers = parent; // have a go at a format _myLayers.addNewItemListener(new CoreFormatItemListener("Show Symbols", this.getName(), null, 15 * 60 * 1000, true) { @Override protected void formatTrack(TrackWrapper track, HiResDate interval) { track.setSymbolFrequency(interval); } @Override protected void applyFormat(FixWrapper fix) { fix.setSymbolShowing(true); } }); _myLayers.addNewItemListener(new CoreFormatItemListener("Show labels", this .getName(), null, 30 * 60 * 1000, true) { @Override protected void formatTrack(TrackWrapper track, HiResDate interval) { track.setLabelFrequency(interval); } @Override protected void applyFormat(FixWrapper fix) { fix.setLabelShowing(true); } }); _myLayers.addNewItemListener(new CoreFormatItemListener("Show arrows", this .getName(), null, 10 * 60 * 1000, true) { @Override protected void formatTrack(TrackWrapper track, HiResDate interval) { track.setArrowFrequency(interval); } @Override protected void applyFormat(FixWrapper fix) { fix.setArrowShowing(true); } }); } }
// Revision 1.1 1999-01-31 13:33:08+00 sm11td // Initial revision package Debrief.Wrappers; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.beans.IntrospectionException; import java.beans.MethodDescriptor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import Debrief.ReaderWriter.Replay.FormatTracks; import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeSetWrapper; import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeWrapper; import Debrief.Wrappers.Track.AbsoluteTMASegment; import Debrief.Wrappers.Track.CoreTMASegment; import Debrief.Wrappers.Track.PlanningSegment; import Debrief.Wrappers.Track.RelativeTMASegment; import Debrief.Wrappers.Track.SplittableLayer; import Debrief.Wrappers.Track.TrackSegment; import Debrief.Wrappers.Track.TrackWrapper_Support; import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter; import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList; import Debrief.Wrappers.Track.WormInHoleOffset; import MWC.GUI.BaseLayer; import MWC.GUI.CanvasType; import MWC.GUI.DynamicPlottable; import MWC.GUI.Editable; import MWC.GUI.FireExtended; import MWC.GUI.FireReformatted; import MWC.GUI.Layer; import MWC.GUI.Layer.ProvidesContiguousElements; import MWC.GUI.Layers; import MWC.GUI.MessageProvider; import MWC.GUI.PlainWrapper; import MWC.GUI.Plottable; import MWC.GUI.Canvas.CanvasTypeUtilities; import MWC.GUI.Properties.LineStylePropertyEditor; import MWC.GUI.Properties.TimeFrequencyPropertyEditor; import MWC.GUI.Shapes.DraggableItem; import MWC.GUI.Shapes.HasDraggableComponents; import MWC.GUI.Shapes.TextLabel; import MWC.GUI.Shapes.Symbols.Vessels.WorldScaledSym; import MWC.GenericData.HiResDate; import MWC.GenericData.TimePeriod; import MWC.GenericData.Watchable; import MWC.GenericData.WatchableList; import MWC.GenericData.WorldArea; import MWC.GenericData.WorldDistance; import MWC.GenericData.WorldDistance.ArrayLength; import MWC.GenericData.WorldLocation; import MWC.GenericData.WorldSpeed; import MWC.GenericData.WorldVector; import MWC.TacticalData.Fix; import MWC.Utilities.TextFormatting.FormatRNDateTime; /** * the TrackWrapper maintains the GUI and data attributes of the whole track iteself, but the * responsibility for the fixes within the track are demoted to the FixWrapper */ public class TrackWrapper extends MWC.GUI.PlainWrapper implements WatchableList, MWC.GUI.Layer, DraggableItem, HasDraggableComponents, ProvidesContiguousElements, ISecondaryTrack, DynamicPlottable { // member variables /** * class containing editable details of a track */ public final class trackInfo extends Editable.EditorType implements Editable.DynamicDescriptors { /** * constructor for this editor, takes the actual track as a parameter * * @param data * track being edited */ public trackInfo(final TrackWrapper data) { super(data, data.getName(), ""); } @Override public final MethodDescriptor[] getMethodDescriptors() { // just add the reset color field first final Class<TrackWrapper> c = TrackWrapper.class; final MethodDescriptor[] mds = { method(c, "exportThis", null, "Export Shape"), method(c, "resetLabels", null, "Reset DTG Labels"), method(c, "calcCourseSpeed", null/* no params */, "Generate calculated Course and Speed")}; return mds; } @Override public final String getName() { return super.getName(); } @Override public final PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor[] res = { displayExpertProp("SymbolType", "Symbol type", "the type of symbol plotted for this label", FORMAT), displayExpertProp("LineThickness", "Line thickness", "the width to draw this track", FORMAT), expertProp("Name", "the track name"), displayExpertProp("InterpolatePoints", "Interpolate points", "whether to interpolate points between known data points", SPATIAL), expertProp("Color", "the track color", FORMAT), displayExpertProp("SymbolColor", "Symbol color", "the color of the symbol (when used)", FORMAT), displayExpertProp( "PlotArrayCentre", "Plot array centre", "highlight the sensor array centre when non-zero array length provided", FORMAT), displayExpertProp("TrackFont", "Track font", "the track label font", FORMAT), displayExpertProp("NameVisible", "Name visible", "show the track label", VISIBILITY), displayExpertProp("PositionsVisible", "Positions visible", "show individual Positions", VISIBILITY), displayExpertProp("NameAtStart", "Name at start", "whether to show the track name at the start (or end)", VISIBILITY), displayExpertProp("LinkPositions", "Link positions", "whether to join the track points", FORMAT), expertProp("Visible", "whether the track is visible", VISIBILITY), displayExpertLongProp("NameLocation", "Name location", "relative location of track label", MWC.GUI.Properties.LocationPropertyEditor.class), displayExpertLongProp("LabelFrequency", "Label frequency", "the label frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("SymbolFrequency", "Symbol frequency", "the symbol frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("ResampleDataAt", "Resample data at", "the data sample rate", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("ArrowFrequency", "Arrow frequency", "the direction marker frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), displayExpertLongProp("LineStyle", "Line style", "the line style used to join track points", MWC.GUI.Properties.LineStylePropertyEditor.class), }; res[0] .setPropertyEditorClass(MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor.class); res[1] .setPropertyEditorClass(MWC.GUI.Properties.LineWidthPropertyEditor.class); // SPECIAL CASE: if we have a world scaled symbol, provide // editors for // the symbol size final TrackWrapper item = (TrackWrapper) this.getData(); if (item._theSnailShape instanceof WorldScaledSym) { // yes = better create height/width editors final PropertyDescriptor[] res2 = new PropertyDescriptor[res.length + 2]; System.arraycopy(res, 0, res2, 2, res.length); res2[0] = displayExpertProp("SymbolLength", "Symbol length", "Length of symbol", FORMAT); res2[1] = displayExpertProp("SymbolWidth", "Symbol width", "Width of symbol", FORMAT); // and now use the new value res = res2; } return res; } catch (final IntrospectionException e) { return super.getPropertyDescriptors(); } } } private static final String SOLUTIONS_LAYER_NAME = "Solutions"; public static final String SENSORS_LAYER_NAME = "Sensors"; public static final String DYNAMIC_SHAPES_LAYER_NAME = "Dynamic Shapes"; /** * keep track of versions - version id */ static final long serialVersionUID = 1; /** * put the other objects into this one as children * * @param wrapper * whose going to receive it * @param theLayers * the top level layers object * @param parents * the track wrapppers containing the children * @param subjects * the items to insert. */ public static void groupTracks(final TrackWrapper target, final Layers theLayers, final Layer[] parents, final Editable[] subjects) { // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; final TrackWrapper thisP = (TrackWrapper) parents[i]; if (thisL != target) { // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment ts = (TrackSegment) segs.nextElement(); // reset the name if we need to if (ts.getName().startsWith("Posi")) { ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate() .getTime())); } target.add(ts); } } else { if (obj instanceof TrackSegment) { final TrackSegment ts = (TrackSegment) obj; // reset the name if we need to if (ts.getName().startsWith("Posi")) { ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate() .getTime())); } // and remember it target.add(ts); } } } } else { // get it's data, and add it to the target target.add(thisL); } // and remove the layer from it's parent if (thisL instanceof TrackSegment) { thisP.removeElement(thisL); // does this just leave an empty husk? if (thisP.numFixes() == 0) { // may as well ditch it anyway theLayers.removeThisLayer(thisP); } } else { // we'll just remove it from the top level layer theLayers.removeThisLayer(thisL); } } } } /** * perform a merge of the supplied tracks. * * @param target * the final recipient of the other items * @param theLayers * @param parents * the parent tracks for the supplied items * @param subjects * the actual selected items * @return sufficient information to undo the merge */ public static int mergeTracksInPlace(final Editable target, final Layers theLayers, final Layer[] parents, final Editable[] subjects) { // where we dump the new data points Layer receiver = (Layer) target; // check that the legs don't overlap String failedMsg = checkTheyAreNotOverlapping(subjects); // how did we get on? if (failedMsg != null) { MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg + " overlap in time. Please correct this and retry", MessageProvider.ERROR); return MessageProvider.ERROR; } // right, if the target is a TMA track, we have to change it into a // proper // track, since // the merged tracks probably contain manoeuvres if (target instanceof CoreTMASegment) { final CoreTMASegment tma = (CoreTMASegment) target; final TrackSegment newSegment = new TrackSegment(tma); // now do some fancy footwork to remove the target from the wrapper, // and // replace it with our new segment newSegment.getWrapper().removeElement(target); newSegment.getWrapper().add(newSegment); // store the new segment into the receiver receiver = newSegment; } // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; final TrackWrapper thisP = (TrackWrapper) parents[i]; // is this the target item (note we're comparing against the item // passed // in, not our // temporary receiver, since the receiver may now be a tracksegment, // not a // TMA segment if (thisL != target) { // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment ts = (TrackSegment) segs.nextElement(); receiver.add(ts); } } else { final Layer ts = (Layer) obj; receiver.append(ts); } } } else { // get it's data, and add it to the target receiver.append(thisL); } // and remove the layer from it's parent if (thisL instanceof TrackSegment) { thisP.removeElement(thisL); // does this just leave an empty husk? if (thisP.numFixes() == 0) { // may as well ditch it anyway theLayers.removeThisLayer(thisP); } } else { // we'll just remove it from the top level layer theLayers.removeThisLayer(thisL); } } } return MessageProvider.OK; } /** * perform a merge of the supplied tracks. * * @param target * the final recipient of the other items * @param theLayers * @param parents * the parent tracks for the supplied items * @param subjects * the actual selected items * @param _newName * name to give to the merged object * @return sufficient information to undo the merge */ public static int mergeTracks(final TrackWrapper recipient, final Layers theLayers, final Editable[] subjects) { // where we dump the new data points TrackWrapper newTrack = (TrackWrapper) recipient; // check that the legs don't overlap String failedMsg = checkTheyAreNotOverlapping(subjects); // how did we get on? if (failedMsg != null) { MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg + " overlap in time. Please correct this and retry", MessageProvider.ERROR); return MessageProvider.ERROR; } // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; TrackSegment newT = new TrackSegment(); duplicateFixes(sl, newT); newTrack.add(newT); } else if (obj instanceof TrackSegment) { TrackSegment ts = (TrackSegment) obj; // ok, duplicate the fixes in this segment TrackSegment newT = new TrackSegment(); duplicateFixes(ts, newT); // and add it to the new track newTrack.append(newT); } } } else if (thisL instanceof TrackSegment) { TrackSegment ts = (TrackSegment) thisL; // ok, duplicate the fixes in this segment TrackSegment newT = new TrackSegment(); duplicateFixes(ts, newT); // and add it to the new track newTrack.append(newT); } else if (thisL instanceof SegmentList) { SegmentList sl = (SegmentList) thisL; TrackSegment newT = new TrackSegment(); // ok, duplicate the fixes in this segment duplicateFixes(sl, newT); // and add it to the new track newTrack.append(newT); } } // and store the new track theLayers.addThisLayer(newTrack); return MessageProvider.OK; } private static void duplicateFixes(SegmentList sl, TrackSegment target) { final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment segment = (TrackSegment) segs.nextElement(); if (segment instanceof CoreTMASegment) { CoreTMASegment ct = (CoreTMASegment) segment; TrackSegment newSeg = new TrackSegment(ct); duplicateFixes(newSeg, target); } else { duplicateFixes(segment, target); } } } private static void duplicateFixes(TrackSegment source, TrackSegment target) { // ok, retrieve the points in the track segment Enumeration<Editable> tsPts = source.elements(); while (tsPts.hasMoreElements()) { FixWrapper existingFix = (FixWrapper) tsPts.nextElement(); FixWrapper newF = new FixWrapper(existingFix.getFix()); // also duplicate the label newF.setLabel(existingFix.getLabel()); target.addFix(newF); } } private static String checkTheyAreNotOverlapping(final Editable[] subjects) { // first, check they don't overlap. // start off by collecting the periods final TimePeriod[] _periods = new TimePeriod.BaseTimePeriod[subjects.length]; for (int i = 0; i < subjects.length; i++) { final Editable editable = subjects[i]; TimePeriod thisPeriod = null; if (editable instanceof TrackWrapper) { final TrackWrapper tw = (TrackWrapper) editable; thisPeriod = new TimePeriod.BaseTimePeriod(tw.getStartDTG(), tw.getEndDTG()); } else if (editable instanceof TrackSegment) { final TrackSegment ts = (TrackSegment) editable; thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG()); } _periods[i] = thisPeriod; } // now test them. String failedMsg = null; for (int i = 0; i < _periods.length; i++) { final TimePeriod timePeriod = _periods[i]; for (int j = 0; j < _periods.length; j++) { final TimePeriod timePeriod2 = _periods[j]; // check it's not us if (timePeriod2 != timePeriod) { if (timePeriod.overlaps(timePeriod2)) { failedMsg = "'" + subjects[i].getName() + "' and '" + subjects[j].getName() + "'"; break; } } } } return failedMsg; } /** * whether to interpolate points in this track */ private boolean _interpolatePoints = false; /** * the end of the track to plot the label */ private boolean _LabelAtStart = true; private HiResDate _lastLabelFrequency = null; private HiResDate _lastSymbolFrequency = null; private HiResDate _lastArrowFrequency = null; private HiResDate _lastDataFrequency = new HiResDate(0, TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY); /** * the width of this track */ private int _lineWidth = 3; /** * the style of this line * */ private int _lineStyle = CanvasType.SOLID; /** * whether or not to link the Positions */ private boolean _linkPositions; /** * whether to show a highlight for the array centre * */ private boolean _plotArrayCentre; /** * our editable details */ protected transient Editable.EditorType _myEditor = null; /** * keep a list of points waiting to be plotted * */ transient int[] _myPts; /** * the sensor tracks for this vessel */ final private BaseLayer _mySensors; /** * the dynamic shapes for this vessel */ final private BaseLayer _myDynamicShapes; /** * the TMA solutions for this vessel */ final private BaseLayer _mySolutions; /** * keep track of how far we are through our array of points * */ transient int _ptCtr = 0; /** * whether or not to show the Positions */ private boolean _showPositions; /** * the label describing this track */ private final MWC.GUI.Shapes.TextLabel _theLabel; /** * the list of wrappers we hold */ protected SegmentList _thePositions; /** * the symbol to pass on to a snail plotter */ private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape; /** * working ZERO location value, to reduce number of working values */ final private WorldLocation _zeroLocation = new WorldLocation(0, 0, 0); // member functions transient private FixWrapper finisher; transient private HiResDate lastDTG; transient private FixWrapper lastFix; // for getNearestTo transient private FixWrapper nearestFix; /** * working parameters */ // for getFixesBetween transient private FixWrapper starter; transient private TimePeriod _myTimePeriod; transient private WorldArea _myWorldArea; transient private final PropertyChangeListener _locationListener; // constructors /** * Wrapper for a Track (a series of position fixes). It combines the data with the formatting * details */ public TrackWrapper() { _mySensors = new SplittableLayer(true); _mySensors.setName(SENSORS_LAYER_NAME); _myDynamicShapes = new SplittableLayer(true); _myDynamicShapes.setName(DYNAMIC_SHAPES_LAYER_NAME); _mySolutions = new BaseLayer(true); _mySolutions.setName(SOLUTIONS_LAYER_NAME); // create a property listener for when fixes are moved _locationListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent arg0) { fixMoved(); } }; _linkPositions = true; // start off with positions showing (although the default setting for a // fix // is to not show a symbol anyway). We need to make this "true" so that // when a fix position is set to visible it is not over-ridden by this // setting _showPositions = true; _theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null); // set an initial location for the label _theLabel.setRelativeLocation(new Integer( MWC.GUI.Properties.LocationPropertyEditor.RIGHT)); // initialise the symbol to use for plotting this track in snail mode _theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol("Submarine"); // declare our arrays _thePositions = new TrackWrapper_Support.SegmentList(); _thePositions.setWrapper(this); } /** * add the indicated point to the track * * @param point * the point to add */ @Override public void add(final MWC.GUI.Editable point) { boolean done = false; // see what type of object this is if (point instanceof FixWrapper) { final FixWrapper fw = (FixWrapper) point; fw.setTrackWrapper(this); addFix(fw); done = true; } // is this a sensor? else if (point instanceof SensorWrapper) { final SensorWrapper swr = (SensorWrapper) point; // see if we already have a sensor with this name SensorWrapper existing = null; Enumeration<Editable> enumer = _mySensors.elements(); while (enumer.hasMoreElements()) { SensorWrapper oldS = (SensorWrapper) enumer.nextElement(); // does this have the same name? if (oldS.getName().equals(swr.getName())) { // yes - ok, remember it existing = oldS; // and append the data points existing.append(swr); } } // did we find it already? if (existing == null) { // nope, so store it _mySensors.add(swr); } // tell the sensor about us swr.setHost(this); // and the track name (if we're loading from REP it will already // know // the name, but if this data is being pasted in, it may start with // a different // parent track name - so override it here) swr.setTrackName(this.getName()); // indicate success done = true; } // is this a dynamic shape? else if (point instanceof DynamicTrackShapeSetWrapper) { final DynamicTrackShapeSetWrapper swr = (DynamicTrackShapeSetWrapper) point; // just check we don't alraedy have it if (_myDynamicShapes.contains(swr)) { MWC.Utilities.Errors.Trace .trace("Don't allow duplicate shape set name:" + swr.getName()); } else { // add to our list _myDynamicShapes.add(swr); // tell the sensor about us swr.setHost(this); // indicate success done = true; } } // is this a TMA solution track? else if (point instanceof TMAWrapper) { final TMAWrapper twr = (TMAWrapper) point; // add to our list _mySolutions.add(twr); // tell the sensor about us twr.setHost(this); // and the track name (if we're loading from REP it will already // know // the name, but if this data is being pasted in, it may start with // a different // parent track name - so override it here) twr.setTrackName(this.getName()); // indicate success done = true; } else if (point instanceof TrackSegment) { final TrackSegment seg = (TrackSegment) point; seg.setWrapper(this); _thePositions.addSegment((TrackSegment) point); done = true; // hey, sort out the positions sortOutRelativePositions(); } if (!done) { MWC.GUI.Dialogs.DialogFactory.showMessage("Add point", "Sorry it is not possible to add:" + point.getName() + " to " + this.getName()); } } /** * append this other layer to ourselves (although we don't really bother with it) * * @param other * the layer to add to ourselves */ @Override public void append(final Layer other) { // is it a track? if ((other instanceof TrackWrapper) || (other instanceof TrackSegment)) { // yes, break it down. final java.util.Enumeration<Editable> iter = other.elements(); while (iter.hasMoreElements()) { final Editable nextItem = iter.nextElement(); if (nextItem instanceof Layer) { append((Layer) nextItem); } else { add(nextItem); } } } else { // nope, just add it to us. add(other); } } /** * instruct this object to clear itself out, ready for ditching */ @Override public final void closeMe() { // and my objects // first ask them to close themselves final Enumeration<Editable> it = getPositions(); while (it.hasMoreElements()) { final Object val = it.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _thePositions.removeAllElements(); _thePositions = null; // and my objects // first ask the sensors to close themselves if (_mySensors != null) { final Enumeration<Editable> it2 = _mySensors.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _mySensors.removeAllElements(); } // and my objects // first ask the sensors to close themselves if (_myDynamicShapes != null) { final Enumeration<Editable> it2 = _myDynamicShapes.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _myDynamicShapes.removeAllElements(); } // now ask the solutions to close themselves if (_mySolutions != null) { final Enumeration<Editable> it2 = _mySolutions.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _mySolutions.removeAllElements(); } // and our utility objects finisher = null; lastFix = null; nearestFix = null; starter = null; // and our editor _myEditor = null; // now get the parent to close itself super.closeMe(); } /** * switch the two track sections into one track section * * @param res * the previously split track sections */ public void combineSections(final Vector<TrackSegment> res) { // ok, remember the first final TrackSegment keeper = res.firstElement(); // now remove them all, adding them to the first final Iterator<TrackSegment> iter = res.iterator(); while (iter.hasNext()) { final TrackSegment pl = iter.next(); if (pl != keeper) { keeper.append((Layer) pl); } _thePositions.removeElement(pl); } // and put the keepers back in _thePositions.addSegment(keeper); } /** * return our tiered data as a single series of elements * * @return */ @Override public Enumeration<Editable> contiguousElements() { final Vector<Editable> res = new Vector<Editable>(0, 1); if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // is it visible? if (sw.getVisible()) { res.addAll(sw._myContacts); } } } if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); // is it visible? if (sw.getVisible()) { res.addAll(sw.getData()); } } } if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); if (sw.getVisible()) { res.addAll(sw._myContacts); } } } if (_thePositions != null) { res.addAll(getRawPositions()); } return res.elements(); } /** * get an enumeration of the points in this track * * @return the points in this track */ @Override public Enumeration<Editable> elements() { final TreeSet<Editable> res = new TreeSet<Editable>(); if (_mySensors.size() > 0) { res.add(_mySensors); } if (_myDynamicShapes.size() > 0) { res.add(_myDynamicShapes); } if (_mySolutions.size() > 0) { res.add(_mySolutions); } // ok, we want to wrap our fast-data as a set of plottables // see how many track segments we have if (_thePositions.size() == 1) { // just the one, insert it res.add(_thePositions.first()); } else { // more than one, insert them as a tree res.add(_thePositions); } return new TrackWrapper_Support.IteratorWrapper(res.iterator()); } /** * export this track to REPLAY file */ @Override public final void exportShape() { // call the method in PlainWrapper this.exportThis(); } /** * filter the list to the specified time period, then inform any listeners (such as the time * stepper) * * @param start * the start dtg of the period * @param end * the end dtg of the period */ @Override public final void filterListTo(final HiResDate start, final HiResDate end) { final Enumeration<Editable> fixWrappers = getPositions(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); final HiResDate dtg = fw.getTime(); if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end))) { fw.setVisible(true); } else { fw.setVisible(false); } } // now do the same for our sensor data if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensors } // whether we have any sensors // now do the same for our sensor arc data if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensor arcs } // whether we have any sensor arcs if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensors } // whether we have any sensors // do we have any property listeners? if (getSupport() != null) { final Debrief.GUI.Tote.StepControl.somePeriod newPeriod = new Debrief.GUI.Tote.StepControl.somePeriod(start, end); getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null, newPeriod); } } @Override public void findNearestHotSpotIn(final Point cursorPos, final WorldLocation cursorLoc, final ComponentConstruct currentNearest, final Layer parentLayer) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS); // cycle through the fixes final Enumeration<Editable> fixes = getPositions(); while (fixes.hasMoreElements()) { final FixWrapper thisF = (FixWrapper) fixes.nextElement(); // only check it if it's visible if (thisF.getVisible()) { // how far away is it? thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist); final WorldLocation fixLocation = new WorldLocation(thisF.getLocation()) { private static final long serialVersionUID = 1L; @Override public void addToMe(final WorldVector delta) { super.addToMe(delta); thisF.setFixLocation(this); } }; // try range currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation); } } } @Override public void findNearestHotSpotIn(final Point cursorPos, final WorldLocation cursorLoc, final LocationConstruct currentNearest, final Layer parentLayer, final Layers theData) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS); // cycle through the fixes final Enumeration<Editable> fixes = getPositions(); while (fixes.hasMoreElements()) { final FixWrapper thisF = (FixWrapper) fixes.nextElement(); if (thisF.getVisible()) { // how far away is it? thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist); // is it closer? currentNearest.checkMe(this, thisDist, null, parentLayer); } } } public void findNearestSegmentHotspotFor(final WorldLocation cursorLoc, final Point cursorPt, final LocationConstruct currentNearest) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist; // cycle through the track segments final Collection<Editable> segments = _thePositions.getData(); for (final Iterator<Editable> iterator = segments.iterator(); iterator .hasNext();) { final TrackSegment thisSeg = (TrackSegment) iterator.next(); if (thisSeg.getVisible()) { // how far away is it? thisDist = new WorldDistance(thisSeg.rangeFrom(cursorLoc), WorldDistance.DEGS); // is it closer? currentNearest.checkMe(thisSeg, thisDist, null, this); } } } /** * one of our fixes has moved. better tell any bits that rely on the locations of our bits * * @param theFix * the fix that moved */ public void fixMoved() { if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper nextS = (SensorWrapper) iter.nextElement(); nextS.setHost(this); } } if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper nextS = (DynamicTrackShapeSetWrapper) iter.nextElement(); nextS.setHost(this); } } } /** * return the arrow frequencies for the track * * @return frequency in seconds */ public final HiResDate getArrowFrequency() { return _lastArrowFrequency; } /** * calculate a position the specified distance back along the ownship track (note, we always * interpolate the parent track position) * * @param searchTime * the time we're looking at * @param sensorOffset * how far back the sensor should be * @param wormInHole * whether to plot a straight line back, or make sensor follow ownship * @return the location */ public FixWrapper getBacktraceTo(final HiResDate searchTime, final ArrayLength sensorOffset, final boolean wormInHole) { FixWrapper res = null; if (wormInHole && sensorOffset != null) { res = WormInHoleOffset.getWormOffsetFor(this, searchTime, sensorOffset); } else { final boolean parentInterpolated = getInterpolatePoints(); setInterpolatePoints(true); final MWC.GenericData.Watchable[] list = getNearestTo(searchTime); // and restore the interpolated value setInterpolatePoints(parentInterpolated); FixWrapper wa = null; if (list.length > 0) { wa = (FixWrapper) list[0]; } // did we find it? if (wa != null) { // yes, store it res = new FixWrapper(wa.getFix().makeCopy()); // ok, are we dealing with an offset? if (sensorOffset != null) { // get the current heading final double hdg = wa.getCourse(); // and calculate where it leaves us final WorldVector vector = new WorldVector(hdg, sensorOffset, null); // now apply this vector to the origin res.setLocation(new WorldLocation(res.getLocation().add(vector))); } } } return res; } // editing parameters /** * what geographic area is covered by this track? * * @return get the outer bounds of the area */ @Override public final WorldArea getBounds() { // we no longer just return the bounds of the track, because a portion // of the track may have been made invisible. // instead, we will pass through the full dataset and find the outer // bounds // of the visible area WorldArea res = null; if (!getVisible()) { // hey, we're invisible, return null } else { final Enumeration<Editable> it = getPositions(); while (it.hasMoreElements()) { final FixWrapper fw = (FixWrapper) it.nextElement(); // is this point visible? if (fw.getVisible()) { // has our data been initialised? if (res == null) { // no, initialise it res = new WorldArea(fw.getLocation(), fw.getLocation()); } else { // yes, extend to include the new area res.extend(fw.getLocation()); } } } // also extend to include our sensor data if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final PlainWrapper sw = (PlainWrapper) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // whether we have any sensors // also extend to include our sensor data if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final Plottable sw = (Plottable) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // and our solution data if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final PlainWrapper sw = (PlainWrapper) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // whether we have any sensors } // whether we're visible // SPECIAL CASE: if we're a DR track, the positions all // have the same value if (res != null) { // have we ended up with an empty area? if (res.getHeight() == 0) { // ok - force a bounds update sortOutRelativePositions(); // and retrieve the bounds of hte first segment res = this.getSegments().first().getBounds(); } } return res; } /** * the time of the last fix * * @return the DTG */ @Override public final HiResDate getEndDTG() { HiResDate dtg = null; final TimePeriod res = getTimePeriod(); if (res != null) { dtg = res.getEndDTG(); } return dtg; } /** * the editable details for this track * * @return the details */ @Override public Editable.EditorType getInfo() { if (_myEditor == null) { _myEditor = new trackInfo(this); } return _myEditor; } /** * create a new, interpolated point between the two supplied * * @param previous * the previous point * @param next * the next point * @return and interpolated point */ private final FixWrapper getInterpolatedFix(final FixWrapper previous, final FixWrapper next, final HiResDate requestedDTG) { FixWrapper res = null; // do we have a start point if (previous == null) { res = next; } // hmm, or do we have an end point? if (next == null) { res = previous; } // did we find it? if (res == null) { res = FixWrapper.interpolateFix(previous, next, requestedDTG); } return res; } @Override public final boolean getInterpolatePoints() { return _interpolatePoints; } /** * get the set of fixes contained within this time period (inclusive of both end values) * * @param start * start DTG * @param end * end DTG * @return series of fixes */ @Override public final Collection<Editable> getItemsBetween(final HiResDate start, final HiResDate end) { SortedSet<Editable> set = null; // does our track contain any data at all if (_thePositions.size() > 0) { // see if we have _any_ points in range if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start))) { // don't bother with it. } else { // SPECIAL CASE! If we've been asked to show interpolated data // points, // then // we should produce a series of items between the indicated // times. How // about 1 minute resolution? if (getInterpolatePoints()) { final long ourInterval = 1000 * 60; // one minute set = new TreeSet<Editable>(); for (long newTime = start.getDate().getTime(); newTime < end .getDate().getTime(); newTime += ourInterval) { final HiResDate newD = new HiResDate(newTime); final Watchable[] nearestOnes = getNearestTo(newD); if (nearestOnes.length > 0) { final FixWrapper nearest = (FixWrapper) nearestOnes[0]; set.add(nearest); } } } else { // bugger that - get the real data // have a go.. if (starter == null) { starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0)); } else { starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1)); } if (finisher == null) { finisher = new FixWrapper(new Fix(new HiResDate(0, end.getMicros() + 1), _zeroLocation, 0.0, 0.0)); } else { finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1)); } // ok, ready, go for it. set = getPositionsBetween(starter, finisher); } } } return set; } /** * method to allow the setting of label frequencies for the track * * @return frequency to use */ public final HiResDate getLabelFrequency() { return this._lastLabelFrequency; } /** * what is the style used for plotting this track? * * @return */ public int getLineStyle() { return _lineStyle; } /** * the line thickness (convenience wrapper around width) * * @return */ @Override public int getLineThickness() { return _lineWidth; } /** * whether to link points * * @return */ public boolean getLinkPositions() { return _linkPositions; } /** * just have the one property listener - rather than an anonymous class * * @return */ public PropertyChangeListener getLocationListener() { return _locationListener; } /** * name of this Track (normally the vessel name) * * @return the name */ @Override public final String getName() { return _theLabel.getString(); } /** * get our child segments * * @return */ public SegmentList getSegments() { return _thePositions; } /** * whether to show the track label at the start or end of the track * * @return yes/no to indicate <I>At Start</I> */ public final boolean getNameAtStart() { return _LabelAtStart; } /** * the relative location of the label * * @return the relative location */ public final Integer getNameLocation() { return _theLabel.getRelativeLocation(); } /** * whether the track label is visible or not * * @return yes/no */ public final boolean getNameVisible() { return _theLabel.getVisible(); } /** * find the fix nearest to this time (or the first fix for an invalid time) * * @param DTG * the time of interest * @return the nearest fix */ @Override public final Watchable[] getNearestTo(final HiResDate srchDTG) { /** * we need to end up with a watchable, not a fix, so we need to work our way through the fixes */ FixWrapper res = null; // check that we do actually contain some data if (_thePositions.size() == 0) { return new MWC.GenericData.Watchable[] {}; } // special case - if we've been asked for an invalid time value if (srchDTG == TimePeriod.INVALID_DATE) { final TrackSegment seg = (TrackSegment) _thePositions.first(); final FixWrapper fix = (FixWrapper) seg.first(); // just return our first location return new MWC.GenericData.Watchable[] {fix}; } // see if this is the DTG we have just requestsed if ((srchDTG.equals(lastDTG)) && (lastFix != null)) { res = lastFix; } else { final TrackSegment firstSeg = (TrackSegment) _thePositions.first(); final TrackSegment lastSeg = (TrackSegment) _thePositions.last(); if ((firstSeg != null) && (firstSeg.size() > 0)) { // see if this DTG is inside our data range // in which case we will just return null final FixWrapper theFirst = (FixWrapper) firstSeg.first(); final FixWrapper theLast = (FixWrapper) lastSeg.last(); if ((srchDTG.greaterThan(theFirst.getTime())) && (srchDTG.lessThanOrEqualTo(theLast.getTime()))) { // yes it's inside our data range, find the first fix // after the indicated point // right, increment the time, since we want to allow matching // points // HiResDate DTG = new HiResDate(0, srchDTG.getMicros() + 1); // see if we have to create our local temporary fix if (nearestFix == null) { nearestFix = new FixWrapper(new Fix(srchDTG, _zeroLocation, 0.0, 0.0)); } else { nearestFix.getFix().setTime(srchDTG); } // right, we really should be filtering the list according to if // the // points are visible. // how do we do filters? // get the data. use tailSet, since it's inclusive... SortedSet<Editable> set = getRawPositions().tailSet(nearestFix); // see if the requested DTG was inside the range of the data if (!set.isEmpty() && (set.size() > 0)) { res = (FixWrapper) set.first(); // is this one visible? if (!res.getVisible()) { // right, the one we found isn't visible. duplicate the // set, so that // we can remove items // without affecting the parent TreeSet<Editable> tmpSet = new TreeSet<Editable>(set); // ok, start looping back until we find one while ((!res.getVisible()) && (tmpSet.size() > 0)) { // the first one wasn't, remove it tmpSet.remove(res); if (tmpSet.size() > 0) { res = (FixWrapper) tmpSet.first(); } } // SPECIAL CASE: when the time period is after // the end of the filtered period, the above logic will // result in the very last point on the list being // selected. In truth, the first point on the // list is closer to the requested time. // when this happens, return the first item in the // original list. if (tmpSet.size() == 0) { res = (FixWrapper) set.first(); } } } // right, that's the first points on or before the indicated // DTG. Are we // meant // to be interpolating? if (res != null) { if (getInterpolatePoints()) { // right - just check that we aren't actually on the // correct time // point. // HEY, USE THE ORIGINAL SEARCH TIME, NOT THE // INCREMENTED ONE, // SINCE WE DON'T WANT TO COMPARE AGAINST A MODIFIED // TIME if (!res.getTime().equals(srchDTG)) { // right, we haven't found an actual data point. // Better calculate // one // hmm, better also find the point before our one. // the // headSet operation is exclusive - so we need to // find the one // after the first final SortedSet<Editable> otherSet = getRawPositions().headSet(nearestFix); FixWrapper previous = null; if (!otherSet.isEmpty()) { previous = (FixWrapper) otherSet.last(); } // did it work? if (previous != null) { // cool, sort out the interpolated point USING // THE ORIGINAL // SEARCH TIME res = getInterpolatedFix(previous, res, srchDTG); } } } } } else if (srchDTG.equals(theFirst.getDTG())) { // aaah, special case. just see if we're after a data point // that's the // same // as our start time res = theFirst; } } // and remember this fix lastFix = res; lastDTG = srchDTG; } if (res != null) { return new MWC.GenericData.Watchable[] {res}; } else { return new MWC.GenericData.Watchable[] {}; } } public boolean getPlotArrayCentre() { return _plotArrayCentre; } /** * get the position data, not all the sensor/contact/position data mixed together * * @return */ public final Enumeration<Editable> getPositions() { final SortedSet<Editable> res = getRawPositions(); return new TrackWrapper_Support.IteratorWrapper(res.iterator()); } private SortedSet<Editable> getPositionsBetween(final FixWrapper starter2, final FixWrapper finisher2) { // first get them all as one list final SortedSet<Editable> pts = getRawPositions(); // now do the sort return pts.subSet(starter2, finisher2); } /** * whether positions are being shown * * @return */ public final boolean getPositionsVisible() { return _showPositions; } private SortedSet<Editable> getRawPositions() { SortedSet<Editable> res = null; // do we just have the one list? if (_thePositions.size() == 1) { final TrackSegment p = (TrackSegment) _thePositions.first(); res = (SortedSet<Editable>) p.getData(); } else { // loop through them res = new TreeSet<Editable>(); final Enumeration<Editable> segs = _thePositions.elements(); while (segs.hasMoreElements()) { // get this segment final TrackSegment seg = (TrackSegment) segs.nextElement(); // add all the points res.addAll(seg.getData()); } } return res; } /** * method to allow the setting of data sampling frequencies for the track & sensor data * * @return frequency to use */ public final HiResDate getResampleDataAt() { return this._lastDataFrequency; } /** * get the list of sensors for this track */ public final BaseLayer getSensors() { return _mySensors; } /** * get the list of sensor arcs for this track */ public final BaseLayer getDynamicShapes() { return _myDynamicShapes; } /** * return the symbol to be used for plotting this track in snail mode */ @Override public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape() { return _theSnailShape; } /** * get the list of sensors for this track */ public final BaseLayer getSolutions() { return _mySolutions; } // watchable (tote related) parameters /** * the earliest fix in the track * * @return the DTG */ @Override public final HiResDate getStartDTG() { HiResDate res = null; final TimePeriod period = getTimePeriod(); if (period != null) { res = period.getStartDTG(); } return res; } /** * get the color used to plot the symbol * * @return the color */ public final Color getSymbolColor() { return _theSnailShape.getColor(); } /** * return the symbol frequencies for the track * * @return frequency in seconds */ public final HiResDate getSymbolFrequency() { return _lastSymbolFrequency; } public WorldDistance getSymbolLength() { WorldDistance res = null; if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; res = sym.getLength(); } return res; } /** * get the type of this symbol */ public final String getSymbolType() { return _theSnailShape.getType(); } public WorldDistance getSymbolWidth() { WorldDistance res = null; if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; res = sym.getWidth(); } return res; } private TimePeriod getTimePeriod() { TimePeriod res = null; final Enumeration<Editable> segs = _thePositions.elements(); while (segs.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segs.nextElement(); // do we have a dtg? if ((seg.startDTG() != null) && (seg.endDTG() != null)) { // yes, get calculating if (res == null) { res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG()); } else { res.extend(seg.startDTG()); res.extend(seg.endDTG()); } } } return res; } /** * the colour of the points on the track * * @return the colour */ public final Color getTrackColor() { return getColor(); } /** * font handler * * @return the font to use for the label */ public final java.awt.Font getTrackFont() { return _theLabel.getFont(); } /** * get the set of fixes contained within this time period which haven't been filtered, and which * have valid depths. The isVisible flag indicates whether a track has been filtered or not. We * also have the getVisibleFixesBetween method (below) which decides if a fix is visible if it is * set to Visible, and it's label or symbol are visible. * <p/> * We don't have to worry about a valid depth, since 3d doesn't show points with invalid depth * values * * @param start * start DTG * @param end * end DTG * @return series of fixes */ public final Collection<Editable> getUnfilteredItems(final HiResDate start, final HiResDate end) { // see if we have _any_ points in range if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start))) { return null; } if (this.getVisible() == false) { return null; } // get ready for the output final Vector<Editable> res = new Vector<Editable>(0, 1); // put the data into a period final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end); // step through our fixes final Enumeration<Editable> iter = getPositions(); while (iter.hasMoreElements()) { final FixWrapper fw = (FixWrapper) iter.nextElement(); if (fw.getVisible()) { // is it visible? if (thePeriod.contains(fw.getTime())) { // hey, it's valid - continue res.add(fw); } } } return res; } /** * whether this object has editor details * * @return yes/no */ @Override public final boolean hasEditor() { return true; } @Override public boolean hasOrderedChildren() { return false; } /** * quick accessor for how many fixes we have * * @return */ public int numFixes() { return getRawPositions().size(); } private void checkPointsArray() { // is our points store long enough? if ((_myPts == null) || (_myPts.length < numFixes() * 2)) { _myPts = new int[numFixes() * 2]; } // reset the points counter _ptCtr = 0; } private boolean paintFixes(final CanvasType dest) { // we need an array to store the polyline of points in. Check it's big // enough checkPointsArray(); // keep track of if we have plotted any points (since // we won't be plotting the name if none of the points are visible). // this typically occurs when filtering is applied and a short // track is completely outside the time period boolean plotted_anything = false; // java.awt.Point lastP = null; Color lastCol = null; final int defaultlineStyle = getLineStyle(); boolean locatedTrack = false; WorldLocation lastLocation = null; FixWrapper lastFix = null; final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); // how shall we plot this segment? final int thisLineStyle; // is the parent using the default style? if (defaultlineStyle == CanvasType.SOLID) { // yes, let's override it, if the segment wants to thisLineStyle = seg.getLineStyle(); } else { // no, we're using a custom style - don't override it. thisLineStyle = defaultlineStyle; } // SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN // RELATIVE MODE final boolean isRelative = seg.getPlotRelative(); WorldLocation tmaLastLoc = null; long tmaLastDTG = 0; // if it's not a relative track, and it's not visible, we don't // need to work with ut if (!getVisible() && !isRelative) { continue; } // is this segment visible? if (!seg.getVisible()) { continue; } // final Enumeration<Editable> fixWrappers = seg.elements(); // while (fixWrappers.hasMoreElements()) // final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); // get the data as an array - to avoid the concurrent modification // problems we were getting when doing network monitoring (DIS support) Editable[] existingWrapper = seg.getData().toArray(new Editable[] {null}); for (int i = 0; i < existingWrapper.length; i++) { final FixWrapper fw = (FixWrapper) existingWrapper[i]; // now there's a chance that our fix has forgotten it's // parent, // particularly if it's the victim of a // copy/paste operation. Tell it about it's children fw.setTrackWrapper(this); // is this fix visible? if (!fw.getVisible()) { // nope. Don't join it to the last position. // ok, if we've built up a polygon, we need to write it // now paintSetOfPositions(dest, lastCol, thisLineStyle); } // Note: we're carrying on working with this position even // if it isn't visible, // since we need to use non-visible positions to build up a // DR track. // ok, so we have plotted something plotted_anything = true; // ok, are we in relative? if (isRelative) { final long thisTime = fw.getDateTimeGroup().getDate().getTime(); // ok, is this our first location? if (tmaLastLoc == null) { tmaLastLoc = new WorldLocation(seg.getTrackStart()); lastLocation = tmaLastLoc; } else { // calculate a new vector final long timeDelta = thisTime - tmaLastDTG; if (lastFix != null) { final double speedKts = lastFix.getSpeed(); final double courseRads = lastFix.getCourse(); final double depthM = lastFix.getDepth(); // use the value of depth as read in from the // file tmaLastLoc.setDepth(depthM); final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts, courseRads); tmaLastLoc.addToMe(thisVec); lastLocation = tmaLastLoc; } } lastFix = fw; tmaLastDTG = thisTime; // dump the location into the fix fw.setFixLocationSilent(new WorldLocation(tmaLastLoc)); } else { // this is an absolute position lastLocation = fw.getLocation(); } // ok, we only do this writing to screen if the actual // position is visible if (!fw.getVisible()) continue; final java.awt.Point thisP = dest.toScreen(lastLocation); // just check that there's enough GUI to create the plot // (i.e. has a point been returned) if (thisP == null) { return false; } // so, we're looking at the first data point. Do // we want to use this to locate the track name? // or have we already sorted out the location if (_LabelAtStart && !locatedTrack) { locatedTrack = true; _theLabel.setLocation(new WorldLocation(lastLocation)); } // are we if (getLinkPositions() && (getLineStyle() != LineStylePropertyEditor.UNCONNECTED)) { // right, just check if we're a different colour to // the previous one final Color thisCol = fw.getColor(); // do we know the previous colour if (lastCol == null) { lastCol = thisCol; } // is this to be joined to the previous one? if (fw.getLineShowing()) { // so, grow the the polyline, unless we've got a // colour change... if (thisCol != lastCol) { // add our position to the list - so it // finishes on us _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; // yup, better get rid of the previous // polygon paintSetOfPositions(dest, lastCol, thisLineStyle); } // add our position to the list - we'll output // the polyline at the end _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; } else { // nope, output however much line we've got so // far - since this // line won't be joined to future points paintSetOfPositions(dest, thisCol, thisLineStyle); // start off the next line _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; } /* * set the colour of the track from now on to this colour, so that the "link" to the next * fix is set to this colour if left unchanged */ dest.setColor(fw.getColor()); // and remember the last colour lastCol = thisCol; } if (_showPositions && fw.getVisible()) { // this next method just paints the fix. we've put the // call into paintThisFix so we can override the painting // in the CompositeTrackWrapper class paintThisFix(dest, lastLocation, fw); } }// while fixWrappers has more elements // SPECIAL HANDLING, IF IT'S A TMA SEGMENT PLOT THE VECTOR LABEL if (seg instanceof CoreTMASegment) { CoreTMASegment tma = (CoreTMASegment) seg; WorldLocation firstLoc = seg.first().getBounds().getCentre(); WorldLocation lastLoc = seg.last().getBounds().getCentre(); Font f = new Font("Sans Serif", Font.PLAIN, 11); Color c = _theLabel.getColor(); // tell the segment it's being stretched final String spdTxt = MWC.Utilities.TextFormatting.GeneralFormat .formatOneDecimalPlace(tma.getSpeed() .getValueIn(WorldSpeed.Kts)); // copied this text from RelativeTMASegment double courseVal = tma.getCourse(); if (courseVal < 0) courseVal += 360; String textLabel = "[" + spdTxt + " kts " + (int) courseVal + "\u00B0]"; // ok, now plot it CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc, lastLoc, 1.2, true); textLabel = tma.getName().replace(TextLabel.NEWLINE_MARKER, " "); CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc, lastLoc, 1.2, false); } // ok, just see if we have any pending polylines to paint paintSetOfPositions(dest, lastCol, thisLineStyle); } // are we trying to put the label at the end of the track? // have we found at least one location to plot? if (!_LabelAtStart && lastLocation != null) { _theLabel.setLocation(new WorldLocation(lastLocation)); } return plotted_anything; } private void paintSingleTrackLabel(final CanvasType dest) { // check that we have found a location for the label if (_theLabel.getLocation() == null) return; // is the first track a DR track? // NO - CHANGED: we only initialise the track font in italics // for a DR track. Then we let the user change it // final TrackSegment t1 = (TrackSegment) _thePositions.first(); // if (t1.getPlotRelative()) // _theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC)); // else if (_theLabel.getFont().isItalic()) // _theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN)); // check that we have set the name for the label if (_theLabel.getString() == null) { _theLabel.setString(getName()); } // does the first label have a colour? if (_theLabel.getColor() == null) { // check we have a colour Color labelColor = getColor(); // did we ourselves have a colour? if (labelColor == null) { // nope - do we have any legs? final Enumeration<Editable> numer = this.getPositions(); if (numer.hasMoreElements()) { // ok, use the colour of the first point final FixWrapper pos = (FixWrapper) numer.nextElement(); labelColor = pos.getColor(); } } _theLabel.setColor(labelColor); } // and paint it _theLabel.paint(dest); } private void paintMultipleSegmentLabel(final CanvasType dest) { final Enumeration<Editable> posis = _thePositions.elements(); while (posis.hasMoreElements()) { final TrackSegment thisE = (TrackSegment) posis.nextElement(); // is this segment visible? if (!thisE.getVisible()) { continue; } // does it have visible data points? if (thisE.size() == 0) { continue; } // if this is a TMA segment, we plot the name 1/2 way along. If it isn't // we plot it at the start if (thisE instanceof CoreTMASegment) { // just move along - we plot the name // a the mid-point } else { // is the first track a DR track? if (thisE.getPlotRelative()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC)); } else if (_theLabel.getFont().isItalic()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN)); } final WorldLocation theLoc = thisE.getTrackStart(); final String oldTxt = _theLabel.getString(); _theLabel.setString(thisE.getName()); // just see if this is a planning segment, with its own colors if (thisE instanceof PlanningSegment) { final PlanningSegment ps = (PlanningSegment) thisE; _theLabel.setColor(ps.getColor()); } else { _theLabel.setColor(getColor()); } _theLabel.setLocation(theLoc); _theLabel.paint(dest); _theLabel.setString(oldTxt); } } } /** * draw this track (we can leave the Positions to draw themselves) * * @param dest * the destination */ @Override public final void paint(final CanvasType dest) { // check we are visible and have some track data, else we won't work if (!getVisible() || this.getStartDTG() == null) { return; } // set the thickness for this track dest.setLineWidth(_lineWidth); // and set the initial colour for this track if (getColor() != null) dest.setColor(getColor()); // firstly plot the solutions if (_mySolutions.getVisible()) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); // just check that the sensor knows we're it's parent if (sw.getHost() == null) { sw.setHost(this); } // and do the paint sw.paint(dest); } // through the solutions } // whether the solutions are visible // now plot the sensors if (_mySensors.getVisible()) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // just check that the sensor knows we're it's parent if (sw.getHost() == null) { sw.setHost(this); } // and do the paint sw.paint(dest); } // through the sensors } // whether the sensor layer is visible // and now the track itself // just check if we are drawing anything at all if ((!getLinkPositions() || getLineStyle() == LineStylePropertyEditor.UNCONNECTED) && (!_showPositions)) { return; } // let the fixes draw themselves in final boolean plotted_anything = paintFixes(dest); // and draw the track label // still, we only plot the track label if we have plotted any // points if (_theLabel.getVisible() && plotted_anything) { // just see if we have multiple segments. if we do, // name them individually if (this._thePositions.size() <= 1) { paintSingleTrackLabel(dest); } else { // we've got multiple segments, name them paintMultipleSegmentLabel(dest); } } // if the label is visible // paint vector label if (plotted_anything) { paintVectorLabel(dest); } } private void paintVectorLabel(final CanvasType dest) { if (getVisible()) { final Enumeration<Editable> posis = _thePositions.elements(); while (posis.hasMoreElements()) { final TrackSegment thisE = (TrackSegment) posis.nextElement(); // paint only visible planning segments if ((thisE instanceof PlanningSegment) && thisE.getVisible()) { PlanningSegment ps = (PlanningSegment) thisE; ps.paintLabel(dest); } } } } /** * get the fix to paint itself * * @param dest * @param lastLocation * @param fw */ protected void paintThisFix(final CanvasType dest, final WorldLocation lastLocation, final FixWrapper fw) { fw.paintMe(dest, lastLocation, fw.getColor()); } /** * this accessor is present for debug/testing purposes only. Do not use outside testing! * * @return the list of screen locations about to be plotted */ public int[] debug_GetPoints() { return _myPts; } /** * this accessor is present for debug/testing purposes only. Do not use outside testing! * * @return the length of the list of screen points waiting to be plotted */ public int debug_GetPointCtr() { return _ptCtr; } /** * paint any polyline that we've built up * * @param dest * - where we're painting to * @param thisCol * @param lineStyle */ private void paintSetOfPositions(final CanvasType dest, final Color thisCol, final int lineStyle) { if (_ptCtr > 0) { dest.setColor(thisCol); dest.setLineStyle(lineStyle); final int[] poly = new int[_ptCtr]; System.arraycopy(_myPts, 0, poly, 0, _ptCtr); dest.drawPolyline(poly); dest.setLineStyle(CanvasType.SOLID); // and reset the counter _ptCtr = 0; } } /** * return the range from the nearest corner of the track * * @param other * the other location * @return the range */ @Override public final double rangeFrom(final WorldLocation other) { double nearest = -1; // do we have a track? if (_myWorldArea != null) { // find the nearest point on the track nearest = _myWorldArea.rangeFrom(other); } return nearest; } /** * remove the requested item from the track * * @param point * the point to remove */ @Override public final void removeElement(final Editable point) { // just see if it's a sensor which is trying to be removed if (point instanceof SensorWrapper) { _mySensors.removeElement(point); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) point; sw.setHost(null); } else if (point instanceof TMAWrapper) { _mySolutions.removeElement(point); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) point; sw.setHost(null); } else if (point instanceof SensorContactWrapper) { // ok, cycle through our sensors, try to remove this contact... final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // try to remove it from this one... sw.removeElement(point); } } else if (point instanceof DynamicTrackShapeWrapper) { // ok, cycle through our sensors, try to remove this contact... final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); // try to remove it from this one... sw.removeElement(point); } } else if (point instanceof TrackSegment) { _thePositions.removeElement(point); // and clear the parent item final TrackSegment ts = (TrackSegment) point; ts.setWrapper(null); } else if (point == _mySensors) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) editable; sw.setHost(null); } // and empty them out _mySensors.removeAllElements(); } else if (point == _myDynamicShapes) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) editable; sw.setHost(null); } // and empty them out _myDynamicShapes.removeAllElements(); } else if (point == _mySolutions) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) editable; sw.setHost(null); } // and empty them out _mySolutions.removeAllElements(); } else { // loop through the segments final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); seg.removeElement(point); // and stop listening to it (if it's a fix) if (point instanceof FixWrapper) { final FixWrapper fw = (FixWrapper) point; fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED, _locationListener); } } } } // LAYER support methods /** * pass through the track, resetting the labels back to their original DTG */ @FireReformatted public void resetLabels() { FormatTracks.formatTrack(this); } /** * how frequently symbols are placed on the track * * @param theVal * frequency in seconds */ public final void setArrowFrequency(final HiResDate theVal) { this._lastArrowFrequency = theVal; // set the "showPositions" parameter, as long as we are // not setting the symbols off if (theVal.getMicros() != 0.0) { this.setPositionsVisible(true); } final FixSetter setSymbols = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setArrowShowing(val); } }; setFixes(setSymbols, theVal); } /** * set the colour of this track label * * @param theCol * the colour */ @Override @FireReformatted public final void setColor(final Color theCol) { // do the parent super.setColor(theCol); // now do our processing _theLabel.setColor(theCol); } /** * the setter function which passes through the track */ private void setFixes(final FixSetter setter, final HiResDate theVal) { if (theVal == null) { return; } final long freq = theVal.getMicros(); // briefly check if we are revealing/hiding all times (ie if freq is 1 // or 0) if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY) { // show all of the labels final Enumeration<Editable> iter = getPositions(); while (iter.hasMoreElements()) { final FixWrapper fw = (FixWrapper) iter.nextElement(); setter.execute(fw, true); } } else { // no, we're not just blindly doing all of them. do them at the // correct // frequency // hide all of the labels/symbols first final Enumeration<Editable> enumA = getPositions(); while (enumA.hasMoreElements()) { final FixWrapper fw = (FixWrapper) enumA.nextElement(); setter.execute(fw, false); } if (freq == 0) { // we can ignore this, since we have just hidden all of the // points } else { if (getStartDTG() != null) { // pass through the track setting the values // sort out the start and finish times long start_time = getStartDTG().getMicros(); final long end_time = getEndDTG().getMicros(); // first check that there is a valid time period between start // time // and end time if (start_time + freq < end_time) { long num = start_time / freq; // we need to add one to the quotient if it has rounded down if (start_time % freq == 0) { // start is at our freq, so we don't need to increment } else { num++; } // calculate new start time start_time = num * freq; } else { // there is not one of our 'intervals' between the start and // the end, // so use the start time } while (start_time <= end_time) { // right, increment the start time by one, because we were // getting the // fix immediately before the requested time final HiResDate thisDTG = new HiResDate(0, start_time); final MWC.GenericData.Watchable[] list = this.getNearestTo(thisDTG); // check we found some if (list.length > 0) { final FixWrapper fw = (FixWrapper) list[0]; setter.execute(fw, true); } // produce the next time step start_time += freq; } } } } } @Override public final void setInterpolatePoints(final boolean val) { _interpolatePoints = val; } /** * set the label frequency (in seconds) * * @param theVal * frequency to use */ public final void setLabelFrequency(final HiResDate theVal) { this._lastLabelFrequency = theVal; final FixSetter setLabel = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setLabelShowing(val); } }; setFixes(setLabel, theVal); } // track-shifting operation // support for dragging the track around /** * set the style used for plotting the lines for this track * * @param val */ public void setLineStyle(final int val) { _lineStyle = val; } /** * the line thickness (convenience wrapper around width) */ public void setLineThickness(final int val) { _lineWidth = val; } /** * whether to link points * * @param linkPositions */ public void setLinkPositions(final boolean linkPositions) { _linkPositions = linkPositions; } /** * set the name of this track (normally the name of the vessel * * @param theName * the name as a String */ @Override @FireReformatted public final void setName(final String theName) { _theLabel.setString(theName); } /** * whether to show the track name at the start or end of the track * * @param val * yes no for <I>show label at start</I> */ public final void setNameAtStart(final boolean val) { _LabelAtStart = val; } /** * the relative location of the label * * @param val * the relative location */ public final void setNameLocation(final Integer val) { _theLabel.setRelativeLocation(val); } /** * whether to show the track name * * @param val * yes/no */ public final void setNameVisible(final boolean val) { _theLabel.setVisible(val); } public void setPlotArrayCentre(final boolean plotArrayCentre) { _plotArrayCentre = plotArrayCentre; } /** * whether to show the position fixes * * @param val * yes/no */ public final void setPositionsVisible(final boolean val) { _showPositions = val; } /** * set the data frequency (in seconds) for the track & sensor data * * @param theVal * frequency to use */ @FireExtended public final void setResampleDataAt(final HiResDate theVal) { this._lastDataFrequency = theVal; // have a go at trimming the start time to a whole number of intervals final long interval = theVal.getMicros(); // do we have a start time (we may just be being tested...) if (this.getStartDTG() == null) { return; } final long currentStart = this.getStartDTG().getMicros(); long startTime = (currentStart / interval) * interval; // just check we're in the range if (startTime < currentStart) { startTime += interval; } // just check it's not a barking frequency if (theVal.getDate().getTime() <= 0) { // ignore, we don't need to do anything for a zero or a -1 } else { final SegmentList segments = _thePositions; final Enumeration<Editable> theEnum = segments.elements(); while (theEnum.hasMoreElements()) { final TrackSegment seg = (TrackSegment) theEnum.nextElement(); seg.decimate(theVal, this, startTime); } // start off with the sensor data if (_mySensors != null) { for (final Enumeration<Editable> iterator = _mySensors.elements(); iterator .hasMoreElements();) { final SensorWrapper thisS = (SensorWrapper) iterator.nextElement(); thisS.decimate(theVal, startTime); } } // now the solutions if (_mySolutions != null) { for (final Enumeration<Editable> iterator = _mySolutions.elements(); iterator .hasMoreElements();) { final TMAWrapper thisT = (TMAWrapper) iterator.nextElement(); thisT.decimate(theVal, startTime); } } } } public final void setSymbolColor(final Color col) { _theSnailShape.setColor(col); } /** * how frequently symbols are placed on the track * * @param theVal * frequency in seconds */ public final void setSymbolFrequency(final HiResDate theVal) { this._lastSymbolFrequency = theVal; // set the "showPositions" parameter, as long as we are // not setting the symbols off if (theVal == null) { return; } if (theVal.getMicros() != 0.0) { this.setPositionsVisible(true); } final FixSetter setSymbols = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setSymbolShowing(val); } }; setFixes(setSymbols, theVal); } public void setSymbolLength(final WorldDistance symbolLength) { if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; sym.setLength(symbolLength); } } public final void setSymbolType(final String val) { // is this the type of our symbol? if (val.equals(_theSnailShape.getType())) { // don't bother we're using it already } else { // remember the size of the symbol final double scale = _theSnailShape.getScaleVal(); // remember the color of the symbol final Color oldCol = _theSnailShape.getColor(); // replace our symbol with this new one _theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val); _theSnailShape.setColor(oldCol); _theSnailShape.setScaleVal(scale); } } public void setSymbolWidth(final WorldDistance symbolWidth) { if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; sym.setHeight(symbolWidth); } } // note we are putting a track-labelled wrapper around the colour // parameter, to make the properties window less confusing /** * the colour of the points on the track * * @param theCol * the colour to use */ @FireReformatted public final void setTrackColor(final Color theCol) { setColor(theCol); } /** * font handler * * @param font * the font to use for the label */ public final void setTrackFont(final java.awt.Font font) { _theLabel.setFont(font); } @Override public void shift(final WorldLocation feature, final WorldVector vector) { feature.addToMe(vector); // right, one of our fixes has moved. get the sensors to update // themselves fixMoved(); } @Override public void shift(final WorldVector vector) { this.shiftTrack(elements(), vector); } /** * move the whole of the track be the provided offset */ public final void shiftTrack(final Enumeration<Editable> theEnum, final WorldVector offset) { Enumeration<Editable> enumA = theEnum; // keep track of if the track contains something that doesn't get // dragged boolean handledData = false; if (enumA == null) { enumA = elements(); } while (enumA.hasMoreElements()) { final Object thisO = enumA.nextElement(); if (thisO instanceof TrackSegment) { final TrackSegment seg = (TrackSegment) thisO; seg.shift(offset); // ok - job well done handledData = true; } else if (thisO instanceof SegmentList) { final SegmentList list = (SegmentList) thisO; final Collection<Editable> items = list.getData(); for (final Iterator<Editable> iterator = items.iterator(); iterator .hasNext();) { final TrackSegment segment = (TrackSegment) iterator.next(); segment.shift(offset); } handledData = true; } else if (thisO instanceof SensorWrapper) { final SensorWrapper sw = (SensorWrapper) thisO; final Enumeration<Editable> enumS = sw.elements(); while (enumS.hasMoreElements()) { final SensorContactWrapper scw = (SensorContactWrapper) enumS.nextElement(); // does this fix have it's own origin? final WorldLocation sensorOrigin = scw.getOrigin(); if (sensorOrigin != null) { // create new object to contain the updated location final WorldLocation newSensorLocation = new WorldLocation(sensorOrigin); newSensorLocation.addToMe(offset); // so the contact did have an origin, change it scw.setOrigin(newSensorLocation); } } // looping through the contacts // ok - job well done handledData = true; } // whether this is a sensor wrapper else if (thisO instanceof TrackSegment) { final TrackSegment tw = (TrackSegment) thisO; final Enumeration<Editable> enumS = tw.elements(); // fire recursively, smart-arse. shiftTrack(enumS, offset); // ok - job well done handledData = true; } // whether this is a sensor wrapper } // looping through this track // ok, did we handle the data? if (!handledData) { System.err.println("TrackWrapper problem; not able to shift:" + enumA); } } /** * if we've got a relative track segment, it only learns where its individual fixes are once * they've been initialised. This is where we do it. */ public void sortOutRelativePositions() { final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); // SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN // RELATIVE MODE final boolean isRelative = seg.getPlotRelative(); WorldLocation tmaLastLoc = null; long tmaLastDTG = 0; // if it's not a relative track, and it's not visible, we don't // need to // work with ut if (!isRelative) { continue; } final Enumeration<Editable> fixWrappers = seg.elements(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); // now there's a chance that our fix has forgotten it's parent, // particularly if it's the victim of a // copy/paste operation. Tell it about it's children fw.setTrackWrapper(this); // ok, are we in relative? if (isRelative) { final long thisTime = fw.getDateTimeGroup().getDate().getTime(); // ok, is this our first location? if (tmaLastLoc == null) { tmaLastLoc = new WorldLocation(seg.getTrackStart()); } else { // calculate a new vector final long timeDelta = thisTime - tmaLastDTG; if (lastFix != null) { final double speedKts = lastFix.getSpeed(); final double courseRads = lastFix.getCourse(); final double depthM = lastFix.getDepth(); // use the value of depth as read in from the file tmaLastLoc.setDepth(depthM); final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts, courseRads); tmaLastLoc.addToMe(thisVec); } } lastFix = fw; tmaLastDTG = thisTime; // dump the location into the fix fw.setFixLocationSilent(new WorldLocation(tmaLastLoc)); } } } } /** * split this whole track into two sub-tracks * * @param splitPoint * the point at which we perform the split * @param splitBeforePoint * whether to put split before or after specified point * @return a list of the new track segments (used for subsequent undo operations) */ public Vector<TrackSegment> splitTrack(final FixWrapper splitPoint, final boolean splitBeforePoint) { FixWrapper splitPnt = splitPoint; Vector<TrackSegment> res = null; TrackSegment relevantSegment = null; // are we still in one section? if (_thePositions.size() == 1) { relevantSegment = (TrackSegment) _thePositions.first(); // yup, looks like we're going to be splitting it. // better give it a proper name relevantSegment.setName(relevantSegment.startDTG().getDate().toString()); } else { // ok, find which segment contains our data final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); if (seg.getData().contains(splitPnt)) { relevantSegment = seg; break; } } } if (relevantSegment == null) { throw new RuntimeException( "failed to provide relevant segment, alg will break"); } // hmm, if we're splitting after the point, we need to move along the // bus by // one if (!splitBeforePoint) { final Collection<Editable> items = relevantSegment.getData(); final Iterator<Editable> theI = items.iterator(); Editable previous = null; while (theI.hasNext()) { final Editable thisE = theI.next(); // have we chosen to remember the previous item? if (previous != null) { // yes, this must be the one we're after splitPnt = (FixWrapper) thisE; break; } // is this the one we're looking for? if (thisE == splitPnt) { // yup, remember it - we want to use the next value previous = thisE; } } } // yup, do our first split final SortedSet<Editable> p1 = relevantSegment.headSet(splitPnt); final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPnt); // get our results ready final TrackSegment ts1, ts2; // aaah, just sort out if we are splitting a TMA segment, in which case // want to create two // tma segments, not track segments if (relevantSegment instanceof RelativeTMASegment) { final RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment; // find the ownship location at the relevant time WorldLocation secondLegOrigin = null; // get the time of the split final HiResDate splitTime = splitPnt.getDateTimeGroup(); // aah, sort out if we are splitting before or after. SensorWrapper sensor = theTMA.getReferenceSensor(); if (sensor != null) { Watchable[] nearestF = sensor.getNearestTo(splitTime); if ((nearestF != null) && (nearestF.length > 0)) { SensorContactWrapper scw = (SensorContactWrapper) nearestF[0]; secondLegOrigin = scw.getCalculatedOrigin(null); } } // if we couldn't get a sensor origin, try for the track origin if (secondLegOrigin == null) { final Watchable firstMatch = theTMA.getReferenceTrack().getNearestTo(splitTime)[0]; secondLegOrigin = firstMatch.getLocation(); } final WorldVector secondOffset = splitPnt.getLocation().subtract(secondLegOrigin); // put the lists back into plottable layers final RelativeTMASegment tr1 = new RelativeTMASegment(theTMA, p1, theTMA.getOffset()); final RelativeTMASegment tr2 = new RelativeTMASegment(theTMA, p2, secondOffset); // update the freq's tr1.setBaseFrequency(theTMA.getBaseFrequency()); tr2.setBaseFrequency(theTMA.getBaseFrequency()); // and store them ts1 = tr1; ts2 = tr2; } else if (relevantSegment instanceof AbsoluteTMASegment) { final AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment; // aah, sort out if we are splitting before or after. // find out the offset at the split point, so we can initiate it for // the // second part of the track final Watchable[] matches = this.getNearestTo(splitPnt.getDateTimeGroup()); final WorldLocation origin = matches[0].getLocation(); final FixWrapper t1Start = (FixWrapper) p1.first(); // put the lists back into plottable layers final AbsoluteTMASegment tr1 = new AbsoluteTMASegment(theTMA, p1, t1Start.getLocation(), null, null); final AbsoluteTMASegment tr2 = new AbsoluteTMASegment(theTMA, p2, origin, null, null); // update the freq's tr1.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); tr2.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); // and store them ts1 = tr1; ts2 = tr2; } else { // put the lists back into plottable layers ts1 = new TrackSegment(p1); ts2 = new TrackSegment(p2); } // now clear the positions _thePositions.removeElement(relevantSegment); // and put back our new layers _thePositions.addSegment(ts1); _thePositions.addSegment(ts2); // remember them res = new Vector<TrackSegment>(); res.add(ts1); res.add(ts2); return res; } /** * extra parameter, so that jvm can produce a sensible name for this * * @return the track name, as a string */ @Override public final String toString() { return "Track:" + getName(); } /** * is this track visible between these time periods? * * @param start * start DTG * @param end * end DTG * @return yes/no */ public final boolean visibleBetween(final HiResDate start, final HiResDate end) { boolean visible = false; if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start))) { visible = true; } return visible; } /** * Calculates Course & Speed for the track. */ public void calcCourseSpeed() { // step through our fixes final Enumeration<Editable> iter = getPositions(); FixWrapper prevFw = null; while (iter.hasMoreElements()) { final FixWrapper currFw = (FixWrapper) iter.nextElement(); if (prevFw == null) prevFw = currFw; else { // calculate the course final WorldVector wv = currFw.getLocation().subtract(prevFw.getLocation()); prevFw.getFix().setCourse(wv.getBearing()); // also, set the correct label alignment currFw.resetLabelLocation(); // calculate the speed // get distance in meters final WorldDistance wd = new WorldDistance(wv); final double distance = wd.getValueIn(WorldDistance.METRES); // get time difference in seconds final long timeDifference = (currFw.getTime().getMicros() - prevFw.getTime().getMicros()) / 1000000; // get speed in meters per second and convert it to knots final WorldSpeed speed = new WorldSpeed(distance / timeDifference, WorldSpeed.M_sec); final double knots = WorldSpeed.convert(WorldSpeed.M_sec, WorldSpeed.Kts, speed .getValue()); prevFw.setSpeed(knots); prevFw = currFw; } } } public void trimTo(TimePeriod period) { if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); sw.trimTo(period); } } if (_myDynamicShapes != null) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); sw.trimTo(period); } } if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); sw.trimTo(period); } } if (_thePositions != null) { final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); seg.trimTo(period); } } } @Override public Enumeration<Editable> segments() { return elements(); } /** * accessor to determine if this is a relative track * * @return */ public boolean isTMATrack() { boolean res = false; if (_thePositions != null) if (_thePositions.size() > 0) if (_thePositions.first() instanceof CoreTMASegment) { res = true; } return res; } @Override public int compareTo(Plottable arg0) { Integer answer = null; // SPECIAL PROCESSING: we wish to push TMA tracks to the top of any // tracks shown in the outline view. // is he a track? if (arg0 instanceof TrackWrapper) { TrackWrapper other = (TrackWrapper) arg0; // yes, he's a track. See if we're a relative track boolean iAmTMA = isTMATrack(); // is he relative? boolean heIsTMA = other.isTMATrack(); if (heIsTMA) { // ok, he's a TMA segment. now we need to sort out if we are. if (iAmTMA) { // we're both relative, compare names answer = getName().compareTo(other.getName()); } else { // only he is relative, he comes first answer = 1; } } else { // he's not relative. am I? if (iAmTMA) { // I am , so go first answer = -1; } } } else { // we're a track, they're not - put us at the end! answer = 1; } // if we haven't worked anything out yet, just use the parent implementation if (answer == null) answer = super.compareTo(arg0); return answer; } @Override public void paint(CanvasType dest, long time) { if (!getVisible()) return; // set the thickness for this track dest.setLineWidth(_lineWidth); // and set the initial colour for this track if (getColor() != null) dest.setColor(getColor()); // we plot only the dynamic arcs because they are MovingPlottable if (_myDynamicShapes.getVisible()) { final Enumeration<Editable> iter = _myDynamicShapes.elements(); while (iter.hasMoreElements()) { final DynamicTrackShapeSetWrapper sw = (DynamicTrackShapeSetWrapper) iter.nextElement(); // and do the paint sw.paint(dest, time); } } } public void addFix(FixWrapper theFix) { // do we have any track segments if (_thePositions.size() == 0) { // nope, add one final TrackSegment firstSegment = new TrackSegment(); firstSegment.setName("Positions"); _thePositions.addSegment(firstSegment); } // add fix to last track segment final TrackSegment last = (TrackSegment) _thePositions.last(); last.addFix(theFix); // tell the fix about it's daddy theFix.setTrackWrapper(this); // and extend the start/end DTGs if (_myTimePeriod == null) { _myTimePeriod = new TimePeriod.BaseTimePeriod(theFix.getDateTimeGroup(), theFix .getDateTimeGroup()); } else { _myTimePeriod.extend(theFix.getDateTimeGroup()); } if (_myWorldArea == null) { _myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation()); } else { _myWorldArea.extend(theFix.getLocation()); } // we want to listen out for the fix being moved. better listen in to it // theFix.addPropertyChangeListener(PlainWrapper.LOCATION_CHANGED, // _locationListener); } }
package org.oscm.ui.beans; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.event.ActionEvent; import org.oscm.converter.WhiteSpaceConverter; import org.oscm.ui.beans.marketplace.CategorySelectionBean; import org.oscm.ui.beans.marketplace.ServicePagingBean; import org.oscm.ui.beans.marketplace.TagCloudBean; import org.oscm.ui.common.Constants; import org.oscm.ui.common.ExceptionHandler; import org.oscm.ui.common.JSFUtils; import org.oscm.ui.converter.TrimConverter; import org.oscm.ui.dialog.mp.landingpage.EnterpriseLandingpageModel; import org.oscm.ui.model.Service; import org.oscm.internal.types.enumtypes.LandingpageType; import org.oscm.internal.types.enumtypes.OfferingType; import org.oscm.internal.types.enumtypes.PerformanceHint; import org.oscm.internal.types.exception.DomainObjectException.ClassEnum; import org.oscm.internal.types.exception.InvalidPhraseException; import org.oscm.internal.types.exception.ObjectNotFoundException; import org.oscm.internal.types.exception.SaaSApplicationException; import org.oscm.internal.vo.ListCriteria; import org.oscm.internal.vo.VOService; import org.oscm.internal.vo.VOServiceListResult; /** * The ServicesListBean is responsible for serving serviceLists. * * @author Enes Sejfi */ @ViewScoped @ManagedBean(name="serviceListingBean") public class ServiceListingBean extends BaseBean implements Serializable { /** * This list contains all selected services. */ private List<Service> services; /** * This list contains all services selected by * SearchServiceBean.searchServices. */ private List<Service> searchResult; /** * Contains the services which should be listed on the landing page. */ private List<Service> landingPageServices; /** * Contains the services which should be listed on the enterprise landing * page. */ EnterpriseLandingpageModel enterpriseLandingpageModel; /** * References the pagingBean which is responsible for paging the services. */ @ManagedProperty(value="#{servicePagingBean}") private ServicePagingBean servicePagingBean; /** * Needed to reset the categories of a marketplace if a selected category * was deleted concurrently. */ @ManagedProperty(value="#{categorySelectionBean}") private CategorySelectionBean categorySelectionBean; /** * Needed to reset the tags of a marketplace if a selected tag was deleted * concurrently. */ @ManagedProperty(value="#{tagCloudBean}") private TagCloudBean tagCloudBean; LandingpageType landingpageType; private static final long serialVersionUID = 50587384050094871L; private boolean serviceListContainsChargeableResellerService; public static final Vo2ModelMapper<VOService, Service> DEFAULT_VOSERVICE_MAPPER = new Vo2ModelMapper<VOService, Service>() { @Override public Service createModel(final VOService vo) { return new Service(vo); } }; void updateServiceListContainsChargeableResellerService( List<VOService> resultList) { serviceListContainsChargeableResellerService = false; if (resultList != null && resultList.size() > 0) { for (VOService svc : resultList) { if (OfferingType.RESELLER.equals(svc.getOfferingType()) && svc.getPriceModel().isChargeable()) { serviceListContainsChargeableResellerService = true; break; } } } } /** * @return the serviceListContainsChargeableResellerService */ public boolean isServiceListContainsChargeableResellerService() { return serviceListContainsChargeableResellerService; } public void setServiceListContainsChargeableResellerService( @SuppressWarnings("unused") boolean listContainsResellerService) { // ignore } /** * Returns the list of services which should be listed on the landing page. * * @return the services which should be listed on the landing page. */ public List<Service> getServicesForLandingPage() { if (landingPageServices == null) { try { String locale = JSFUtils.getViewLocale().getLanguage(); List<VOService> result = getShowLandingpage() .servicesForLandingpage(getMarketplaceId(), locale); updateServiceListContainsChargeableResellerService(result); landingPageServices = DEFAULT_VOSERVICE_MAPPER.map(result); } catch (SaaSApplicationException e) { ExceptionHandler.execute(e); } } return landingPageServices; } /** * Get a list with all services. * * @return a list with all services. */ public List<Service> getServices() { if (services == null && isMarketplaceSet()) { if (isLoggedIn()) { services = DEFAULT_VOSERVICE_MAPPER .map(getProvisioningServiceInternal() .getServicesForMarketplace( getMarketplaceId(), PerformanceHint.ONLY_FIELDS_FOR_LISTINGS)); } else if (isMarketplaceSet(getRequest())) { getPublicServices(); } } return services; } /** * Returns a list of all public services that can be viewed in the public * catalog by a potential customer. The supplier ID or marketplace ID must * be given in the request URL. * * @return List of services that can seen by anonymous users. */ public List<Service> getPublicServices() { if (services == null) { String marketplaceId = getMarketplaceId(); List<VOService> voList = Collections.emptyList(); if (marketplaceId != null) { voList = getProvisioningServiceInternal() .getServicesForMarketplace(marketplaceId, PerformanceHint.ONLY_FIELDS_FOR_LISTINGS); updateServiceListContainsChargeableResellerService(voList); } services = DEFAULT_VOSERVICE_MAPPER.map(voList); } return services; } /** * Executes the service for paging, sorting and filtering and updates the * result size if the service list is not initialized. * * @return the paged, sorted and filtered services */ public List<Service> searchWithCriteria() { ListCriteria criteria = servicePagingBean.getListCriteria(); if (categorySelectionBean.isCategorySelected()) { criteria.setCategoryId(categorySelectionBean .getSelectedCategoryId()); } if (services == null) { try { VOServiceListResult result = getSearchServiceInternal() .getServicesByCriteria(getMarketplaceId(), JSFUtils.getViewLocale().getLanguage(), criteria, PerformanceHint.ONLY_FIELDS_FOR_LISTINGS); getServicePagingBean().setResultSize(result.getResultSize()); updateServiceListContainsChargeableResellerService(result .getServices()); services = DEFAULT_VOSERVICE_MAPPER.map(result.getServices()); } catch (ObjectNotFoundException e) { if (e.getDomainObjectClassEnum() == ClassEnum.CATEGORY) { refreshCategories(); } else if (e.getDomainObjectClassEnum() == ClassEnum.TAG) { refreshTags(); } else { ExceptionHandler.execute(e); } } } return services; } /** * Reset cached categories in case the category was not found */ private void refreshCategories() { categorySelectionBean.resetCategoriesForMarketplace(); services = new LinkedList<Service>(); getServicePagingBean().setResultSize(0); } /** * Reset cached tags in case the tag was not found */ private void refreshTags() { tagCloudBean.resetTagsForMarketplace(); services = new LinkedList<Service>(); getServicePagingBean().setResultSize(0); } /** * forces data to be loaded from backend * * @param ae * required by faces actionListener */ public void reloadData(ActionEvent ae) { services = null; } /** * Return the service list for the marketplace portal. This is either the * complete, the filtered list a list resulting from the search execution. * <p> * The first one is also paged and sorted while the second is not (realized * in future). * * @return the service list as described above. */ public List<Service> getServiceList() { if (getServicePagingBean().isSearchRequested()) { return searchWithPhrase(); } else { return searchWithCriteria(); } } /** * Return the services representing the search results. * * @return the services representing the search results. */ public List<Service> searchWithPhrase() { String phrase = getServicePagingBean().getSearchPhrase(); // TODO: Handle empty phrase condition in ServicePagingBean, eg. // combine logic with isInvalidSearchPhrase() String searchPhrase = WhiteSpaceConverter.replace(phrase); searchPhrase = searchPhrase.trim(); if (searchPhrase != null && searchPhrase.trim().length() > 0 && (searchResult == null || getServicePagingBean() .isNewSearchRequired())) { getServicePagingBean().resetNewSearchRequired(); try { VOServiceListResult result = getSearchServiceInternal() .searchServices(getMarketplaceId(), getLanguage(), searchPhrase.trim(), PerformanceHint.ONLY_FIELDS_FOR_LISTINGS); updateServiceListContainsChargeableResellerService(result .getServices()); searchResult = DEFAULT_VOSERVICE_MAPPER.map(result .getServices()); } catch (InvalidPhraseException e) { getServicePagingBean().setInvalidSearchPhrase(true); ExceptionHandler.execute(e); return Collections.emptyList(); } catch (SaaSApplicationException e) { ExceptionHandler.execute(e); } } if (searchResult != null) { // Number of results must also be updated if results are cached, // because it might be changed by other queries. getServicePagingBean().setInvalidSearchPhrase(false); getServicePagingBean().setResultSize(searchResult.size()); } categorySelectionBean.setSelectedCategoryId(null); return searchResult; } /** * Action for displaying the service list resulting from a search query. * * @see org.oscm.ui.beans.marketplace.ServicePagingBean * @return OUTCOME_SHOW_SERVICE_LIST */ public String showServiceListSearch() { String phrase = getServicePagingBean().getSearchPhrase(); String tmp = TrimConverter.stripToNull(phrase); if (tmp == null) { return showServiceList(); } getRequest().setAttribute(Constants.REQ_ATTR_SEARCH_REQUEST, phrase); getServicePagingBean().setFilterTag(null); return OUTCOME_SHOW_SERVICE_LIST; } protected String getLanguage() { return JSFUtils.getViewLocale().getLanguage(); } /** * Sets the passed message key as error attribute in the current request. * * @param errorMsgKey * the error message key the be set. */ private void setErrorAttribute(String errorMsgKey) { getRequest().setAttribute(Constants.REQ_ATTR_ERROR_KEY, errorMsgKey); } /** * Action for displaying the service list. * <p> * All defined filter, sorting and paging criteria will be evaluated. * * @see org.oscm.ui.beans.marketplace.ServicePagingBean * @return OUTCOME_SHOW_SERVICE_LIST */ public String showServiceList() { services = null; return OUTCOME_SHOW_SERVICE_LIST; } /** * Sets the selected services * * @param services * selected services */ public void setServices(List<Service> services) { this.services = services; } /** * Sets the paging bean which sorts, filters and pages the services * * @param servicePagingBean * paging bean instance */ public void setServicePagingBean(ServicePagingBean servicePagingBean) { this.servicePagingBean = servicePagingBean; } /** * Returns the paging bean * * @return current paging bean instance */ public ServicePagingBean getServicePagingBean() { return servicePagingBean; } public void setCategorySelectionBean( CategorySelectionBean categorySelectionBean) { this.categorySelectionBean = categorySelectionBean; } public CategorySelectionBean getCategorySelectionBean() { return categorySelectionBean; } public TagCloudBean getTagCloudBean() { return tagCloudBean; } public void setTagCloudBean(TagCloudBean tagCloudBean) { this.tagCloudBean = tagCloudBean; } public boolean isPublicLandingpage() { return loadLandingpageType() == LandingpageType.PUBLIC; } LandingpageType loadLandingpageType() { if (landingpageType == null) { try { landingpageType = getLandingpageService().loadLandingpageType( ui.getMarketplaceId()); } catch (ObjectNotFoundException e) { ExceptionHandler.execute(e); } } return landingpageType; } }
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.CompatibilityFixer; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; import gcm2sbml.util.GlobalConstants; import graph.Graph; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; 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.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTabbedPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.plaf.basic.BasicTabbedPaneUI; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import learn.Learn; import synthesis.Synthesis; import verification.Verification; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; /** * This class creates a GUI for the Tstubd program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * are selected. * * @author Curtis Madsen */ public class BioSim implements MouseListener, ActionListener { private JFrame frame; // Frame where components of the GUI are displayed private JMenu file; // The file menu private JMenuItem newProj; // The new menu item private JMenuItem newModel; // The new menu item private JMenuItem newCircuit; // The new menu item private JMenuItem newVhdl; // The new vhdl menu item private JMenuItem newLhpn; // The new lhpn menu item private JMenuItem exit; // The exit menu item private JMenuItem importSbml; // The import sbml menu item private JMenuItem importDot; // The import dot menu item private JMenuItem importVhdl; // The import vhdl menu item private JMenuItem importLhpn; // The import lhpn menu item private JMenuItem manual; // The manual menu item private JMenuItem about; // The about menu item private JMenuItem openProj; // The open menu item private JMenuItem pref; // The preferences menu item private JMenuItem graph; // The graph menu item private JMenuItem probGraph; private String root; // The root directory private FileTree tree; // FileTree private JTabbedPane tab; // JTabbedPane for different tools private JPanel mainPanel; // the main panel private Log log; // the log private JPopupMenu popup; // popup menu private String separator; private KeyEventDispatcher dispatcher; private JMenuItem recentProjects[]; private String recentProjectPaths[]; private int numberRecentProj; private int ShortCutKey; public boolean checkUndeclared, checkUnits; private JCheckBox Undeclared, Units; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean lema; public class MacOSAboutHandler extends Application { public MacOSAboutHandler() { addApplicationListener(new AboutBoxHandler()); } class AboutBoxHandler extends ApplicationAdapter { public void handleAbout(ApplicationEvent event) { about(); event.setHandled(true); } } } public class MacOSPreferencesHandler extends Application { public MacOSPreferencesHandler() { addApplicationListener(new PreferencesHandler()); } class PreferencesHandler extends ApplicationAdapter { public void handlePreferences(ApplicationEvent event) { preferences(); event.setHandled(true); } } } public class MacOSQuitHandler extends Application { public MacOSQuitHandler() { addApplicationListener(new QuitHandler()); } class QuitHandler extends ApplicationAdapter { public void handleQuit(ApplicationEvent event) { exit(); event.setHandled(true); } } } /** * This is the constructor for the Proj class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. * * @throws Exception */ public BioSim(boolean lema) { this.lema = lema; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Creates a new frame frame = new JFrame("iBioSim"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png").getImage()); // Makes it so that clicking the x in the corner closes the program WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { exit.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; frame.addWindowListener(w); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); popup = new JPopupMenu(); // Creates a menu for the frame JMenuBar menuBar = new JMenuBar(); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); JMenu help = new JMenu("Help"); help.setMnemonic(KeyEvent.VK_H); JMenu importMenu = new JMenu("Import"); JMenu newMenu = new JMenu("New"); menuBar.add(file); menuBar.add(help); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); pref = new JMenuItem("Preferences"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); newVhdl = new JMenuItem("VHDL Model"); newLhpn = new JMenuItem("Labeled Hybrid Petri Net"); graph = new JMenuItem("TSD Graph"); probGraph = new JMenuItem("Probability Graph"); importSbml = new JMenuItem("SBML Model"); importDot = new JMenuItem("Genetic Circuit Model"); importVhdl = new JMenuItem("VHDL Model"); importLhpn = new JMenuItem("Labeled Hybrid Petri Net"); exit = new JMenuItem("Exit"); openProj.addActionListener(this); pref.addActionListener(this); manual.addActionListener(this); newProj.addActionListener(this); newCircuit.addActionListener(this); newModel.addActionListener(this); newVhdl.addActionListener(this); newLhpn.addActionListener(this); exit.addActionListener(this); about.addActionListener(this); importSbml.addActionListener(this); importDot.addActionListener(this); importVhdl.addActionListener(this); importLhpn.addActionListener(this); graph.addActionListener(this); probGraph.addActionListener(this); ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ShortCutKey)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey)); newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ShortCutKey)); newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ShortCutKey)); newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey)); about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ShortCutKey)); probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey)); importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, ShortCutKey)); importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ShortCutKey)); importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey)); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); newCircuit.setMnemonic(KeyEvent.VK_G); newCircuit.setDisplayedMnemonicIndex(8); newModel.setMnemonic(KeyEvent.VK_S); newVhdl.setMnemonic(KeyEvent.VK_V); newLhpn.setMnemonic(KeyEvent.VK_L); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_R); importDot.setMnemonic(KeyEvent.VK_E); importDot.setDisplayedMnemonicIndex(14); importSbml.setMnemonic(KeyEvent.VK_B); importVhdl.setMnemonic(KeyEvent.VK_H); importLhpn.setMnemonic(KeyEvent.VK_N); importDot.setEnabled(false); importSbml.setEnabled(false); importVhdl.setEnabled(false); importLhpn.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); newVhdl.setEnabled(false); newLhpn.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); file.add(newMenu); newMenu.add(newProj); if (!lema) { newMenu.add(newCircuit); newMenu.add(newModel); } else { newMenu.add(newVhdl); newMenu.add(newLhpn); } newMenu.add(graph); newMenu.add(probGraph); file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(importMenu); if (!lema) { importMenu.add(importDot); importMenu.add(importSbml); } else { importMenu.add(importVhdl); importMenu.add(importLhpn); } file.addSeparator(); help.add(manual); if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { file.add(pref); file.add(exit); file.addSeparator(); help.add(about); } root = null; // Create recent project menu items numberRecentProj = 0; recentProjects = new JMenuItem[5]; recentProjectPaths = new String[5]; for (int i = 0; i < 5; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_5); Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < 5; i++) { recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } if (biosimrc.get("biosim.check.undeclared", "").equals("false")) { checkUndeclared = false; } else { checkUndeclared = true; } if (biosimrc.get("biosim.check.units", "").equals("false")) { checkUnits = false; } else { checkUnits = true; } if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KREP_VALUE", ".5"); } if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KACT_VALUE", ".0033"); } if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBIO_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2"); } if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001"); } if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.OCR_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075"); } if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_VALUE", "30"); } if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2"); } if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25"); } if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1"); } if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.INITIAL_VALUE", "0"); } if (biosimrc.get("biosim.sim.abs", "").equals("")) { biosimrc.put("biosim.sim.abs", "None"); } if (biosimrc.get("biosim.sim.type", "").equals("")) { biosimrc.put("biosim.sim.type", "ODE"); } if (biosimrc.get("biosim.sim.sim", "").equals("")) { biosimrc.put("biosim.sim.sim", "rkf45"); } if (biosimrc.get("biosim.sim.limit", "").equals("")) { biosimrc.put("biosim.sim.limit", "100.0"); } if (biosimrc.get("biosim.sim.interval", "").equals("")) { biosimrc.put("biosim.sim.interval", "1.0"); } if (biosimrc.get("biosim.sim.step", "").equals("")) { biosimrc.put("biosim.sim.step", "inf"); } if (biosimrc.get("biosim.sim.error", "").equals("")) { biosimrc.put("biosim.sim.error", "1.0E-9"); } if (biosimrc.get("biosim.sim.seed", "").equals("")) { biosimrc.put("biosim.sim.seed", "314159"); } if (biosimrc.get("biosim.sim.runs", "").equals("")) { biosimrc.put("biosim.sim.runs", "1"); } if (biosimrc.get("biosim.sim.rapid1", "").equals("")) { biosimrc.put("biosim.sim.rapid1", "0.1"); } if (biosimrc.get("biosim.sim.rapid2", "").equals("")) { biosimrc.put("biosim.sim.rapid2", "0.1"); } if (biosimrc.get("biosim.sim.qssa", "").equals("")) { biosimrc.put("biosim.sim.qssa", "0.1"); } if (biosimrc.get("biosim.sim.concentration", "").equals("")) { biosimrc.put("biosim.sim.concentration", "15"); } // Open .biosimrc here // Packs the frame and displays it mainPanel = new JPanel(new BorderLayout()); tree = new FileTree(null, this, lema); log = new Log(); tab = new JTabbedPane(); tab.setPreferredSize(new Dimension(1050, 550)); tab.setUI(new TabbedPaneCloseButtonUI()); mainPanel.add(tree, "West"); mainPanel.add(tab, "Center"); mainPanel.add(log, "South"); frame.setContentPane(mainPanel); frame.setJMenuBar(menuBar); frame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; frame.setLocation(x, y); frame.setVisible(true); dispatcher = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_TYPED) { if (e.getKeyChar() == '') { if (tab.getTabCount() > 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher( dispatcher); if (save(tab.getSelectedIndex()) != 0) { tab.remove(tab.getSelectedIndex()); } KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( dispatcher); } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); } public void preferences() { if (!lema) { Undeclared = new JCheckBox("Check for undeclared units in SBML"); if (checkUndeclared) { Undeclared.setSelected(true); } else { Undeclared.setSelected(false); } Units = new JCheckBox("Check units in SBML"); if (checkUnits) { Units.setSelected(true); } else { Units.setSelected(false); } Preferences biosimrc = Preferences.userRoot(); final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get("biosim.gcm.ACTIVED_VALUE", "")); final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", "")); final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", "")); final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.COOPERATIVITY_VALUE", "")); final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KASSOCIATION_VALUE", "")); final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", "")); final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get( "biosim.gcm.PROMOTER_COUNT_VALUE", "")); final JTextField INITIAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.INITIAL_VALUE", "")); final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "")); final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", "")); final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.RNAP_BINDING_VALUE", "")); final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", "")); final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.STOICHIOMETRY_VALUE", "")); JPanel labels = new JPanel(new GridLayout(15, 1)); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KASSOCIATION_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(15, 1)); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KBIO_VALUE); fields.add(KDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(KASSOCIATION_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_VALUE); fields.add(MAX_DIMER_VALUE); fields.add(OCR_VALUE); fields.add(RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); String[] choices = { "None", "Abstraction", "Logical Abstraction" }; final JComboBox abs = new JComboBox(choices); abs.setSelectedItem(biosimrc.get("biosim.sim.abs", "")); if (abs.getSelectedItem().equals("None")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else if (abs.getSelectedItem().equals("Abstraction")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else { choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser" }; } final JComboBox type = new JComboBox(choices); type.setSelectedItem(biosimrc.get("biosim.sim.type", "")); if (type.getSelectedItem().equals("ODE")) { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } else if (type.getSelectedItem().equals("Monte Carlo")) { choices = new String[] { "gillespie", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "atacs", "ctmc-transient" }; } else { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } final JComboBox sim = new JComboBox(choices); sim.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); abs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (abs.getSelectedItem().equals("None")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else if (abs.getSelectedItem().equals("Abstraction")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("Monte Carlo"); type.addItem("Markov"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } } }); type.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (type.getSelectedItem() == null) { } else if (type.getSelectedItem().equals("ODE")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Monte Carlo")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("gillespie"); sim.addItem("emc-sim"); sim.addItem("bunker"); sim.addItem("nmc"); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Markov")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("atacs"); sim.addItem("ctmc-transient"); sim.setSelectedItem(o); } else { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } } }); final JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", "")); final JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", "")); final JTextField step = new JTextField(biosimrc.get("biosim.sim.step", "")); final JTextField error = new JTextField(biosimrc.get("biosim.sim.error", "")); final JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", "")); final JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", "")); final JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", "")); final JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", "")); final JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", "")); final JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", "")); JPanel analysisLabels = new JPanel(new GridLayout(13, 1)); analysisLabels.add(new JLabel("Abstraction:")); analysisLabels.add(new JLabel("Simulation Type:")); analysisLabels.add(new JLabel("Possible Simulators/Analyzers:")); analysisLabels.add(new JLabel("Time Limit:")); analysisLabels.add(new JLabel("Print Interval:")); analysisLabels.add(new JLabel("Maximum Time Step:")); analysisLabels.add(new JLabel("Absolute Error:")); analysisLabels.add(new JLabel("Random Seed:")); analysisLabels.add(new JLabel("Runs:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 2:")); analysisLabels.add(new JLabel("QSSA Condition:")); analysisLabels.add(new JLabel("Max Concentration Threshold:")); JPanel analysisFields = new JPanel(new GridLayout(13, 1)); analysisFields.add(abs); analysisFields.add(type); analysisFields.add(sim); analysisFields.add(limit); analysisFields.add(interval); analysisFields.add(step); analysisFields.add(error); analysisFields.add(seed); analysisFields.add(runs); analysisFields.add(rapid1); analysisFields.add(rapid2); analysisFields.add(qssa); analysisFields.add(concentration); JPanel analysisPrefs = new JPanel(new GridLayout(1, 2)); analysisPrefs.add(analysisLabels); analysisPrefs.add(analysisFields); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); sbmlPrefsBordered.add(Undeclared, "North"); sbmlPrefsBordered.add(Units, "Center"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("SBML Preferences", sbmlPrefs); prefTabs.addTab("GCM Preferences", gcmPrefs); prefTabs.addTab("Analysis Preferences", analysisPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (Undeclared.isSelected()) { checkUndeclared = true; biosimrc.put("biosim.check.undeclared", "true"); } else { checkUndeclared = false; biosimrc.put("biosim.check.undeclared", "false"); } if (Units.isSelected()) { checkUnits = true; biosimrc.put("biosim.check.units", "true"); } else { checkUnits = false; biosimrc.put("biosim.check.units", "false"); } try { Double.parseDouble(KREP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KACT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBIO_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KASSOCIATION_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBASAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(OCR_VALUE.getText().trim()); biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(COOPERATIVITY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ACTIVED_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(MAX_DIMER_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(INITIAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(limit.getText().trim()); biosimrc.put("biosim.sim.limit", limit.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(interval.getText().trim()); biosimrc.put("biosim.sim.interval", interval.getText().trim()); } catch (Exception e1) { } try { if (step.getText().trim().equals("inf")) { biosimrc.put("biosim.sim.step", step.getText().trim()); } else { Double.parseDouble(step.getText().trim()); biosimrc.put("biosim.sim.step", step.getText().trim()); } } catch (Exception e1) { } try { Double.parseDouble(error.getText().trim()); biosimrc.put("biosim.sim.error", error.getText().trim()); } catch (Exception e1) { } try { Long.parseLong(seed.getText().trim()); biosimrc.put("biosim.sim.seed", seed.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(runs.getText().trim()); biosimrc.put("biosim.sim.runs", runs.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid1.getText().trim()); biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid2.getText().trim()); biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(qssa.getText().trim()); biosimrc.put("biosim.sim.qssa", qssa.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(concentration.getText().trim()); biosimrc.put("biosim.sim.concentration", concentration.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem()); biosimrc.put("biosim.sim.type", (String) type.getSelectedItem()); biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem()); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters(); ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters(); } } } else { } } else { // Preferences biosimrc = Preferences.userRoot(); JPanel vhdlPrefs = new JPanel(); JPanel lhpnPrefs = new JPanel(); JTabbedPane prefTabsNoLema = new JTabbedPane(); prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs); prefTabsNoLema.addTab("LHPN Preferences", lhpnPrefs); Object[] options = { "Save", "Cancel" }; // int value = JOptionPane.showOptionDialog(frame, prefTabsNoLema, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } } public void about() { final JFrame f = new JFrame("About"); // frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + // File.separator // + "gui" // + File.separator + "icons" + File.separator + // "iBioSim.png").getImage()); JLabel bioSim = new JLabel("iBioSim", JLabel.CENTER); Font font = bioSim.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); bioSim.setFont(font); JLabel version = new JLabel("Version 1.0", JLabel.CENTER); JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER); JButton credits = new JButton("Credits"); credits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] options = { "Close" }; JOptionPane.showOptionDialog(f, "Nathan Barker\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen", "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } }); JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(credits); buttons.add(close); JPanel aboutPanel = new JPanel(new BorderLayout()); JPanel uOfUPanel = new JPanel(new BorderLayout()); uOfUPanel.add(bioSim, "North"); uOfUPanel.add(version, "Center"); uOfUPanel.add(uOfU, "South"); aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png")), "North"); // aboutPanel.add(bioSim, "North"); aboutPanel.add(uOfUPanel, "Center"); aboutPanel.add(buttons, "South"); f.setContentPane(aboutPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } public void exit() { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < numberRecentProj; i++) { biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText()); biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]); } System.exit(1); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == about) { about(); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = "iBioSim.html"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } File work = new File(directory); log.addText("Executing:\n" + command + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command + theFile, null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the exit menu item is selected else if (e.getSource() == exit) { exit(); } // if the open popup menu is selected on a sim directory else if (e.getActionCommand().equals("openSim")) { openSim(); } else if (e.getActionCommand().equals("openLearn")) { openLearn(); } else if (e.getActionCommand().equals("openSynth")) { openSynth(); } else if (e.getActionCommand().equals("openVerification")) { openVerify(); } // if the create simulation popup menu is selected on a dot file else if (e.getActionCommand().equals("createSim")) { try { simulate(true); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the simulate popup menu is selected on an sbml file else if (e.getActionCommand().equals("simulate")) { try { simulate(false); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the synthesis popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createSynthesis")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:", "Synthesis View ID", JOptionPane.PLAIN_MESSAGE); if (synthName != null && !synthName.trim().equals("")) { synthName = synthName.trim(); try { if (overwrite(root + separator + synthName, synthName)) { new File(root + separator + synthName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + synthName.trim() + ".syn")); out.write(("synthesis.file=" + sbmlFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JPanel synthPane = new JPanel(); synthPane.add(new Synthesis(root + separator + synthName, sbmlFile, this)); /* * JLabel noData = new JLabel("No data available"); * Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); * lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = * new JLabel("No data available"); font = * noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD * Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(synthName, synthPane, null); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the synthesis popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createVerify")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:", "Verification View ID", JOptionPane.PLAIN_MESSAGE); if (verName != null && !verName.trim().equals("")) { verName = verName.trim(); try { if (overwrite(root + separator + verName, verName)) { new File(root + separator + verName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + verName.trim() + ".ver")); out.write(("verification.file=" + sbmlFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JPanel verPane = new JPanel(); verPane.add(new Verification(root + separator + verName, sbmlFile, this)); /* * JLabel noData = new JLabel("No data available"); * Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); * lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = * new JLabel("No data available"); font = * noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD * Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(verName, verPane, null); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Verification View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the delete popup menu is selected on a sim directory else if (e.getActionCommand().equals("deleteSim")) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } refreshTree(); } // if the delete popup menu is selected else if (e.getActionCommand().equals("delete")) { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); refreshTree(); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("createSBML")) { try { String[] dot = tree.getFile().split(separator); String sbmlFile = dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"; // log.addText("Executing:\ngcm2sbml.pl " + tree.getFile() + " " // + root // + separator + sbmlFile // Runtime exec = Runtime.getRuntime(); // String filename = tree.getFile(); // String directory = ""; // String theFile = ""; // if (filename.lastIndexOf('/') >= 0) { // directory = filename.substring(0, // filename.lastIndexOf('/') + 1); // theFile = filename.substring(filename.lastIndexOf('/') + 1); // if (filename.lastIndexOf('\\') >= 0) { // directory = filename.substring(0, filename // .lastIndexOf('\\') + 1); // theFile = filename // .substring(filename.lastIndexOf('\\') + 1); // File work = new File(directory); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + sbmlFile); refreshTree(); addTab(sbmlFile, new SBML_Editor(root + separator + sbmlFile, null, log, this, null, null), "SBML Editor"); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("dotEditor")) { try { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { File work = new File(directory); addTab(theFile, new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log), "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, 1, 1, 1, tree.getFile().substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the browse popup menu is selected on an sbml file else if (e.getActionCommand().equals("browse")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, 1, 1, 1, tree.getFile().substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + tree.getFile() + "\n"); Runtime exec = Runtime.getRuntime(); Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); String error = ""; String output = ""; InputStream reb = browse.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = browse.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } browse.waitFor(); String command = ""; if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { command = "cmd /c start "; } log.addText("Executing:\n" + command + directory + out + ".xhtml\n"); exec.exec(command + out + ".xhtml", null, work); } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph dot popup menu is selected else if (e.getActionCommand().equals("graphDot")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new menu item is selected else if (e.getSource() == newProj) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } String filename = Buttons.browse(frame, null, null, JFileChooser.DIRECTORIES_ONLY, "New"); if (!filename.trim().equals("")) { filename = filename.trim(); File f = new File(filename); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return; } } new File(filename).mkdir(); try { new FileWriter(new File(filename + separator + ".prj")).close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } } // if the open project menu item is selected else if (e.getSource() == pref) { preferences(); } else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } File f; if (root == null) { f = null; } else { f = new File(root); } String projDir = ""; if (e.getSource() == openProj) { projDir = Buttons.browse(frame, f, null, JFileChooser.DIRECTORIES_ONLY, "Open"); } else if (e.getSource() == recentProjects[0]) { projDir = recentProjectPaths[0]; } else if (e.getSource() == recentProjects[1]) { projDir = recentProjectPaths[1]; } else if (e.getSource() == recentProjects[2]) { projDir = recentProjectPaths[2]; } else if (e.getSource() == recentProjects[3]) { projDir = recentProjectPaths[3]; } else if (e.getSource() == recentProjects[4]) { projDir = recentProjectPaths[4]; } if (!projDir.equals("")) { if (new File(projDir).isDirectory()) { boolean isProject = false; for (String temp : new File(projDir).list()) { if (temp.equals(".prj")) { isProject = true; } } if (isProject) { root = projDir; refresh(); tab.removeAll(); addRecentProject(projDir); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new circuit model menu item is selected else if (e.getSource() == newCircuit) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 4).equals(".gcm")) { simName += ".gcm"; } } else { simName += ".gcm"; } String modelID = ""; if (simName.length() > 3) { if (simName.substring(simName.length() - 4).equals(".gcm")) { modelID = simName.substring(0, simName.length() - 4); } else { modelID = simName.substring(0, simName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); new GCMFile().save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } addTab(f.getName(), new GCM2SBMLEditor(root + separator, f.getName(), this, log), "GCM Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new SBML model menu item is selected else if (e.getSource() == newModel) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) { simName += ".sbml"; } } else { simName += ".sbml"; } String modelID = ""; if (simName.length() > 4) { if (simName.substring(simName.length() - 5).equals(".sbml")) { modelID = simName.substring(0, simName.length() - 5); } else { modelID = simName.substring(0, simName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(2, 3); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); document.getModel().setId(modelID); FileOutputStream out = new FileOutputStream(f); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); addTab( f.getAbsolutePath().split(separator)[f.getAbsolutePath().split(separator).length - 1], new SBML_Editor(f.getAbsolutePath(), null, log, this, null, null), "SBML Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new vhdl menu item is selected else if (e.getSource() == newVhdl) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 4) { if (!vhdlName.substring(vhdlName.length() - 5).equals(".vhd")) { vhdlName += ".vhd"; } } else { vhdlName += ".vhd"; } String modelID = ""; if (vhdlName.length() > 3) { if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) { modelID = vhdlName.substring(0, vhdlName.length() - 4); } else { modelID = vhdlName.substring(0, vhdlName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new lhpn menu item is selected else if (e.getSource() == newLhpn) { if (root != null) { try { String lhpnName = JOptionPane.showInputDialog(frame, "Enter LHPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 1) { if (!lhpnName.substring(lhpnName.length() - 2).equals(".g")) { lhpnName += ".g"; } } else { lhpnName += ".g"; } String modelID = ""; if (lhpnName.length() > 1) { if (lhpnName.substring(lhpnName.length() - 2).equals(".g")) { modelID = lhpnName.substring(0, lhpnName.length() - 2); } else { modelID = lhpnName.substring(0, lhpnName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + lhpnName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import SBML"); if (!filename.trim().equals("")) { if (new File(filename.trim()).isDirectory()) { JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML files contain the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; for (String s : new File(filename.trim()).list()) { try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim() + separator + s); if (document.getNumErrors() == 0) { if (overwrite(root + separator + s, s)) { long numErrors = document.checkConsistency(); if (numErrors > 0) { display = true; messageArea .append(" messageArea.append(s); messageArea .append("\n for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // replace messageArea.append(i + ":" + error + "\n"); } } FileOutputStream out = new FileOutputStream(new File(root + separator + s)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } refreshTree(); if (display) { final JFrame f = new JFrame("SBML Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } else { String[] file = filename.trim().split(separator); try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim()); if (document.getNumErrors() > 0) { JOptionPane.showMessageDialog(frame, "Invalid SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // replace messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import dot menu item is selected else if (e.getSource() == importDot) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit"); if (new File(filename.trim()).isDirectory()) { for (String s : new File(filename.trim()).list()) { if (!(filename.trim() + separator + s).equals("") && (filename.trim() + separator + s).length() > 3 && (filename.trim() + separator + s).substring( (filename.trim() + separator + s).length() - 4, (filename.trim() + separator + s).length()).equals(".gcm")) { try { // GCMParser parser = new GCMParser((filename.trim() + separator + s)); if (overwrite(root + separator + s, s)) { FileOutputStream out = new FileOutputStream(new File(root + separator + s)); FileInputStream in = new FileInputStream(new File( (filename.trim() + separator + s))); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { if (filename.trim().length() > 3 && !filename.trim().substring(filename.trim().length() - 4, filename.trim().length()) .equals(".gcm")) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.trim().equals("")) { String[] file = filename.trim().split(separator); try { // GCMParser parser = new GCMParser(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename.trim())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import vhdl menu item is selected else if (e.getSource() == importVhdl) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import VHDL Model"); if (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals(".vhd")) { JOptionPane.showMessageDialog(frame, "You must select a valid vhdl file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import lhpn menu item is selected else if (e.getSource() == importLhpn) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import LHPN"); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals(".g")) { JOptionPane.showMessageDialog(frame, "You must select a valid lhpn file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the Graph data menu item is clicked else if (e.getSource() == graph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName .trim(), true, false); addTab(graphName.trim(), g, "TSD Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == probGraph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Probability Graph:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName .trim(), false, false); addTab(graphName.trim(), g, "Probability Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLearn")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE); if (lrnName != null && !lrnName.trim().equals("")) { lrnName = lrnName.trim(); try { if (overwrite(root + separator + lrnName, lrnName)) { new File(root + separator + lrnName).mkdir(); // new FileWriter(new File(root + separator + // lrnName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn")); out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JTabbedPane lrnTab = new JTabbedPane(); lrnTab.addTab("Data Manager", new DataManager(root + separator + lrnName, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); lrnTab.addTab("Learn", new Learn(root + separator + lrnName, log, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("TSD Graph", new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator + lrnName, "time", this, null, log, null, true, true)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents ().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment (SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD Graph"); */ addTab(lrnName, lrnTab, null); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Learn View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("copy")) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } try { if (!copy.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".sbml") && !copy.substring(copy.length() - 4).equals(".xml")) { copy += ".sbml"; } } else { copy += ".sbml"; } if (copy.length() > 4) { if (copy.substring(copy.length() - 5).equals(".sbml")) { modelID = copy.substring(0, copy.length() - 5); } else { modelID = copy.substring(0, copy.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".vhd")) { copy += ".vhd"; } } else { copy += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".g")) { copy += ".g"; } } else { copy += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".grf")) { copy += ".grf"; } } else { copy += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".prb")) { copy += ".prb"; } } else { copy += ".prb"; } } } if (copy .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + copy, copy)) { if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(tree.getFile()); document.getModel().setId(modelID); FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); } else if ((tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm") || tree.getFile().substring(tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring(tree.getFile().length() - 4).equals(".vhd")) || (tree.getFile().length() >= 2 && tree.getFile().substring( tree.getFile().length() - 2).equals(".g"))) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); FileInputStream in = new FileInputStream(new File(tree.getFile())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { new File(root + separator + copy).mkdir(); // new FileWriter(new File(root + separator + copy + // separator + // ".sim")).close(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile() + separator + ss); FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); FileInputStream in = new FileInputStream( new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring( ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream( new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } else { new File(root + separator + copy).mkdir(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring( ss.length() - 4).equals(".lrn"))) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".lrn")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream( new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } } refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("rename")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".sbml") && !rename.substring(rename.length() - 4).equals(".xml")) { rename += ".sbml"; } } else { rename += ".sbml"; } if (rename.length() > 4) { if (rename.substring(rename.length() - 5).equals(".sbml")) { modelID = rename.substring(0, rename.length() - 5); } else { modelID = rename.substring(0, rename.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".gcm")) { rename += ".gcm"; } } else { rename += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".vhd")) { rename += ".vhd"; } } else { rename += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".g")) { rename += ".g"; } } else { rename += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".grf")) { rename += ".grf"; } } else { rename += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".prb")) { rename += ".prb"; } } else { rename += ".prb"; } } if (rename .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + rename, rename)) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(root + separator + rename); document.getModel().setId(modelID); FileOutputStream out = new FileOutputStream(new File(root + separator + rename)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); } if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm")) { updateViews(rename); } if (new File(root + separator + rename).isDirectory()) { if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").renameTo(new File(root + separator + rename + separator + rename + ".sim")); } else if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").renameTo(new File(root + separator + rename + separator + rename + ".sim")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").renameTo(new File(root + separator + rename + separator + rename + ".lrn")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").renameTo(new File(root + separator + rename + separator + rename + ".grf")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").renameTo(new File(root + separator + rename + separator + rename + ".prb")); } } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { ((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID); ((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && (tree.getFile().substring(tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring(tree.getFile().length() - 4).equals(".prb"))) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 2)); } else { JTabbedPane t = new JTabbedPane(); int selected = ((JTabbedPane) tab.getComponentAt(i)).getSelectedIndex(); boolean analysis = false; ArrayList<Component> comps = new ArrayList<Component>(); for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getTabCount(); j++) { Component c = ((JTabbedPane) tab.getComponentAt(i)).getComponent(j); comps.add(c); } for (Component c : comps) { if (c instanceof Reb2Sac) { ((Reb2Sac) c).setSim(rename); analysis = true; } else if (c instanceof SBML_Editor) { String properties = root + separator + rename + separator + rename + ".sim"; new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) c).isDirty(); ((SBML_Editor) c) .setParamFileAndSimDir(properties, root + separator + rename); ((SBML_Editor) c).save(false, "", true); ((SBML_Editor) c).updateSBML(i, 0); ((SBML_Editor) c).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File(properties)); } else if (c instanceof Graph) { Graph g = ((Graph) c); g.setDirectory(root + separator + rename); if (g.isTSDGraph()) { g.setGraphName(rename + ".grf"); } else { g.setGraphName(rename + ".prb"); } } else if (c instanceof Learn) { Learn l = ((Learn) c); l.setDirectory(root + separator + rename); } else if (c instanceof DataManager) { DataManager d = ((DataManager) c); d.setDirectory(root + separator + rename); } if (analysis) { if (c instanceof Reb2Sac) { t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1).setName("Simulate"); } else if (c instanceof SBML_Editor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1).setName("SBML Editor"); } else if (c instanceof Graph) { if (((Graph) c).isTSDGraph()) { t.addTab("TSD Graph", c); t.getComponentAt(t.getComponents().length - 1).setName("TSD Graph"); } else { t.addTab("Probability Graph", c); t.getComponentAt(t.getComponents().length - 1).setName("ProbGraph"); } } else { t.addTab("Abstraction Options", c); t.getComponentAt(t.getComponents().length - 1).setName(""); } } } if (analysis) { t.setSelectedIndex(selected); tab.setComponentAt(i, t); } tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } } } refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("openGraph")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .contains(".grf")) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], true, false), "TSD Graph"); } else { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], false, false), "Probability Graph"); } } } } public int getTab(String name) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { return i; } } return -1; } public void deleteDir(File dir) { int count = 0; do { File[] list = dir.listFiles(); System.gc(); for (int i = 0; i < list.length; i++) { if (list[i].isDirectory()) { deleteDir(list[i]); } else { list[i].delete(); } } count++; } while (!dir.delete() && count != 100); if (count == 100) { JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method adds a new project to recent list */ public void addRecentProject(String projDir) { // boolean newOne = true; for (int i = 0; i < numberRecentProj; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = 0; j <= i; j++) { String save = recentProjectPaths[j]; recentProjects[j].setText(projDir.split(separator)[projDir.split(separator).length - 1]); file.add(recentProjects[j]); recentProjectPaths[j] = projDir; projDir = save; } for (int j = i + 1; j < numberRecentProj; j++) { file.add(recentProjects[j]); } return; } } if (numberRecentProj < 5) { numberRecentProj++; } for (int i = 0; i < numberRecentProj; i++) { String save = recentProjectPaths[i]; recentProjects[i].setText(projDir.split(separator)[projDir.split(separator).length - 1]); file.add(recentProjects[i]); recentProjectPaths[i] = projDir; projDir = save; } } /** * This method refreshes the menu. */ public void refresh() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema); mainPanel.add(tree, "West"); mainPanel.validate(); } /** * This method refreshes the tree. */ public void refreshTree() { tree.fixTree(); mainPanel.validate(); updateGCM(); } /** * This method adds the given Component to a tab. */ public void addTab(String name, Component panel, String tabName) { tab.addTab(name, panel); if (tabName != null) { tab.getComponentAt(tab.getComponents().length - 1).setName(tabName); } else { tab.getComponentAt(tab.getComponents().length - 1).setName(name); } tab.setSelectedIndex(tab.getComponents().length - 1); } /** * This method removes the given component from the tabs. */ public void removeTab(Component component) { tab.remove(component); } public JTabbedPane getTab() { return tab; } /** * Prompts the user to save work that has been done. */ public int save(int index) { if (tab.getComponentAt(index).getName().contains(("GCM"))) { if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) { GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index); if (editor.isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { editor.save("gcm"); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().equals("SBML Editor")) { if (tab.getComponentAt(index) instanceof SBML_Editor) { if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().contains("Graph")) { if (tab.getComponentAt(index) instanceof Graph) { if (((Graph) tab.getComponentAt(index)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else { if (tab.getComponentAt(index) instanceof JTabbedPane) { for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName().equals( "Simulate")) { if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save simulation option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "SBML Editor")) { if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save( false, "", true); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { if (((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Data Manager")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) { ((DataManager) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .saveChanges(tab.getTitleAt(index)); } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().contains( "Graph")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { if (((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save graph changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)); g.save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } } } return 1; } } /** * Saves a circuit from a learn view to the project view */ public void saveGcm(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Returns the frame. */ public JFrame frame() { return frame; } public void mousePressed(MouseEvent e) { if (e.isPopupTrigger() && tree.getFile() != null) { popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (tree.getFile() != null) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { addTab(theFile, new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log), "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } String[] command = { "emacs", filename }; Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } String[] cmd = { "emacs", filename }; Runtime.getRuntime().exec(cmd); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this lhpn file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree .getFile(), log, tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1], true, false), "TSD Graph"); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree .getFile(), log, tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1], false, false), "Probability Graph"); } } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } if (sim) { openSim(); } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else { openLearn(); } } } } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger() && tree.getFile() != null) { popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } private void simulate(boolean isDot) throws Exception { if (isDot) { String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String[] dot = tree.getFile().split(separator); String sbmlFile = /* * root + separator + simName + separator + */(dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + simName + separator + sbmlFile); try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + separator + (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(), log, simTab, null); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } else { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile()); // document.setLevel(2); document.setLevelAndVersion(2, 3); String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String sbmlFile = tree.getFile(); String[] sbml1 = tree.getFile().split(separator); String sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((sbml1[sbml1.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } new FileOutputStream(new File(sbmlFileProp)).close(); /* * try { FileOutputStream out = new FileOutputStream(new * File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); String doc = * writer.writeToString(document); byte[] output = doc.getBytes(); * out.write(output); out.close(); } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy sbml file to * output location.", "Error", JOptionPane.ERROR_MESSAGE); } */ refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(), log, simTab, null); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } } private void openLearn() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i] .substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(), this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); lrnTab.addTab("Learn", new Learn(tree.getFile(), log, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("TSD Graph", new Graph(null, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, true)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * else { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(), * this)); lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data available"); * font = noData1.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD * Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openSynth() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel synthPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String synthFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn"; String synthFile2 = tree.getFile() + separator + ".syn"; Properties load = new Properties(); String synthesisFile = ""; try { if (new File(synthFile2).exists()) { FileInputStream in = new FileInputStream(new File(synthFile2)); load.load(in); in.close(); new File(synthFile2).delete(); } if (new File(synthFile).exists()) { FileInputStream in = new FileInputStream(new File(synthFile)); load.load(in); in.close(); if (load.containsKey("synthesis.file")) { synthesisFile = load.getProperty("synthesis.file"); synthesisFile = synthesisFile.split(separator)[synthesisFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(synthesisFile)); load.store(out, synthesisFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(synthesisFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + synthesisFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { synthPanel.add(new Synthesis(tree.getFile(), "flag", this)); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], synthPanel, null); } } private void openVerify() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel verPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String verFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".ver"; String verFile2 = tree.getFile() + separator + ".ver"; Properties load = new Properties(); String verifyFile = ""; try { if (new File(verFile2).exists()) { FileInputStream in = new FileInputStream(new File(verFile2)); load.load(in); in.close(); new File(verFile2).delete(); } if (new File(verFile).exists()) { FileInputStream in = new FileInputStream(new File(verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(verifyFile)); load.store(out, verifyFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(verifyFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + verifyFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { verPanel.add(new Synthesis(tree.getFile(), "flag", this)); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], verPanel, null); } } private void openSim() { String filename = tree.getFile(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(filename.split(separator)[filename.split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (filename != null && !filename.equals("")) { if (new File(filename).isDirectory()) { if (new File(filename + separator + ".sim").exists()) { new File(filename + separator + ".sim").delete(); } String[] list = new File(filename).list(); String getAFile = ""; // String probFile = ""; String openFile = ""; // String graphFile = ""; String open = null; String openProb = null; int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals("sbml")) { getAFile = filename + separator + list[i]; } else if (end.equals(".xml") && getAFile.equals("")) { getAFile = filename + separator + list[i]; } else if (end.equals(".txt") && list[i].contains("sim-rep")) { // probFile = filename + separator + list[i]; } else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) { openFile = filename + separator + list[i]; } else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = filename + separator + // list[i]; } } else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) { // graphFile = filename + separator + // list[i]; } else if (end.contains("=")) { // graphFile = filename + separator + // list[i]; } } else if (end.equals(".grf")) { open = filename + separator + list[i]; } else if (end.equals(".prb")) { openProb = filename + separator + list[i]; } } else if (new File(filename + separator + list[i]).isDirectory()) { String[] s = new File(filename + separator + list[i]).list(); for (int j = 0; j < s.length; j++) { if (s[j].contains("sim-rep")) { // probFile = filename + separator + list[i] // + separator + } else if (s[j].contains(".tsd")) { // graphFile = filename + separator + // list[i] + separator + } } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"; String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; if (new File(pmsFile).exists()) { if (new File(simFile).exists()) { new File(pmsFile).delete(); } else { new File(pmsFile).renameTo(new File(simFile)); } } String sbmlLoadFile = ""; if (new File(simFile).exists()) { try { Scanner s = new Scanner(new File(simFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]; if (sbmlLoadFile.equals("")) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + "the sbml linked to this view is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!(new File(root + separator + sbmlLoadFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (s.hasNextLine()) { s.nextLine(); } s.close(); File f = new File(sbmlLoadFile); if (!f.exists()) { sbmlLoadFile = root + separator + f.getName(); } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else { sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1]; if (!new File(sbmlLoadFile).exists()) { sbmlLoadFile = getAFile; /* * JOptionPane.showMessageDialog(frame, "Unable to load sbml * file.", "Error", JOptionPane.ERROR_MESSAGE); return; */ } } if (!new File(sbmlLoadFile).exists()) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1] + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); // if (open != null) { simTab.addTab("TSD Graph", reb2sac.createGraph(open)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); /* * } else if (!graphFile.equals("")) { simTab.addTab("TSD Graph", * reb2sac.createGraph(open)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } / else { JLabel noData = new * JLabel("No data available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } */ // if (openProb != null) { simTab.addTab("Probability Graph", reb2sac.createProbGraph(openProb)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * } else if (!probFile.equals("")) { simTab.addTab("Probability * Graph", reb2sac.createProbGraph(openProb)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } else { JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment (SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } /** * Embedded class that allows tabs to be closed. */ class TabbedPaneCloseButtonUI extends BasicTabbedPaneUI { public TabbedPaneCloseButtonUI() { super(); } protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect); Rectangle rect = rects[tabIndex]; g.setColor(Color.black); g.drawRect(rect.x + rect.width - 19, rect.y + 4, 13, 12); g.drawLine(rect.x + rect.width - 16, rect.y + 7, rect.x + rect.width - 10, rect.y + 13); g.drawLine(rect.x + rect.width - 10, rect.y + 7, rect.x + rect.width - 16, rect.y + 13); g.drawLine(rect.x + rect.width - 15, rect.y + 7, rect.x + rect.width - 9, rect.y + 13); g.drawLine(rect.x + rect.width - 9, rect.y + 7, rect.x + rect.width - 15, rect.y + 13); } protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + 24; } protected MouseListener createMouseListener() { return new MyMouseHandler(); } class MyMouseHandler extends MouseHandler { public MyMouseHandler() { super(); } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); int tabIndex = -1; int tabCount = tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (rects[i].contains(x, y)) { tabIndex = i; break; } } if (tabIndex >= 0 && !e.isPopupTrigger()) { Rectangle tabRect = rects[tabIndex]; y = y - tabRect.y; if ((x >= tabRect.x + tabRect.width - 18) && (x <= tabRect.x + tabRect.width - 8) && (y >= 5) && (y <= 15)) { if (save(tabIndex) == 1) { tabPane.remove(tabIndex); } } } } } } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public JMenuItem getExitButton() { return exit; } /** * This is the main method. It excecutes the BioSim GUI FrontEnd program. */ public static void main(String args[]) { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname + " environment variable does not include\nthe" + " directory containing the libsbml library file."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment" + " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file."); System.exit(1); } catch (SecurityException e) { System.err.println("Could not load the libSBML library files due to a" + " security exception."); System.exit(1); } if (args.length > 0 && args[0].equals("-lema")) { new BioSim(true); } else { new BioSim(false); } } public void copySim(String newSim) { try { new File(root + separator + newSim).mkdir(); // new FileWriter(new File(root + separator + newSim + separator + // ".sim")).close(); String oldSim = tab.getTitleAt(tab.getSelectedIndex()); String[] s = new File(root + separator + oldSim).list(); String sbmlFile = ""; String propertiesFile = ""; String sbmlLoadFile = null; for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(root + separator + oldSim + separator + ss); FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); sbmlFile = root + separator + newSim + separator + ss; } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); propertiesFile = root + separator + newSim + separator + ss; } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring(ss.length() - 4) .equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else { out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); } FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); if (ss.substring(ss.length() - 4).equals(".pms")) { if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) { new File(root + separator + newSim + separator + ss).delete(); } else { new File(root + separator + newSim + separator + ss).renameTo(new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim")); } ss = ss.substring(0, ss.length() - 4) + ".sim"; } if (ss.substring(ss.length() - 4).equals(".sim")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (scan.hasNextLine()) { scan.nextLine(); } scan.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD * Graph"); JLabel noData1 = new JLabel("No data available"); Font font1 = * noData1.getFont(); font1 = font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ tab.setComponentAt(tab.getSelectedIndex(), simTab); tab.setTitleAt(tab.getSelectedIndex(), newSim); tab.getComponentAt(tab.getSelectedIndex()).setName(newSim); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } public void refreshLearn(String learnName, boolean data) { for (int i = 0; i < tab.getComponentCount(); i++) { if (tab.getTitleAt(i).equals(learnName)) { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals("TSD Graph")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) { ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)).refresh(); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null, "amount", learnName + " data", "tsd.printer", root + separator + learnName, "time", this, null, log, null, true, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("TSD Graph"); } /* * } else { JLabel noData1 = new JLabel("No data available"); Font * font = noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); noData1.setHorizontalAlignment * (SwingConstants.CENTER); ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData1); ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j ).setName("TSD Graph"); } */ } else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) { } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn(root + separator + learnName, log, this)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("Learn"); } /* * } else { JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, noData); * ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j * ).setName("Learn"); } */ } } } } } private void updateGCM() { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles(); tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename()); } } } public void updateViews(String updatedFile) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".sim"; String properties2 = root + separator + tab + separator + tab + ".lrn"; if (new File(properties).exists()) { String check = ""; try { Scanner s = new Scanner(new File(properties)); if (s.hasNextLine()) { check = s.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } s.close(); } catch (Exception e) { } if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("SBML Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty(); ((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true); if (updatedFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + updatedFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); } else { ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile); } ((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File(properties)); } } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } ArrayList<String> saved = new ArrayList<String>(); if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { saved.add(this.tab.getTitleAt(i)); GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i); if (gcm.getSBMLFile().equals(updatedFile)) { gcm.save("save"); } } String[] files = new File(root).list(); for (String s : files) { if (s.contains(".gcm") && !saved.contains(s)) { GCMFile gcm = new GCMFile(); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(updatedFile)) { updateViews(s); } } } } } public String getRoot() { return root; } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, name + " already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { String[] views = canDelete(name); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { tab.remove(i); } } File dir = new File(fullPath); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } return true; } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to overwrite file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File", JOptionPane.ERROR_MESSAGE); return false; } } else { return false; } } else { return true; } } public void updateOpenSBML(String sbmlName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (sbmlName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof SBML_Editor) { SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null); this.tab.setComponentAt(i, newSBML); this.tab.getComponentAt(i).setName("SBML Editor"); newSBML.save(false, "", false); } } } } private String[] canDelete(String filename) { ArrayList<String> views = new ArrayList<String>(); String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } scan.close(); } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } if (check.equals(filename)) { views.add(s); } } } String[] usingViews = views.toArray(new String[0]); sort(usingViews); return usingViews; } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } private void reassignViews(String oldName, String newName) { String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { ArrayList<String> copy = new ArrayList<String>(); Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; if (check.equals(oldName)) { while (scan.hasNextLine()) { copy.add(scan.nextLine()); } scan.close(); FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim")); out.write((newName + "\n").getBytes()); for (String cop : copy) { out.write((cop + "\n").getBytes()); } out.close(); } else { scan.close(); } } } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; if (check.equals(oldName)) { p.setProperty("genenet.file", newName); FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn")); p.store(store, "Learn File Data"); store.close(); } } } catch (Exception e) { } } } } } }
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.CompatibilityFixer; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; import gcm2sbml.util.GlobalConstants; import lhpn2sbml.parser.LHPNFile; import lhpn2sbml.gui.*; import graph.Graph; import stategraph.StateGraph; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.Point; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.MouseWheelEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; //import java.awt.event.ComponentListener; //import java.awt.event.ComponentEvent; import java.awt.event.WindowFocusListener; //import java.awt.event.FocusListener; //import java.awt.event.FocusEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; //import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JViewport; //import javax.swing.tree.TreePath; import tabs.CloseAndMaxTabbedPane; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import learn.Learn; import learn.LearnLHPN; import synthesis.Synthesis; import verification.*; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; import java.net.*; //import datamanager.DataManagerLHPN; /** * This class creates a GUI for the Tstubd program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * are selected. * * @author Curtis Madsen */ public class BioSim implements MouseListener, ActionListener, MouseMotionListener, MouseWheelListener, WindowFocusListener { private JFrame frame; // Frame where components of the GUI are displayed private JMenuBar menuBar; private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu, viewModel; // The file menu private JMenuItem newProj; // The new menu item private JMenuItem newModel; // The new menu item private JMenuItem newCircuit; // The new menu item private JMenuItem newVhdl; // The new vhdl menu item private JMenuItem newLhpn; // The new lhpn menu item private JMenuItem newG; // The new petri net menu item private JMenuItem newCsp; // The new csp menu item private JMenuItem newHse; // The new handshaking extension menu item private JMenuItem newUnc; // The new extended burst mode menu item private JMenuItem newRsg; // The new rsg menu item private JMenuItem newSpice; // The new spice circuit item private JMenuItem exit; // The exit menu item private JMenuItem importSbml; // The import sbml menu item private JMenuItem importBioModel; // The import sbml menu item private JMenuItem importDot; // The import dot menu item private JMenuItem importVhdl; // The import vhdl menu item private JMenuItem importLhpn; // The import lhpn menu item private JMenuItem importLpn; // The import lpn menu item private JMenuItem importG; // The import .g file menu item private JMenuItem importCsp; // The import csp menu item private JMenuItem importHse; // The import handshaking extension menu // item private JMenuItem importUnc; // The import extended burst mode menu item private JMenuItem importRsg; // The import rsg menu item private JMenuItem importSpice; // The import spice circuit item private JMenuItem manual; // The manual menu item private JMenuItem about; // The about menu item private JMenuItem openProj; // The open menu item private JMenuItem pref; // The preferences menu item private JMenuItem graph; // The graph menu item private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng, exportSvg, exportTsd; private String root; // The root directory private FileTree tree; // FileTree private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools private JToolBar toolbar; // Tool bar for common options private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool // Bar // options private JPanel mainPanel; // the main panel public Log log; // the log private JPopupMenu popup; // popup menu private String separator; private KeyEventDispatcher dispatcher; private JMenuItem recentProjects[]; private String recentProjectPaths[]; private int numberRecentProj; private int ShortCutKey; public boolean checkUndeclared, checkUnits; private JCheckBox Undeclared, Units, viewerCheck; private JTextField viewerField; private JLabel viewerLabel; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean async, externView, treeSelected = false, popupFlag = false, menuFlag = false; public boolean atacs, lema; private String viewer; private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml, saveAsTemplate, saveGcmAsLhpn, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules, viewTrace, viewLog, viewCoverage, viewVHDL, viewVerilog, viewLHPN, saveParam, saveSbml, saveTemp, viewModGraph, viewModBrowser, createAnal, createLearn, createSbml, createSynth, createVer, close, closeAll; public String ENVVAR; public static final int SBML_LEVEL = 2; public static final int SBML_VERSION = 4; public static final Object[] OPTIONS = { "Yes", "No", "Yes To All", "No To All", "Cancel" }; public static final int YES_OPTION = JOptionPane.YES_OPTION; public static final int NO_OPTION = JOptionPane.NO_OPTION; public static final int YES_TO_ALL_OPTION = JOptionPane.CANCEL_OPTION; public static final int NO_TO_ALL_OPTION = 3; public static final int CANCEL_OPTION = 4; public class MacOSAboutHandler extends Application { public MacOSAboutHandler() { addApplicationListener(new AboutBoxHandler()); } class AboutBoxHandler extends ApplicationAdapter { public void handleAbout(ApplicationEvent event) { about(); event.setHandled(true); } } } public class MacOSPreferencesHandler extends Application { public MacOSPreferencesHandler() { addApplicationListener(new PreferencesHandler()); } class PreferencesHandler extends ApplicationAdapter { public void handlePreferences(ApplicationEvent event) { preferences(); event.setHandled(true); } } } public class MacOSQuitHandler extends Application { public MacOSQuitHandler() { addApplicationListener(new QuitHandler()); } class QuitHandler extends ApplicationAdapter { public void handleQuit(ApplicationEvent event) { exit(); event.setHandled(true); } } } /** * This is the constructor for the Proj class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. * * @throws Exception */ public BioSim(boolean lema, boolean atacs) { this.lema = lema; this.atacs = atacs; async = lema || atacs; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } if (atacs) { ENVVAR = System.getenv("ATACSGUI"); } else if (lema) { ENVVAR = System.getenv("LEMA"); } else { ENVVAR = System.getenv("BIOSIM"); } // Creates a new frame if (lema) { frame = new JFrame("LEMA"); frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "LEMA.png").getImage()); } else if (atacs) { frame = new JFrame("ATACS"); frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "ATACS.png").getImage()); } else { frame = new JFrame("iBioSim"); frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } // Makes it so that clicking the x in the corner closes the program WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { exit.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; frame.addWindowListener(w); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowFocusListener(this); popup = new JPopupMenu(); popup.addMouseListener(this); // popup.addFocusListener(this); // popup.addComponentListener(this); // Sets up the Tool Bar toolbar = new JToolBar(); String imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "save.png"; saveButton = makeToolButton(imgName, "save", "Save", "Save"); // toolButton = new JButton("Save"); toolbar.add(saveButton); imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "saveas.png"; saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As"); toolbar.add(saveasButton); imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "run-icon.jpg"; runButton = makeToolButton(imgName, "run", "Save and Run", "Run"); // toolButton = new JButton("Run"); toolbar.add(runButton); imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "refresh.jpg"; refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh"); toolbar.add(refreshButton); imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "savecheck.png"; checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check"); toolbar.add(checkButton); imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "export.jpg"; exportButton = makeToolButton(imgName, "export", "Export", "Export"); toolbar.add(exportButton); saveButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); saveasButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // Creates a menu for the frame menuBar = new JMenuBar(); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); help = new JMenu("Help"); help.setMnemonic(KeyEvent.VK_H); edit = new JMenu("Edit"); edit.setMnemonic(KeyEvent.VK_E); importMenu = new JMenu("Import"); exportMenu = new JMenu("Export"); newMenu = new JMenu("New"); saveAsMenu = new JMenu("Save As"); view = new JMenu("View"); viewModel = new JMenu("Model"); tools = new JMenu("Tools"); menuBar.add(file); menuBar.add(edit); menuBar.add(view); menuBar.add(tools); menuBar.add(help); // menuBar.addFocusListener(this); // menuBar.addMouseListener(this); // file.addMouseListener(this); // edit.addMouseListener(this); // view.addMouseListener(this); // tools.addMouseListener(this); // help.addMouseListener(this); copy = new JMenuItem("Copy"); rename = new JMenuItem("Rename"); delete = new JMenuItem("Delete"); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); close = new JMenuItem("Close"); closeAll = new JMenuItem("Close All"); pref = new JMenuItem("Preferences"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); newSpice = new JMenuItem("Spice Circuit"); if (lema) { newVhdl = new JMenuItem("VHDL-AMS Model"); newLhpn = new JMenuItem("Labeled Hybrid Petri Net"); } else { newVhdl = new JMenuItem("VHDL Model"); newLhpn = new JMenuItem("Labeled Petri Net"); } newG = new JMenuItem("Petri Net"); newCsp = new JMenuItem("CSP Model"); newHse = new JMenuItem("Handshaking Expansion"); newUnc = new JMenuItem("Extended Burst Mode Machine"); newRsg = new JMenuItem("Reduced State Graph"); graph = new JMenuItem("TSD Graph"); probGraph = new JMenuItem("Histogram"); importSbml = new JMenuItem("SBML Model"); importBioModel = new JMenuItem("BioModel"); importDot = new JMenuItem("Genetic Circuit Model"); importG = new JMenuItem("Petri Net"); importLpn = new JMenuItem("Labeled Petri Net"); importLhpn = new JMenuItem("Labeled Hybrid Petri Net"); if (lema) { importVhdl = new JMenuItem("VHDL-AMS Model"); } else { importVhdl = new JMenuItem("VHDL Model"); } importSpice = new JMenuItem("Spice Circuit"); importCsp = new JMenuItem("CSP Model"); importHse = new JMenuItem("Handshaking Expansion"); importUnc = new JMenuItem("Extended Burst Mode Machine"); importRsg = new JMenuItem("Reduced State Graph"); exportCsv = new JMenuItem("Comma Separated Values (csv)"); exportDat = new JMenuItem("Tab Delimited Data (dat)"); exportEps = new JMenuItem("Encapsulated Postscript (eps)"); exportJpg = new JMenuItem("JPEG (jpg)"); exportPdf = new JMenuItem("Portable Document Format (pdf)"); exportPng = new JMenuItem("Portable Network Graphics (png)"); exportSvg = new JMenuItem("Scalable Vector Graphics (svg)"); exportTsd = new JMenuItem("Time Series Data (tsd)"); save = new JMenuItem("Save"); saveAs = new JMenuItem("Save As"); saveAsGcm = new JMenuItem("Genetic Circuit Model"); saveAsGraph = new JMenuItem("Graph"); saveAsSbml = new JMenuItem("Save SBML Model"); saveAsTemplate = new JMenuItem("Save SBML Template"); saveGcmAsLhpn = new JMenuItem("Save LHPN Model"); saveAsLhpn = new JMenuItem("LHPN"); run = new JMenuItem("Save and Run"); check = new JMenuItem("Save and Check"); saveSbml = new JMenuItem("Save as SBML"); saveTemp = new JMenuItem("Save as SBML Template"); saveParam = new JMenuItem("Save Parameters"); refresh = new JMenuItem("Refresh"); export = new JMenuItem("Export"); viewCircuit = new JMenuItem("Circuit"); viewRules = new JMenuItem("Production Rules"); viewTrace = new JMenuItem("Error Trace"); viewLog = new JMenuItem("Log"); viewCoverage = new JMenuItem("Coverage Report"); viewVHDL = new JMenuItem("VHDL-AMS Model"); viewVerilog = new JMenuItem("Verilog-AMS Model"); viewLHPN = new JMenuItem("LHPN Model"); viewModGraph = new JMenuItem("Model"); viewModBrowser = new JMenuItem("Model in Browser"); createAnal = new JMenuItem("Analysis Tool"); createLearn = new JMenuItem("Learn Tool"); createSbml = new JMenuItem("Create SBML File"); createSynth = new JMenuItem("Synthesis Tool"); createVer = new JMenuItem("Verification Tool"); exit = new JMenuItem("Exit"); copy.addActionListener(this); rename.addActionListener(this); delete.addActionListener(this); openProj.addActionListener(this); close.addActionListener(this); closeAll.addActionListener(this); pref.addActionListener(this); manual.addActionListener(this); newProj.addActionListener(this); newCircuit.addActionListener(this); newModel.addActionListener(this); newVhdl.addActionListener(this); newLhpn.addActionListener(this); newG.addActionListener(this); newCsp.addActionListener(this); newHse.addActionListener(this); newUnc.addActionListener(this); newRsg.addActionListener(this); newSpice.addActionListener(this); exit.addActionListener(this); about.addActionListener(this); importSbml.addActionListener(this); importBioModel.addActionListener(this); importDot.addActionListener(this); importVhdl.addActionListener(this); importLhpn.addActionListener(this); importLpn.addActionListener(this); importG.addActionListener(this); importCsp.addActionListener(this); importHse.addActionListener(this); importUnc.addActionListener(this); importRsg.addActionListener(this); importSpice.addActionListener(this); exportCsv.addActionListener(this); exportDat.addActionListener(this); exportEps.addActionListener(this); exportJpg.addActionListener(this); exportPdf.addActionListener(this); exportPng.addActionListener(this); exportSvg.addActionListener(this); exportTsd.addActionListener(this); graph.addActionListener(this); probGraph.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); saveAsSbml.addActionListener(this); saveAsTemplate.addActionListener(this); saveGcmAsLhpn.addActionListener(this); run.addActionListener(this); check.addActionListener(this); saveSbml.addActionListener(this); saveTemp.addActionListener(this); saveParam.addActionListener(this); export.addActionListener(this); viewCircuit.addActionListener(this); viewRules.addActionListener(this); viewTrace.addActionListener(this); viewLog.addActionListener(this); viewCoverage.addActionListener(this); viewVHDL.addActionListener(this); viewVerilog.addActionListener(this); viewLHPN.addActionListener(this); viewModGraph.addActionListener(this); viewModBrowser.addActionListener(this); createAnal.addActionListener(this); createLearn.addActionListener(this); createSbml.addActionListener(this); createSynth.addActionListener(this); createVer.addActionListener(this); save.setActionCommand("save"); saveAs.setActionCommand("saveas"); run.setActionCommand("run"); check.setActionCommand("check"); refresh.setActionCommand("refresh"); export.setActionCommand("export"); if (atacs) { viewModGraph.setActionCommand("viewModel"); } else { viewModGraph.setActionCommand("graph"); } viewModBrowser.setActionCommand("browse"); createLearn.setActionCommand("createLearn"); createSbml.setActionCommand("createSBML"); createSynth.setActionCommand("createSynthesis"); createVer.setActionCommand("createVerify"); ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey)); rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); // newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, // ShortCutKey)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey)); close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey)); closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey | KeyEvent.SHIFT_MASK)); // saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, // ShortCutKey)); // newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey)); // newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, // ShortCutKey)); // newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, // ShortCutKey)); // about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, // ShortCutKey)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey)); pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey)); viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0)); if (lema) { // viewCoverage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, // 0)); // SB viewVHDL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0)); viewVerilog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); viewLHPN.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); viewTrace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0)); } else { viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey)); createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey)); } Action newAction = new NewAction(); Action saveAction = new SaveAction(); Action importAction = new ImportAction(); Action exportAction = new ExportAction(); Action modelAction = new ModelAction(); newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new"); newMenu.getActionMap().put("new", newAction); saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "save"); saveAsMenu.getActionMap().put("save", saveAction); importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "import"); importMenu.getActionMap().put("import", importAction); exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "export"); exportMenu.getActionMap().put("export", exportAction); viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "model"); viewModel.getActionMap().put("model", modelAction); // graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, // ShortCutKey)); // probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); // if (!lema) { // importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // else { // importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, // ShortCutKey)); // importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); newMenu.setMnemonic(KeyEvent.VK_N); saveAsMenu.setMnemonic(KeyEvent.VK_A); importMenu.setMnemonic(KeyEvent.VK_I); exportMenu.setMnemonic(KeyEvent.VK_E); viewModel.setMnemonic(KeyEvent.VK_M); copy.setMnemonic(KeyEvent.VK_C); rename.setMnemonic(KeyEvent.VK_R); delete.setMnemonic(KeyEvent.VK_D); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); close.setMnemonic(KeyEvent.VK_W); newCircuit.setMnemonic(KeyEvent.VK_G); newModel.setMnemonic(KeyEvent.VK_S); newVhdl.setMnemonic(KeyEvent.VK_V); newLhpn.setMnemonic(KeyEvent.VK_L); newG.setMnemonic(KeyEvent.VK_N); newSpice.setMnemonic(KeyEvent.VK_P); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_H); if (!async) { importDot.setMnemonic(KeyEvent.VK_G); } else { importLhpn.setMnemonic(KeyEvent.VK_L); } importSbml.setMnemonic(KeyEvent.VK_S); // importBioModel.setMnemonic(KeyEvent.VK_S); importVhdl.setMnemonic(KeyEvent.VK_V); importSpice.setMnemonic(KeyEvent.VK_P); save.setMnemonic(KeyEvent.VK_S); run.setMnemonic(KeyEvent.VK_R); check.setMnemonic(KeyEvent.VK_K); exportCsv.setMnemonic(KeyEvent.VK_C); exportEps.setMnemonic(KeyEvent.VK_E); exportDat.setMnemonic(KeyEvent.VK_D); exportJpg.setMnemonic(KeyEvent.VK_J); exportPdf.setMnemonic(KeyEvent.VK_F); exportPng.setMnemonic(KeyEvent.VK_G); exportSvg.setMnemonic(KeyEvent.VK_S); exportTsd.setMnemonic(KeyEvent.VK_T); pref.setMnemonic(KeyEvent.VK_P); viewModGraph.setMnemonic(KeyEvent.VK_G); viewModBrowser.setMnemonic(KeyEvent.VK_B); createAnal.setMnemonic(KeyEvent.VK_A); createLearn.setMnemonic(KeyEvent.VK_L); importDot.setEnabled(false); importSbml.setEnabled(false); importBioModel.setEnabled(false); importVhdl.setEnabled(false); importLhpn.setEnabled(false); importLpn.setEnabled(false); importG.setEnabled(false); importCsp.setEnabled(false); importHse.setEnabled(false); importUnc.setEnabled(false); importRsg.setEnabled(false); importSpice.setEnabled(false); exportMenu.setEnabled(false); // exportCsv.setEnabled(false); // exportDat.setEnabled(false); // exportEps.setEnabled(false); // exportJpg.setEnabled(false); // exportPdf.setEnabled(false); // exportPng.setEnabled(false); // exportSvg.setEnabled(false); // exportTsd.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); newVhdl.setEnabled(false); newLhpn.setEnabled(false); newG.setEnabled(false); newCsp.setEnabled(false); newHse.setEnabled(false); newUnc.setEnabled(false); newRsg.setEnabled(false); newSpice.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); save.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); run.setEnabled(false); check.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); saveParam.setEnabled(false); refresh.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); edit.add(copy); edit.add(rename); // edit.add(refresh); edit.add(delete); // edit.addSeparator(); // edit.add(pref); file.add(newMenu); newMenu.add(newProj); if (!async) { newMenu.add(newCircuit); newMenu.add(newModel); } else if (atacs) { newMenu.add(newVhdl); newMenu.add(newG); newMenu.add(newLhpn); newMenu.add(newCsp); newMenu.add(newHse); newMenu.add(newUnc); newMenu.add(newRsg); } else { newMenu.add(newVhdl); newMenu.add(newLhpn); // newMenu.add(newSpice); } newMenu.add(graph); if (!async) { newMenu.add(probGraph); } file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(close); file.add(closeAll); file.addSeparator(); file.add(save); // file.add(saveAsMenu); if (!async) { saveAsMenu.add(saveAsGcm); saveAsMenu.add(saveAsGraph); saveAsMenu.add(saveAsSbml); saveAsMenu.add(saveAsTemplate); saveAsMenu.add(saveGcmAsLhpn); } else { saveAsMenu.add(saveAsLhpn); saveAsMenu.add(saveAsGraph); } file.add(saveAs); if (!async) { file.add(saveAsSbml); file.add(saveAsTemplate); file.add(saveGcmAsLhpn); } file.add(saveParam); file.add(run); if (!async) { file.add(check); } file.addSeparator(); file.add(importMenu); if (!async) { importMenu.add(importDot); importMenu.add(importSbml); importMenu.add(importBioModel); } else if (atacs) { importMenu.add(importVhdl); importMenu.add(importG); importMenu.add(importLpn); importMenu.add(importCsp); importMenu.add(importHse); importMenu.add(importUnc); importMenu.add(importRsg); } else { importMenu.add(importVhdl); importMenu.add(importLhpn); // importMenu.add(importSpice); } file.add(exportMenu); exportMenu.add(exportCsv); exportMenu.add(exportDat); exportMenu.add(exportEps); exportMenu.add(exportJpg); exportMenu.add(exportPdf); exportMenu.add(exportPng); exportMenu.add(exportSvg); exportMenu.add(exportTsd); file.addSeparator(); // file.add(save); // file.add(saveAs); // file.add(run); // file.add(check); // if (!lema) { // file.add(saveParam); // file.addSeparator(); // file.add(export); // if (!lema) { // file.add(saveSbml); // file.add(saveTemp); help.add(manual); externView = false; viewer = ""; if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { edit.addSeparator(); edit.add(pref); file.add(exit); file.addSeparator(); help.add(about); } if (lema) { view.add(viewVHDL); view.add(viewVerilog); view.add(viewLHPN); view.addSeparator(); view.add(viewCoverage); view.add(viewLog); view.add(viewTrace); } else if (atacs) { view.add(viewModGraph); view.add(viewCircuit); view.add(viewRules); view.add(viewTrace); view.add(viewLog); } else { view.add(viewModGraph); view.add(viewModBrowser); view.add(viewLog); view.addSeparator(); view.add(refresh); } if (!async) { tools.add(createAnal); } if (!atacs) { tools.add(createLearn); } if (atacs) { tools.add(createSynth); } if (async) { tools.add(createVer); } // else { // tools.add(createSbml); root = null; // Create recent project menu items numberRecentProj = 0; recentProjects = new JMenuItem[5]; recentProjectPaths = new String[5]; for (int i = 0; i < 5; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjects[i].setActionCommand("recent" + i); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_5); Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < 5; i++) { if (atacs) { recentProjects[i].setText(biosimrc.get("atacs.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("atacs.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } else if (lema) { recentProjects[i].setText(biosimrc.get("lema.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("lema.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } else { recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } } if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { // file.add(pref); // file.add(exit); help.add(about); } if (biosimrc.get("biosim.check.undeclared", "").equals("false")) { checkUndeclared = false; } else { checkUndeclared = true; } if (biosimrc.get("biosim.check.units", "").equals("false")) { checkUnits = false; } else { checkUnits = true; } if (biosimrc.get("biosim.general.file_browser", "").equals("")) { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KREP_VALUE", ".5"); } if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KACT_VALUE", ".0033"); } if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBIO_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2"); } if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001"); } if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.OCR_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075"); } if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_VALUE", "30"); } if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2"); } if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25"); } if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1"); } if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.INITIAL_VALUE", "0"); } if (biosimrc.get("biosim.sim.abs", "").equals("")) { biosimrc.put("biosim.sim.abs", "None"); } if (biosimrc.get("biosim.sim.type", "").equals("")) { biosimrc.put("biosim.sim.type", "ODE"); } if (biosimrc.get("biosim.sim.sim", "").equals("")) { biosimrc.put("biosim.sim.sim", "rkf45"); } if (biosimrc.get("biosim.sim.limit", "").equals("")) { biosimrc.put("biosim.sim.limit", "100.0"); } if (biosimrc.get("biosim.sim.useInterval", "").equals("")) { biosimrc.put("biosim.sim.useInterval", "Print Interval"); } if (biosimrc.get("biosim.sim.interval", "").equals("")) { biosimrc.put("biosim.sim.interval", "1.0"); } if (biosimrc.get("biosim.sim.step", "").equals("")) { biosimrc.put("biosim.sim.step", "inf"); } if (biosimrc.get("biosim.sim.min.step", "").equals("")) { biosimrc.put("biosim.sim.min.step", "0"); } if (biosimrc.get("biosim.sim.error", "").equals("")) { biosimrc.put("biosim.sim.error", "1.0E-9"); } if (biosimrc.get("biosim.sim.seed", "").equals("")) { biosimrc.put("biosim.sim.seed", "314159"); } if (biosimrc.get("biosim.sim.runs", "").equals("")) { biosimrc.put("biosim.sim.runs", "1"); } if (biosimrc.get("biosim.sim.rapid1", "").equals("")) { biosimrc.put("biosim.sim.rapid1", "0.1"); } if (biosimrc.get("biosim.sim.rapid2", "").equals("")) { biosimrc.put("biosim.sim.rapid2", "0.1"); } if (biosimrc.get("biosim.sim.qssa", "").equals("")) { biosimrc.put("biosim.sim.qssa", "0.1"); } if (biosimrc.get("biosim.sim.concentration", "").equals("")) { biosimrc.put("biosim.sim.concentration", "15"); } if (biosimrc.get("biosim.learn.tn", "").equals("")) { biosimrc.put("biosim.learn.tn", "2"); } if (biosimrc.get("biosim.learn.tj", "").equals("")) { biosimrc.put("biosim.learn.tj", "2"); } if (biosimrc.get("biosim.learn.ti", "").equals("")) { biosimrc.put("biosim.learn.ti", "0.5"); } if (biosimrc.get("biosim.learn.bins", "").equals("")) { biosimrc.put("biosim.learn.bins", "4"); } if (biosimrc.get("biosim.learn.equaldata", "").equals("")) { biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins"); } if (biosimrc.get("biosim.learn.autolevels", "").equals("")) { biosimrc.put("biosim.learn.autolevels", "Auto"); } if (biosimrc.get("biosim.learn.ta", "").equals("")) { biosimrc.put("biosim.learn.ta", "1.15"); } if (biosimrc.get("biosim.learn.tr", "").equals("")) { biosimrc.put("biosim.learn.tr", "0.75"); } if (biosimrc.get("biosim.learn.tm", "").equals("")) { biosimrc.put("biosim.learn.tm", "0.0"); } if (biosimrc.get("biosim.learn.tt", "").equals("")) { biosimrc.put("biosim.learn.tt", "0.025"); } if (biosimrc.get("biosim.learn.debug", "").equals("")) { biosimrc.put("biosim.learn.debug", "0"); } if (biosimrc.get("biosim.learn.succpred", "").equals("")) { biosimrc.put("biosim.learn.succpred", "Successors"); } if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) { biosimrc.put("biosim.learn.findbaseprob", "False"); } // Open .biosimrc here // Packs the frame and displays it mainPanel = new JPanel(new BorderLayout()); tree = new FileTree(null, this, lema, atacs); log = new Log(); tab = new CloseAndMaxTabbedPane(false, this); tab.setPreferredSize(new Dimension(1100, 550)); tab.getPaneUI().addMouseListener(this); mainPanel.add(tree, "West"); mainPanel.add(tab, "Center"); mainPanel.add(log, "South"); mainPanel.add(toolbar, "North"); frame.setContentPane(mainPanel); frame.setJMenuBar(menuBar); frame.getGlassPane().setVisible(true); frame.getGlassPane().addMouseListener(this); frame.getGlassPane().addMouseMotionListener(this); frame.getGlassPane().addMouseWheelListener(this); frame.addMouseListener(this); menuBar.addMouseListener(this); frame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; frame.setSize(frameSize); } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; frame.setSize(frameSize); } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; frame.setLocation(x, y); frame.setVisible(true); dispatcher = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_TYPED) { if (e.getKeyChar() == '') { if (tab.getTabCount() > 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager() .removeKeyEventDispatcher(dispatcher); if (save(tab.getSelectedIndex(), 0) != 0) { tab.remove(tab.getSelectedIndex()); } KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(dispatcher); } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); } public void preferences() { if (!async) { Undeclared = new JCheckBox("Check for undeclared units in SBML"); if (checkUndeclared) { Undeclared.setSelected(true); } else { Undeclared.setSelected(false); } Units = new JCheckBox("Check units in SBML"); if (checkUnits) { Units.setSelected(true); } else { Units.setSelected(false); } Preferences biosimrc = Preferences.userRoot(); JCheckBox dialog = new JCheckBox("Use File Dialog"); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { dialog.setSelected(true); } else { dialog.setSelected(false); } final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get( "biosim.gcm.ACTIVED_VALUE", "")); final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", "")); final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", "")); final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.COOPERATIVITY_VALUE", "")); final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KASSOCIATION_VALUE", "")); final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", "")); final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get( "biosim.gcm.PROMOTER_COUNT_VALUE", "")); final JTextField INITIAL_VALUE = new JTextField(biosimrc.get( "biosim.gcm.INITIAL_VALUE", "")); final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get( "biosim.gcm.MAX_DIMER_VALUE", "")); final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", "")); final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.RNAP_BINDING_VALUE", "")); final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", "")); final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.STOICHIOMETRY_VALUE", "")); JPanel labels = new JPanel(new GridLayout(15, 1)); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.KASSOCIATION_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):")); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(15, 1)); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KBIO_VALUE); fields.add(KDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(KASSOCIATION_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_VALUE); fields.add(MAX_DIMER_VALUE); fields.add(OCR_VALUE); fields.add(RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); String[] choices = { "None", "Abstraction", "Logical Abstraction" }; final JComboBox abs = new JComboBox(choices); abs.setSelectedItem(biosimrc.get("biosim.sim.abs", "")); if (abs.getSelectedItem().equals("None")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else if (abs.getSelectedItem().equals("Abstraction")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else { choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser", "LHPN" }; } final JComboBox type = new JComboBox(choices); type.setSelectedItem(biosimrc.get("biosim.sim.type", "")); if (type.getSelectedItem().equals("ODE")) { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } else if (type.getSelectedItem().equals("Monte Carlo")) { choices = new String[] { "gillespie", "mpde", "mp", "mp-adaptive", "mp-event", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "markov-chain-analysis", "atacs", "ctmc-transient" }; } else { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } final JComboBox sim = new JComboBox(choices); sim.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); abs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (abs.getSelectedItem().equals("None")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else if (abs.getSelectedItem().equals("Abstraction")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("Monte Carlo"); type.addItem("Markov"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.addItem("LHPN"); type.setSelectedItem(o); } } }); type.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (type.getSelectedItem() == null) { } else if (type.getSelectedItem().equals("ODE")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Monte Carlo")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("gillespie"); sim.addItem("mpde"); sim.addItem("mp"); sim.addItem("mp-adaptive"); sim.addItem("mp-event"); sim.addItem("emc-sim"); sim.addItem("bunker"); sim.addItem("nmc"); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Markov")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("atacs"); sim.addItem("ctmc-transient"); sim.setSelectedItem(o); } else { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } } }); JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", "")); JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", "")); JTextField minStep = new JTextField(biosimrc.get("biosim.sim.min.step", "")); JTextField step = new JTextField(biosimrc.get("biosim.sim.step", "")); JTextField error = new JTextField(biosimrc.get("biosim.sim.error", "")); JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", "")); JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", "")); JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", "")); JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", "")); JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", "")); JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", "")); choices = new String[] { "Print Interval", "Minimum Print Interval", "Number Of Steps" }; JComboBox useInterval = new JComboBox(choices); useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", "")); JPanel analysisLabels = new JPanel(new GridLayout(14, 1)); analysisLabels.add(new JLabel("Abstraction:")); analysisLabels.add(new JLabel("Simulation Type:")); analysisLabels.add(new JLabel("Possible Simulators/Analyzers:")); analysisLabels.add(new JLabel("Time Limit:")); analysisLabels.add(useInterval); analysisLabels.add(new JLabel("Minimum Time Step:")); analysisLabels.add(new JLabel("Maximum Time Step:")); analysisLabels.add(new JLabel("Absolute Error:")); analysisLabels.add(new JLabel("Random Seed:")); analysisLabels.add(new JLabel("Runs:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:")); analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:")); analysisLabels.add(new JLabel("QSSA Condition:")); analysisLabels.add(new JLabel("Max Concentration Threshold:")); JPanel analysisFields = new JPanel(new GridLayout(14, 1)); analysisFields.add(abs); analysisFields.add(type); analysisFields.add(sim); analysisFields.add(limit); analysisFields.add(interval); analysisFields.add(minStep); analysisFields.add(step); analysisFields.add(error); analysisFields.add(seed); analysisFields.add(runs); analysisFields.add(rapid1); analysisFields.add(rapid2); analysisFields.add(qssa); analysisFields.add(concentration); JPanel analysisPrefs = new JPanel(new GridLayout(1, 2)); analysisPrefs.add(analysisLabels); analysisPrefs.add(analysisFields); final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", "")); final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", "")); final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", "")); choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; final JComboBox bins = new JComboBox(choices); bins.setSelectedItem(biosimrc.get("biosim.learn.bins", "")); choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" }; final JComboBox equaldata = new JComboBox(choices); equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", "")); choices = new String[] { "Auto", "User" }; final JComboBox autolevels = new JComboBox(choices); autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", "")); final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", "")); final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", "")); final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", "")); final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", "")); choices = new String[] { "0", "1", "2", "3" }; final JComboBox debug = new JComboBox(choices); debug.setSelectedItem(biosimrc.get("biosim.learn.debug", "")); choices = new String[] { "Successors", "Predecessors", "Both" }; final JComboBox succpred = new JComboBox(choices); succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", "")); choices = new String[] { "True", "False" }; final JComboBox findbaseprob = new JComboBox(choices); findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", "")); JPanel learnLabels = new JPanel(new GridLayout(13, 1)); learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):")); learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):")); learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):")); learnLabels.add(new JLabel("Number Of Bins:")); learnLabels.add(new JLabel("Divide Bins:")); learnLabels.add(new JLabel("Generate Levels:")); learnLabels.add(new JLabel("Ratio For Activation (Ta):")); learnLabels.add(new JLabel("Ratio For Repression (Tr):")); learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):")); learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):")); learnLabels.add(new JLabel("Debug Level:")); learnLabels.add(new JLabel("Successors Or Predecessors:")); learnLabels.add(new JLabel("Basic FindBaseProb:")); JPanel learnFields = new JPanel(new GridLayout(13, 1)); learnFields.add(tn); learnFields.add(tj); learnFields.add(ti); learnFields.add(bins); learnFields.add(equaldata); learnFields.add(autolevels); learnFields.add(ta); learnFields.add(tr); learnFields.add(tm); learnFields.add(tt); learnFields.add(debug); learnFields.add(succpred); learnFields.add(findbaseprob); JPanel learnPrefs = new JPanel(new GridLayout(1, 2)); learnPrefs.add(learnLabels); learnPrefs.add(learnFields); JPanel generalPrefs = new JPanel(new BorderLayout()); generalPrefs.add(dialog, "North"); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); sbmlPrefsBordered.add(Undeclared, "North"); sbmlPrefsBordered.add(Units, "Center"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", dialog); prefTabs.addTab("SBML Preferences", sbmlPrefs); prefTabs.addTab("GCM Preferences", gcmPrefs); prefTabs.addTab("Analysis Preferences", analysisPrefs); prefTabs.addTab("Learn Preferences", learnPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (dialog.isSelected()) { biosimrc.put("biosim.general.file_browser", "FileDialog"); } else { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (Undeclared.isSelected()) { checkUndeclared = true; biosimrc.put("biosim.check.undeclared", "true"); } else { checkUndeclared = false; biosimrc.put("biosim.check.undeclared", "false"); } if (Units.isSelected()) { checkUnits = true; biosimrc.put("biosim.check.units", "true"); } else { checkUnits = false; biosimrc.put("biosim.check.units", "false"); } try { Double.parseDouble(KREP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KACT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBIO_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KASSOCIATION_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KBASAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(OCR_VALUE.getText().trim()); biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(COOPERATIVITY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(ACTIVED_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(MAX_DIMER_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(INITIAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(limit.getText().trim()); biosimrc.put("biosim.sim.limit", limit.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(interval.getText().trim()); biosimrc.put("biosim.sim.interval", interval.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(minStep.getText().trim()); biosimrc.put("biosim.min.sim.step", minStep.getText().trim()); } catch (Exception e1) { } try { if (step.getText().trim().equals("inf")) { biosimrc.put("biosim.sim.step", step.getText().trim()); } else { Double.parseDouble(step.getText().trim()); biosimrc.put("biosim.sim.step", step.getText().trim()); } } catch (Exception e1) { } try { Double.parseDouble(error.getText().trim()); biosimrc.put("biosim.sim.error", error.getText().trim()); } catch (Exception e1) { } try { Long.parseLong(seed.getText().trim()); biosimrc.put("biosim.sim.seed", seed.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(runs.getText().trim()); biosimrc.put("biosim.sim.runs", runs.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid1.getText().trim()); biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid2.getText().trim()); biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(qssa.getText().trim()); biosimrc.put("biosim.sim.qssa", qssa.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(concentration.getText().trim()); biosimrc.put("biosim.sim.concentration", concentration.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem()); biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem()); biosimrc.put("biosim.sim.type", (String) type.getSelectedItem()); biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem()); try { Integer.parseInt(tn.getText().trim()); biosimrc.put("biosim.learn.tn", tn.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(tj.getText().trim()); biosimrc.put("biosim.learn.tj", tj.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ti.getText().trim()); biosimrc.put("biosim.learn.ti", ti.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem()); biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem()); biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem()); try { Double.parseDouble(ta.getText().trim()); biosimrc.put("biosim.learn.ta", ta.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tr.getText().trim()); biosimrc.put("biosim.learn.tr", tr.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tm.getText().trim()); biosimrc.put("biosim.learn.tm", tm.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tt.getText().trim()); biosimrc.put("biosim.learn.tt", tt.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem()); biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem()); biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem()); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters(); ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters(); } } } else { } } else { JPanel prefPanel = new JPanel(new GridLayout(0, 2)); viewerLabel = new JLabel("External Editor for non-LHPN files:"); viewerField = new JTextField(""); viewerCheck = new JCheckBox("Use External Viewer"); viewerCheck.addActionListener(this); viewerCheck.setSelected(externView); viewerField.setText(viewer); viewerLabel.setEnabled(externView); viewerField.setEnabled(externView); prefPanel.add(viewerLabel); prefPanel.add(viewerField); prefPanel.add(viewerCheck); // Preferences biosimrc = Preferences.userRoot(); // JPanel vhdlPrefs = new JPanel(); // JPanel lhpnPrefs = new JPanel(); // JTabbedPane prefTabsNoLema = new JTabbedPane(); // prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs); // prefTabsNoLema.addTab("LHPN Preferences", lhpnPrefs); Preferences biosimrc = Preferences.userRoot(); JCheckBox dialog = new JCheckBox("Use File Dialog"); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { dialog.setSelected(true); } else { dialog.setSelected(false); } prefPanel.add(dialog); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefPanel, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { viewer = viewerField.getText(); if (dialog.isSelected()) { biosimrc.put("biosim.general.file_browser", "FileDialog"); } else { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } } } } public void about() { final JFrame f = new JFrame("About"); // frame.setIconImage(new ImageIcon(ENVVAR + // File.separator // + "gui" // + File.separator + "icons" + File.separator + // "iBioSim.png").getImage()); JLabel name; JLabel version; final String developers; if (lema) { name = new JLabel("LEMA", JLabel.CENTER); version = new JLabel("Version 1.3", JLabel.CENTER); developers = "Satish Batchu\nKevin Jones\nScott Little\nCurtis Madsen\nChris Myers\nNicholas Seegmiller\n" + "Robert Thacker\nDavid Walter"; } else if (atacs) { name = new JLabel("ATACS", JLabel.CENTER); version = new JLabel("Version 6.3", JLabel.CENTER); developers = "Wendy Belluomini\nJeff Cuthbert\nHans Jacobson\nKevin Jones\nSung-Tae Jung\n" + "Christopher Krieger\nScott Little\nCurtis Madsen\nEric Mercer\nChris Myers\n" + "Curt Nelson\nEric Peskin\nNicholas Seegmiller\nDavid Walter\nHao Zheng"; } else { name = new JLabel("iBioSim", JLabel.CENTER); version = new JLabel("Version 1.3", JLabel.CENTER); developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen"; } Font font = name.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); name.setFont(font); JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER); JButton credits = new JButton("Credits"); credits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] options = { "Close" }; JOptionPane.showOptionDialog(f, developers, "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } }); JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(credits); buttons.add(close); JPanel aboutPanel = new JPanel(new BorderLayout()); JPanel uOfUPanel = new JPanel(new BorderLayout()); uOfUPanel.add(name, "North"); uOfUPanel.add(version, "Center"); uOfUPanel.add(uOfU, "South"); if (lema) { aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "LEMA.png")), "North"); } else if (atacs) { aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "ATACS.png")), "North"); } else { aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png")), "North"); } // aboutPanel.add(bioSim, "North"); aboutPanel.add(uOfUPanel, "Center"); aboutPanel.add(buttons, "South"); f.setContentPane(aboutPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } public void exit() { int autosave = 0; for (int i = 0; i < tab.getTabCount(); i++) { int save = save(i, autosave); if (save == 0) { return; } else if (save == 2) { autosave = 1; } else if (save == 3) { autosave = 2; } } Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < numberRecentProj; i++) { if (atacs) { biosimrc.put("atacs.recent.project." + i, recentProjects[i].getText()); biosimrc.put("atacs.recent.project.path." + i, recentProjectPaths[i]); } else if (lema) { biosimrc.put("lema.recent.project." + i, recentProjects[i].getText()); biosimrc.put("lema.recent.project.path." + i, recentProjectPaths[i]); } else { biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText()); biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]); } } System.exit(1); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == viewerCheck) { externView = viewerCheck.isSelected(); viewerLabel.setEnabled(viewerCheck.isSelected()); viewerField.setEnabled(viewerCheck.isSelected()); } if (e.getSource() == viewCircuit) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); } } else if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).viewLhpn(); } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Verification) { ((Verification) array[0]).viewCircuit(); } else if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewCircuit(); } } } else if (e.getSource() == viewLog) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { if (new File(root + separator + "atacs.log").exists()) { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame(), "No log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (comp instanceof Verification) { ((Verification) comp).viewLog(); } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewLog(); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewLog(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLog(); } } } else if (e.getSource() == viewCoverage) { Component comp = tab.getSelectedComponent(); if (treeSelected) { JOptionPane.showMessageDialog(frame(), "No Coverage report exists.", "Error", JOptionPane.ERROR_MESSAGE); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewCoverage(); } } } else if (e.getSource() == viewVHDL) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { String vhdFile = tree.getFile(); if (new File(vhdFile).exists()) { File vhdlAmsFile = new File(vhdFile); BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "VHDL-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view VHDL-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewVHDL(); } } } else if (e.getSource() == viewVerilog) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { String vamsFileName = tree.getFile(); if (new File(vamsFileName).exists()) { File vamsFile = new File(vamsFileName); BufferedReader input = new BufferedReader(new FileReader(vamsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "Verilog-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane .showMessageDialog(this.frame(), "Unable to view Verilog-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewVerilog(); } } } else if (e.getSource() == viewLHPN) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException e2) { e2.printStackTrace(); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); } } } else if (e.getSource() == saveParam) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).save(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); } else { ((Reb2Sac) ((JTabbedPane) comp).getComponentAt(2)).save(); } } } else if (e.getSource() == saveSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("SBML"); } else if (e.getSource() == saveTemp) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("template"); } else if (e.getSource() == saveAsGcm) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("GCM"); } else if (e.getSource() == saveGcmAsLhpn) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("LHPN"); } else if (e.getSource() == saveAsLhpn) { Component comp = tab.getSelectedComponent(); ((LHPNEditor) comp).save(); } else if (e.getSource() == saveAsGraph) { Component comp = tab.getSelectedComponent(); ((Graph) comp).save(); } else if (e.getSource() == saveAsSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML"); } else if (e.getSource() == saveAsTemplate) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML template"); } else if (e.getSource() == close && tab.getSelectedComponent() != null) { Component comp = tab.getSelectedComponent(); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), tab.getSelectedIndex()); } else if (e.getSource() == closeAll) { while (tab.getSelectedComponent() != null) { int index = tab.getSelectedIndex(); Component comp = tab.getComponent(index); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), index); } } else if (e.getSource() == viewRules) { Component comp = tab.getSelectedComponent(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).viewRules(); } else if (e.getSource() == viewTrace) { Component comp = tab.getSelectedComponent(); if (comp instanceof Verification) { ((Verification) comp).viewTrace(); } else if (comp instanceof Synthesis) { ((Synthesis) comp).viewTrace(); } } else if (e.getSource() == exportCsv) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(5); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5); } } else if (e.getSource() == exportDat) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(6); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(); } } else if (e.getSource() == exportEps) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(3); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3); } } else if (e.getSource() == exportJpg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(0); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0); } } else if (e.getSource() == exportPdf) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(2); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2); } } else if (e.getSource() == exportPng) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(1); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1); } } else if (e.getSource() == exportSvg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(4); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4); } } else if (e.getSource() == exportTsd) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(7); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7); } } else if (e.getSource() == about) { about(); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = ""; if (!async) { theFile = "iBioSim.html"; } else if (atacs) { theFile = "ATACS.html"; } else { theFile = "LEMA.html"; } String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { directory = ENVVAR + "/docs/"; command = "open "; } else { directory = ENVVAR + "\\docs\\"; command = "cmd /c start "; } File work = new File(directory); log.addText("Executing:\n" + command + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command + theFile, null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the exit menu item is selected else if (e.getSource() == exit) { exit(); } // if the open popup menu is selected on a sim directory else if (e.getActionCommand().equals("openSim")) { openSim(); } else if (e.getActionCommand().equals("openLearn")) { if (lema) { openLearnLHPN(); } else { openLearn(); } } else if (e.getActionCommand().equals("openSynth")) { openSynth(); } else if (e.getActionCommand().equals("openVerification")) { openVerify(); } // if the create simulation popup menu is selected on a dot file else if (e.getActionCommand().equals("createSim")) { try { simulate(true); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the simulate popup menu is selected on an sbml file else if (e.getActionCommand().equals("simulate")) { try { simulate(false); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the synthesis popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createSynthesis")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:", "Synthesis View ID", JOptionPane.PLAIN_MESSAGE); if (synthName != null && !synthName.trim().equals("")) { synthName = synthName.trim(); try { if (overwrite(root + separator + synthName, synthName)) { new File(root + separator + synthName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + synthName.trim() + ".syn")); out .write(("synthesis.file=" + circuitFileNoPath + "\n") .getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } try { FileInputStream in = new FileInputStream(new File(root + separator + circuitFileNoPath)); FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + circuitFileNoPath)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); String work = root + separator + synthName; String circuitFile = root + separator + synthName.trim() + separator + circuitFileNoPath; JPanel synthPane = new JPanel(); Synthesis synth = new Synthesis(work, circuitFile, log, this); // synth.addMouseListener(this); synthPane.add(synth); /* * JLabel noData = new JLabel("No data available"); * Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); * lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = * new JLabel("No data available"); font = * noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt * (lrnTab.getComponents().length - * 1).setName("TSD Graph"); */ addTab(synthName, synthPane, "Synthesis"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the verify popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createVerify")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:", "Verification View ID", JOptionPane.PLAIN_MESSAGE); if (verName != null && !verName.trim().equals("")) { verName = verName.trim(); // try { if (overwrite(root + separator + verName, verName)) { new File(root + separator + verName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + verName.trim() + ".ver")); out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } /* * try { FileInputStream in = new FileInputStream(new * File(root + separator + circuitFileNoPath)); * FileOutputStream out = new FileOutputStream(new * File(root + separator + verName.trim() + separator + * circuitFileNoPath)); int read = in.read(); while * (read != -1) { out.write(read); read = in.read(); } * in.close(); out.close(); } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy * circuit file!", "Error Saving File", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); // String work = root + separator + verName; // log.addText(circuitFile); // JTabbedPane verTab = new JTabbedPane(); // JPanel verPane = new JPanel(); Verification verify = new Verification(root + separator + verName, verName, circuitFileNoPath, log, this, lema, atacs); // verify.addMouseListener(this); verify.save(); // verPane.add(verify); // JPanel abstPane = new JPanel(); // AbstPane abst = new AbstPane(root + separator + // verName, verify, // circuitFileNoPath, log, this, lema, atacs); // abstPane.add(abst); // verTab.addTab("verify", verPane); // verTab.addTab("abstract", abstPane); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - * 1).setName("TSD Graph"); */ addTab(verName, verify, "Verification"); } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Verification View directory.", "Error", // JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the delete popup menu is selected else if (e.getActionCommand().contains("delete") || e.getSource() == delete) { if (!tree.getFile().equals(root)) { if (new File(tree.getFile()).isDirectory()) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } refreshTree(); } else { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); refreshTree(); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE); } } } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("createSBML")) { try { String theFile = ""; String filename = tree.getFile(); GCMFile gcm = new GCMFile(); gcm.load(filename); GCMParser parser = new GCMParser(filename); GeneticNetwork network = null; try { network = parser.buildNetwork(); } catch (IllegalStateException e1) { JOptionPane.showMessageDialog(frame, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return; } network.loadProperties(gcm); if (filename.lastIndexOf('/') >= 0) { theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { theFile = filename.substring(filename.lastIndexOf('\\') + 1); } if (new File(root + File.separator + theFile.replace(".gcm", "") + ".xml").exists()) { String[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "") + ".xml already exists. Overwrite file?", "Save file", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { network.mergeSBML(root + File.separator + theFile.replace(".gcm", "") + ".xml"); log.addText("Saving GCM file as SBML file:\n" + root + File.separator + theFile.replace(".gcm", "") + ".xml\n"); refreshTree(); updateOpenSBML(theFile.replace(".gcm", "") + ".xml"); } else { // Do nothing } } else { network.mergeSBML(root + File.separator + theFile.replace(".gcm", "") + ".xml"); log.addText("Saving GCM file as SBML file:\n" + root + File.separator + theFile.replace(".gcm", "") + ".xml\n"); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLHPN")) { try { String theFile = ""; String filename = tree.getFile(); GCMFile gcm = new GCMFile(); gcm.load(filename); if (filename.lastIndexOf('/') >= 0) { theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { theFile = filename.substring(filename.lastIndexOf('\\') + 1); } if (new File(root + File.separator + theFile.replace(".gcm", "") + ".lpn").exists()) { String[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "") + ".lpn already exists. Overwrite file?", "Save file", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { gcm.createLogicalModel(root + File.separator + theFile.replace(".gcm", "") + ".lpn", log, this, root, theFile.replace(".gcm", "") + ".lpn"); } else { // Do nothing } } else { gcm.createLogicalModel(root + File.separator + theFile.replace(".gcm", "") + ".lpn", log, this, root, theFile.replace(".gcm", "") + ".lpn"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create LHPN file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("dotEditor")) { try { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { File work = new File(directory); GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); JList empty = new JList(); run.createProperties(0, "Print Interval", 1, 1, 1, 1, tree.getFile() .substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split( separator).length - 1].length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile() .split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the browse popup menu is selected on an sbml file else if (e.getActionCommand().equals("browse")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); JList empty = new JList(); dummy.setSelected(false); run.createProperties(0, "Print Interval", 1, 1, 1, 1, tree.getFile() .substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split( separator).length - 1].length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile() .split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + tree.getFile() + "\n"); Runtime exec = Runtime.getRuntime(); Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); String error = ""; String output = ""; InputStream reb = browse.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = browse.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } browse.waitFor(); String command = ""; if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { command = "cmd /c start "; } log.addText("Executing:\n" + command + directory + out + ".xhtml\n"); exec.exec(command + out + ".xhtml", null, work); } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph dot popup menu is selected else if (e.getActionCommand().equals("graphDot")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the save button is pressed on the Tool Bar else if (e.getActionCommand().equals("save")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).save(); } else if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).save("Save GCM"); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(false, "", true); } else if (comp instanceof Graph) { ((Graph) comp).save(); } else if (comp instanceof Verification) { ((Verification) comp).save(); } else if (comp instanceof JTabbedPane) { for (Component component : ((JTabbedPane) comp).getComponents()) { int index = ((JTabbedPane) comp).getSelectedIndex(); if (component instanceof Graph) { ((Graph) component).save(); } else if (component instanceof Learn) { ((Learn) component).saveGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).saveLhpn(); } else if (component instanceof DataManager) { ((DataManager) component).saveChanges(((JTabbedPane) comp) .getTitleAt(index)); } else if (component instanceof SBML_Editor) { ((SBML_Editor) component).save(false, "", true); } else if (component instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) component).saveParams(false, ""); } else if (component instanceof Reb2Sac) { ((Reb2Sac) component).save(); } } } if (comp instanceof JPanel) { if (comp.getName().equals("Synthesis")) { // ((Synthesis) tab.getSelectedComponent()).save(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).save(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); try { File output = new File(root + separator + fileName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + fileName); this.updateAsyncViews(fileName); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the save as button is pressed on the Tool Bar else if (e.getActionCommand().equals("saveas")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter LHPN name:", "LHPN Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".lpn")) { newName = newName + ".lpn"; } ((LHPNEditor) comp).saveAs(newName); tab.setTitleAt(tab.getSelectedIndex(), newName); } else if (comp instanceof GCM2SBMLEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:", "GCM Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (newName.contains(".gcm")) { newName = newName.replace(".gcm", ""); } ((GCM2SBMLEditor) comp).saveAs(newName); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).saveAs(); } else if (comp instanceof Graph) { ((Graph) comp).saveAs(); } else if (comp instanceof Verification) { ((Verification) comp).saveAs(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).saveAs(); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Synthesis")) { Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).saveAs(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); String newName = ""; if (fileName.endsWith(".vhd")) { newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".vhd")) { newName = newName + ".vhd"; } } else if (fileName.endsWith(".g")) { newName = JOptionPane.showInputDialog(frame(), "Enter Petri net name:", "Petri net Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".g")) { newName = newName + ".g"; } } else if (fileName.endsWith(".csp")) { newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".csp")) { newName = newName + ".csp"; } } else if (fileName.endsWith(".hse")) { newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".hse")) { newName = newName + ".hse"; } } else if (fileName.endsWith(".unc")) { newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".unc")) { newName = newName + ".unc"; } } else if (fileName.endsWith(".rsg")) { newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".rsg")) { newName = newName + ".rsg"; } } try { File output = new File(root + separator + newName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + newName); File oldFile = new File(root + separator + fileName); oldFile.delete(); tab.setTitleAt(tab.getSelectedIndex(), newName); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the run button is selected on the tool bar else if (e.getActionCommand().equals("run")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); int index = -1; for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) { index = i; break; } } if (component instanceof Graph) { if (index != -1) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton() .doClick(); } else { ((Graph) component).save(); ((Graph) component).run(); } } else if (component instanceof Learn) { ((Learn) component).save(); new Thread((Learn) component).start(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); ((LearnLHPN) component).learn(); } else if (component instanceof SBML_Editor) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof Reb2Sac) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JPanel) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JScrollPane) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } } else if (comp instanceof Verification) { ((Verification) comp).save(); new Thread((Verification) comp).start(); } else if (comp instanceof Synthesis) { ((Synthesis) comp).save(); new Thread((Synthesis) comp).start(); } } else if (e.getActionCommand().equals("refresh")) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).refresh(); } } else if (comp instanceof Graph) { ((Graph) comp).refresh(); } } else if (e.getActionCommand().equals("check")) { Component comp = tab.getSelectedComponent(); if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(true, "", true); ((SBML_Editor) comp).check(); } } else if (e.getActionCommand().equals("export")) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).export(); } } } // if the new menu item is selected else if (e.getSource() == newProj) { int autosave = 0; for (int i = 0; i < tab.getTabCount(); i++) { int save = save(i, autosave); if (save == 0) { return; } else if (save == 2) { autosave = 1; } else if (save == 3) { autosave = 2; } } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.project_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.project_dir", "")); } String filename = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "New", -1); if (!filename.trim().equals("")) { filename = filename.trim(); biosimrc.put("biosim.general.project_dir", filename); File f = new File(filename); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return; } } new File(filename).mkdir(); try { if (lema) { new FileWriter(new File(filename + separator + "LEMA.prj")).close(); } else if (atacs) { new FileWriter(new File(filename + separator + "ATACS.prj")).close(); } else { new FileWriter(new File(filename + separator + "BioSim.prj")).close(); } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbml.setEnabled(true); importBioModel.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importLpn.setEnabled(true); importG.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newG.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } } // if the open project menu item is selected else if (e.getSource() == pref) { preferences(); } else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) { int autosave = 0; for (int i = 0; i < tab.getTabCount(); i++) { int save = save(i, autosave); if (save == 0) { return; } else if (save == 2) { autosave = 1; } else if (save == 3) { autosave = 2; } } Preferences biosimrc = Preferences.userRoot(); String projDir = ""; if (e.getSource() == openProj) { File file; if (biosimrc.get("biosim.general.project_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.project_dir", "")); } projDir = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "Open", -1); if (projDir.endsWith(".prj")) { biosimrc.put("biosim.general.project_dir", projDir); String[] tempArray = projDir.split(separator); projDir = ""; for (int i = 0; i < tempArray.length - 1; i++) { projDir = projDir + tempArray[i] + separator; } } } else if (e.getSource() == recentProjects[0]) { projDir = recentProjectPaths[0]; } else if (e.getSource() == recentProjects[1]) { projDir = recentProjectPaths[1]; } else if (e.getSource() == recentProjects[2]) { projDir = recentProjectPaths[2]; } else if (e.getSource() == recentProjects[3]) { projDir = recentProjectPaths[3]; } else if (e.getSource() == recentProjects[4]) { projDir = recentProjectPaths[4]; } // log.addText(projDir); if (!projDir.equals("")) { biosimrc.put("biosim.general.project_dir", projDir); if (new File(projDir).isDirectory()) { boolean isProject = false; for (String temp : new File(projDir).list()) { if (temp.equals(".prj")) { isProject = true; } if (lema && temp.equals("LEMA.prj")) { isProject = true; } else if (atacs && temp.equals("ATACS.prj")) { isProject = true; } else if (temp.equals("BioSim.prj")) { isProject = true; } } if (isProject) { root = projDir; refresh(); tab.removeAll(); addRecentProject(projDir); importDot.setEnabled(true); importSbml.setEnabled(true); importBioModel.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importLpn.setEnabled(true); importG.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newG.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new circuit model menu item is selected else if (e.getSource() == newCircuit) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 4).equals(".gcm")) { simName += ".gcm"; } } else { simName += ".gcm"; } String modelID = ""; if (simName.length() > 3) { if (simName.substring(simName.length() - 4).equals(".gcm")) { modelID = simName.substring(0, simName.length() - 4); } else { modelID = simName.substring(0, simName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); new GCMFile().save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f .getName(), this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(f.getName(), gcm, "GCM Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new SBML model menu item is selected else if (e.getSource() == newModel) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) { simName += ".xml"; } } else { simName += ".xml"; } String modelID = ""; if (simName.length() > 4) { if (simName.substring(simName.length() - 5).equals(".sbml")) { modelID = simName.substring(0, simName.length() - 5); } else { modelID = simName.substring(0, simName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { String f = new String(root + separator + simName); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(BioSim.SBML_LEVEL, BioSim.SBML_VERSION); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + simName); SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null); // sbml.addMouseListener(this); addTab(f.split(separator)[f.split(separator).length - 1], sbml, "SBML Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new vhdl menu item is selected else if (e.getSource() == newVhdl) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 4) { if (!vhdlName.substring(vhdlName.length() - 5).equals(".vhd")) { vhdlName += ".vhd"; } } else { vhdlName += ".vhd"; } String modelID = ""; if (vhdlName.length() > 3) { if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) { modelID = vhdlName.substring(0, vhdlName.length() - 4); } else { modelID = vhdlName.substring(0, vhdlName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + vhdlName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(vhdlName, scroll, "VHDL Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new petri net menu item is selected else if (e.getSource() == newG) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter Petri Net Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 42) { if (!vhdlName.substring(vhdlName.length() - 3).equals(".g")) { vhdlName += ".g"; } } else { vhdlName += ".g"; } String modelID = ""; if (vhdlName.length() > 1) { if (vhdlName.substring(vhdlName.length() - 2).equals(".g")) { modelID = vhdlName.substring(0, vhdlName.length() - 2); } else { modelID = vhdlName.substring(0, vhdlName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + vhdlName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(vhdlName, scroll, "Petri Net Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new lhpn menu item is selected else if (e.getSource() == newLhpn) { if (root != null) { try { String lhpnName = JOptionPane.showInputDialog(frame, "Enter LHPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 3) { if (!lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) { lhpnName += ".lpn"; } } else { lhpnName += ".lpn"; } String modelID = ""; if (lhpnName.length() > 3) { if (lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) { modelID = lhpnName.substring(0, lhpnName.length() - 4); } else { modelID = lhpnName.substring(0, lhpnName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { // if (overwrite(root + separator + lhpnName, // lhpnName)) { // File f = new File(root + separator + lhpnName); // f.delete(); // f.createNewFile(); // new LHPNFile(log).save(f.getAbsolutePath()); // int i = getTab(f.getName()); // if (i != -1) { // tab.remove(i); // addTab(f.getName(), new LHPNEditor(root + // separator, f.getName(), // null, this, log), "LHPN Editor"); // refreshTree(); if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.createNewFile(); new LHPNFile(log).save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(), null, this, log); // lhpn.addMouseListener(this); addTab(f.getName(), lhpn, "LHPN Editor"); refreshTree(); } // File f = new File(root + separator + lhpnName); // f.createNewFile(); // String[] command = { "emacs", f.getName() }; // Runtime.getRuntime().exec(command); // refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new csp menu item is selected else if (e.getSource() == newCsp) { if (root != null) { try { String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (cspName != null && !cspName.trim().equals("")) { cspName = cspName.trim(); if (cspName.length() > 3) { if (!cspName.substring(cspName.length() - 4).equals(".csp")) { cspName += ".csp"; } } else { cspName += ".csp"; } String modelID = ""; if (cspName.length() > 3) { if (cspName.substring(cspName.length() - 4).equals(".csp")) { modelID = cspName.substring(0, cspName.length() - 4); } else { modelID = cspName.substring(0, cspName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + cspName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + cspName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(cspName, scroll, "CSP Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new hse menu item is selected else if (e.getSource() == newHse) { if (root != null) { try { String hseName = JOptionPane.showInputDialog(frame, "Enter Handshaking Expansion Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (hseName != null && !hseName.trim().equals("")) { hseName = hseName.trim(); if (hseName.length() > 3) { if (!hseName.substring(hseName.length() - 4).equals(".hse")) { hseName += ".hse"; } } else { hseName += ".hse"; } String modelID = ""; if (hseName.length() > 3) { if (hseName.substring(hseName.length() - 4).equals(".hse")) { modelID = hseName.substring(0, hseName.length() - 4); } else { modelID = hseName.substring(0, hseName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + hseName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + hseName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(hseName, scroll, "HSE Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new unc menu item is selected else if (e.getSource() == newUnc) { if (root != null) { try { String uncName = JOptionPane.showInputDialog(frame, "Enter Extended Burst Mode Machine ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (uncName != null && !uncName.trim().equals("")) { uncName = uncName.trim(); if (uncName.length() > 3) { if (!uncName.substring(uncName.length() - 4).equals(".unc")) { uncName += ".unc"; } } else { uncName += ".unc"; } String modelID = ""; if (uncName.length() > 3) { if (uncName.substring(uncName.length() - 4).equals(".unc")) { modelID = uncName.substring(0, uncName.length() - 4); } else { modelID = uncName.substring(0, uncName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + uncName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + uncName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(uncName, scroll, "UNC Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newRsg) { if (root != null) { try { String rsgName = JOptionPane.showInputDialog(frame, "Enter Reduced State Graph Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (rsgName != null && !rsgName.trim().equals("")) { rsgName = rsgName.trim(); if (rsgName.length() > 3) { if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) { rsgName += ".rsg"; } } else { rsgName += ".rsg"; } String modelID = ""; if (rsgName.length() > 3) { if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) { modelID = rsgName.substring(0, rsgName.length() - 4); } else { modelID = rsgName.substring(0, rsgName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + rsgName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + rsgName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(rsgName, scroll, "RSG Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newSpice) { if (root != null) { try { String spiceName = JOptionPane.showInputDialog(frame, "Enter Spice Circuit ID:", "Circuit ID", JOptionPane.PLAIN_MESSAGE); if (spiceName != null && !spiceName.trim().equals("")) { spiceName = spiceName.trim(); if (spiceName.length() > 3) { if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) { spiceName += ".cir"; } } else { spiceName += ".cir"; } String modelID = ""; if (spiceName.length() > 3) { if (spiceName.substring(spiceName.length() - 4).equals(".cir")) { modelID = spiceName.substring(0, spiceName.length() - 4); } else { modelID = spiceName.substring(0, spiceName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + spiceName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + spiceName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(spiceName, scroll, "Spice Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1); if (!filename.trim().equals("")) { biosimrc.put("biosim.general.import_dir", filename.trim()); if (new File(filename.trim()).isDirectory()) { JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML files contain the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; for (String s : new File(filename.trim()).list()) { if (s.endsWith(".xml") || s.endsWith(".sbml")) { try { SBMLDocument document = readSBML(filename.trim() + separator + s); if (overwrite(root + separator + s, s)) { long numErrors = document.checkConsistency(); if (numErrors > 0) { display = true; messageArea .append(" messageArea.append(s); messageArea .append("\n for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } } SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + s); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } } refreshTree(); if (display) { final JFrame f = new JFrame("SBML Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } else { String[] file = filename.trim().split(separator); try { SBMLDocument document = readSBML(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea .append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } SBMLWriter writer = new SBMLWriter(); writer .writeSBML(document, root + separator + file[file.length - 1]); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importBioModel) { if (root != null) { String modelNumber = JOptionPane.showInputDialog(frame, "Enter BioModel Number:", "BioModel Number", JOptionPane.PLAIN_MESSAGE); String BMurl = "http: String filename = "BIOMD"; for (int i = 0; i < 10 - modelNumber.length(); i++) { filename += "0"; } filename += modelNumber + ".xml"; try { URL url = new URL(BMurl + filename); // System.out.println("Opening connection to " + BMurl + // filename + "..."); URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); // System.out.println("Copying resource (type: " + // urlC.getContentType() + ")..."); // System.out.flush(); FileOutputStream fos = null; fos = new FileOutputStream(root + separator + filename); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); // System.out.println(count + " byte(s) copied"); } catch (MalformedURLException e1) { JOptionPane.showMessageDialog(frame, e1.toString(), "Error", JOptionPane.ERROR_MESSAGE); filename = ""; } catch (IOException e1) { JOptionPane.showMessageDialog(frame, filename + " not found.", "Error", JOptionPane.ERROR_MESSAGE); filename = ""; } if (!filename.trim().equals("")) { String[] file = filename.trim().split(separator); try { SBMLDocument document = readSBML(root + separator + filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea .append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + file[file.length - 1]); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import dot menu item is selected else if (e.getSource() == importDot) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1); if (filename != null && !filename.trim().equals("")) { biosimrc.put("biosim.general.import_dir", filename.trim()); } if (new File(filename.trim()).isDirectory()) { for (String s : new File(filename.trim()).list()) { if (!(filename.trim() + separator + s).equals("") && (filename.trim() + separator + s).length() > 3 && (filename.trim() + separator + s).substring( (filename.trim() + separator + s).length() - 4, (filename.trim() + separator + s).length()).equals(".gcm")) { try { // GCMParser parser = new GCMParser((filename.trim() + separator + s)); if (overwrite(root + separator + s, s)) { FileOutputStream out = new FileOutputStream(new File(root + separator + s)); FileInputStream in = new FileInputStream(new File((filename .trim() + separator + s))); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { if (filename.trim().length() > 3 && !filename.trim().substring(filename.trim().length() - 4, filename.trim().length()).equals(".gcm")) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.trim().equals("")) { String[] file = filename.trim().split(separator); try { // GCMParser parser = new GCMParser(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename.trim())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import vhdl menu item is selected else if (e.getSource() == importVhdl) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import VHDL Model", -1); if (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals( ".vhd")) { JOptionPane.showMessageDialog(frame, "You must select a valid vhdl file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import lhpn menu item is selected else if (e.getSource() == importLhpn) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import LHPN", -1); if ((filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals(".g")) && (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals(".lpn"))) { // System.out.println(filename.substring(filename.length() - // 2, filename.length())); JOptionPane.showMessageDialog(frame, "You must select a valid lhpn file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { if (!filename.equals(root + separator + file[file.length - 1])) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } if (filename.substring(filename.length() - 2, filename.length()).equals( ".g")) { File work = new File(root); String oldName = root + separator + file[file.length - 1]; Process atacs = Runtime.getRuntime().exec("atacs -lgsl " + oldName, null, work); atacs.waitFor(); String lpnName = oldName.replace(".g", ".lpn"); String newName = oldName.replace(".g", "_NEW.lpn"); atacs = Runtime.getRuntime().exec("atacs -llsl " + lpnName, null, work); atacs.waitFor(); FileOutputStream out = new FileOutputStream(new File(lpnName)); FileInputStream in = new FileInputStream(new File(newName)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); new File(newName).delete(); } refreshTree(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importLpn) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import LPN", -1); if ((filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals(".g")) && (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals(".lpn"))) { JOptionPane.showMessageDialog(frame, "You must select a valid lhpn file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { if (new File(filename).exists()) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); // log.addText(filename); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } if (filename.substring(filename.length() - 2, filename.length()).equals( ".g")) { // log.addText(filename + file[file.length - 1]); File work = new File(root); String oldName = root + separator + file[file.length - 1]; // String newName = oldName.replace(".lpn", // "_NEW.g"); Process atacs = Runtime.getRuntime().exec("atacs -lgsl " + oldName, null, work); atacs.waitFor(); String lpnName = oldName.replace(".g", ".lpn"); String newName = oldName.replace(".g", "_NEW.lpn"); atacs = Runtime.getRuntime().exec("atacs -llsl " + lpnName, null, work); atacs.waitFor(); FileOutputStream out = new FileOutputStream(new File(lpnName)); FileInputStream in = new FileInputStream(new File(newName)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); new File(newName).delete(); } refreshTree(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importG) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import Net", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals( ".g")) { JOptionPane.showMessageDialog(frame, "You must select a valid Petri net file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import csp menu item is selected else if (e.getSource() == importCsp) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import CSP", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".csp")) { JOptionPane.showMessageDialog(frame, "You must select a valid csp file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import hse menu item is selected else if (e.getSource() == importHse) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import HSE", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".hse")) { JOptionPane.showMessageDialog(frame, "You must select a valid handshaking expansion file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import unc menu item is selected else if (e.getSource() == importUnc) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import UNC", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".unc")) { JOptionPane.showMessageDialog(frame, "You must select a valid expanded burst mode machine file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import rsg menu item is selected else if (e.getSource() == importRsg) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import RSG", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".rsg")) { JOptionPane.showMessageDialog(frame, "You must select a valid rsg file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import spice menu item is selected else if (e.getSource() == importSpice) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import Spice Circuit", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".cir")) { JOptionPane.showMessageDialog(frame, "You must select a valid spice circuit file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the Graph data menu item is clicked else if (e.getSource() == graph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "Number of molecules", graphName.trim() .substring(0, graphName.length() - 4), "tsd.printer", root, "Time", this, null, log, graphName.trim(), true, false); addTab(graphName.trim(), g, "TSD Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == probGraph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Probability Graph:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "Number of Molecules", graphName.trim() .substring(0, graphName.length() - 4), "tsd.printer", root, "Time", this, null, log, graphName.trim(), false, false); addTab(graphName.trim(), g, "Probability Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLearn")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE); if (lrnName != null && !lrnName.trim().equals("")) { lrnName = lrnName.trim(); // try { if (overwrite(root + separator + lrnName, lrnName)) { new File(root + separator + lrnName).mkdir(); // new FileWriter(new File(root + separator + // lrnName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; if (sbmlFileNoPath.endsWith(".vhd")) { try { File work = new File(root); Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null, work); sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".lpn"); log.addText("atacs -lvsl " + sbmlFileNoPath + "\n"); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to generate LHPN from VHDL file!", "Error Generating File", JOptionPane.ERROR_MESSAGE); } } try { FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn")); if (lema) { out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes()); } else { out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes()); } out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JTabbedPane lrnTab = new JTabbedPane(); DataManager data = new DataManager(root + separator + lrnName, this, lema); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Data Manager"); if (lema) { LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } else { Learn learn = new Learn(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } // learn.addMouseListener(this); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph; tsdGraph = new Graph(null, "Number of molecules", lrnName + " data", "tsd.printer", root + separator + lrnName, "Time", this, null, log, null, true, false); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "TSD Graph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - * 1).setName("TSD Graph"); */ addTab(lrnName, lrnTab, null); } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Learn View directory.", "Error", // JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("viewState")) { if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { LHPNFile lhpnFile = new LHPNFile(); lhpnFile.load(tree.getFile()); log.addText("Creating state graph."); StateGraph sg = new StateGraph(lhpnFile); sg.outputStateGraph(tree.getFile().replace(".lpn", ".dot"), false); String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; log.addText("Executing:\n" + command + root + separator + (file.replace(".lpn", ".dot")) + "\n"); Runtime exec = Runtime.getRuntime(); File work = new File(root); try { exec.exec(command + (file.replace(".lpn", ".dot")), null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("markov")) { if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { LHPNFile lhpnFile = new LHPNFile(); lhpnFile.load(tree.getFile()); log.addText("Creating state graph."); StateGraph sg = new StateGraph(lhpnFile); log.addText("Performing Markov Chain analysis."); sg.performMarkovianAnalysis(null); sg.outputStateGraph(tree.getFile().replace(".lpn", ".dot"), true); String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; log.addText("Executing:\n" + command + root + separator + (file.replace(".lpn", ".dot")) + "\n"); Runtime exec = Runtime.getRuntime(); File work = new File(root); try { exec.exec(command + (file.replace(".lpn", ".dot")), null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("viewModel")) { try { if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPlgodpe " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String vhdFile = tree.getFile(); if (new File(vhdFile).exists()) { File vhdlAmsFile = new File(vhdFile); BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "VHDL-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view VHDL-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } /* * String filename = * tree.getFile().split(separator)[tree.getFile().split( * separator).length - 1]; String cmd = "atacs -lvslllodpl " * + filename; File work = new File(root); Runtime exec = * Runtime.getRuntime(); Process view = exec.exec(cmd, null, * work); log.addText("Executing:\n" + cmd); String[] * findTheFile = filename.split("\\."); view.waitFor(); // * String directory = ""; String theFile = findTheFile[0] + * ".dot"; if (new File(root + separator + * theFile).exists()) { String command = ""; if * (System.getProperty("os.name").contentEquals("Linux")) { * // directory = ENVVAR + "/docs/"; command = * "gnome-open "; } else if * (System.getProperty("os.name").toLowerCase * ().startsWith("mac os")) { // directory = ENVVAR + * "/docs/"; command = "open "; } else { // directory = * ENVVAR + "\\docs\\"; command = "dotty start "; } * log.addText(command + root + theFile + "\n"); * exec.exec(command + theFile, null, work); } else { File * log = new File(root + separator + "atacs.log"); * BufferedReader input = new BufferedReader(new * FileReader(log)); String line = null; JTextArea * messageArea = new JTextArea(); while ((line = * input.readLine()) != null) { messageArea.append(line); * messageArea.append(System.getProperty("line.separator")); * } input.close(); messageArea.setLineWrap(true); * messageArea.setWrapStyleWord(true); * messageArea.setEditable(false); JScrollPane scrolls = new * JScrollPane(); scrolls.setMinimumSize(new Dimension(500, * 500)); scrolls.setPreferredSize(new Dimension(500, 500)); * scrolls.setViewportView(messageArea); * JOptionPane.showMessageDialog(frame(), scrolls, "Log", * JOptionPane.INFORMATION_MESSAGE); } */ } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { try { String vamsFileName = tree.getFile(); if (new File(vamsFileName).exists()) { File vamsFile = new File(vamsFileName); BufferedReader input = new BufferedReader(new FileReader(vamsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "Verilog-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view Verilog-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lcslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lhslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lxodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lsodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException e2) { e2.printStackTrace(); } } else if (e.getActionCommand().equals("copy") || e.getSource() == copy) { if (!tree.getFile().equals(root)) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String modelID = null; String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } try { if (!copy.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".sbml") && !copy.substring(copy.length() - 4).equals(".xml")) { copy += ".xml"; } } else { copy += ".xml"; } if (copy.length() > 4) { if (copy.substring(copy.length() - 5).equals(".sbml")) { modelID = copy.substring(0, copy.length() - 5); } else { modelID = copy.substring(0, copy.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".vhd")) { copy += ".vhd"; } } else { copy += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".g")) { copy += ".g"; } } else { copy += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".lpn")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".lpn")) { copy += ".lpn"; } } else { copy += ".lpn"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".csp")) { copy += ".csp"; } } else { copy += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".hse")) { copy += ".hse"; } } else { copy += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".unc")) { copy += ".unc"; } } else { copy += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".rsg")) { copy += ".rsg"; } } else { copy += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".grf")) { copy += ".grf"; } } else { copy += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".prb")) { copy += ".prb"; } } else { copy += ".prb"; } } } if (copy .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + copy, copy)) { if (modelID != null) { SBMLDocument document = readSBML(tree.getFile()); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy); } else if ((tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".lpn") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc") || tree.getFile().substring( tree.getFile().length() - 4).equals(".rsg")) || (tree.getFile().length() >= 2 && tree.getFile().substring( tree.getFile().length() - 2).equals(".g"))) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); FileInputStream in = new FileInputStream(new File(tree.getFile())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { new File(root + separator + copy).mkdir(); // new FileWriter(new File(root + separator + // copy + // separator + // ".sim")).close(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLDocument document = readSBML(tree.getFile() + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy + separator + ss); } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss .substring(ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } else { new File(root + separator + copy).mkdir(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss .substring(ss.length() - 4).equals(".lrn"))) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".lrn")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } } refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("rename") || e.getSource() == rename) { if (!tree.getFile().equals(root)) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String modelID = null; String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".sbml") && !rename.substring(rename.length() - 4).equals(".xml")) { rename += ".xml"; } } else { rename += ".xml"; } if (rename.length() > 4) { if (rename.substring(rename.length() - 5).equals(".sbml")) { modelID = rename.substring(0, rename.length() - 5); } else { modelID = rename.substring(0, rename.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".gcm")) { rename += ".gcm"; } } else { rename += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".vhd")) { rename += ".vhd"; } } else { rename += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".g")) { rename += ".g"; } } else { rename += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".lpn")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".lpn")) { rename += ".lpn"; } } else { rename += ".lpn"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".csp")) { rename += ".csp"; } } else { rename += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".hse")) { rename += ".hse"; } } else { rename += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".unc")) { rename += ".unc"; } } else { rename += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".rsg")) { rename += ".rsg"; } } else { rename += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".grf")) { rename += ".grf"; } } else { rename += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".prb")) { rename += ".prb"; } } else { rename += ".prb"; } } if (rename.equals(tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + rename, rename)) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".xml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".gcm") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".lpn") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".vhd") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".csp") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".hse") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".unc") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".rsg")) { String oldName = tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]; reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (modelID != null) { SBMLDocument document = readSBML(root + separator + rename); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + rename); } if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".lpn") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".vhd") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".csp") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".hse") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".unc") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".rsg")) { updateAsyncViews(rename); } if (new File(root + separator + rename).isDirectory()) { if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } else if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn") .renameTo(new File(root + separator + rename + separator + rename + ".lrn")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".ver").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".ver") .renameTo(new File(root + separator + rename + separator + rename + ".ver")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf") .renameTo(new File(root + separator + rename + separator + rename + ".grf")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb") .renameTo(new File(root + separator + rename + separator + rename + ".prb")); } } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { if (tree.getFile().length() > 4 && tree.getFile() .substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".xml")) { ((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID); ((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && (tree.getFile().substring( tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring( tree.getFile().length() - 4).equals( ".prb"))) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".lpn")) { ((LHPNEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); tab.setTitleAt(i, rename); } else if (tab.getComponentAt(i) instanceof JTabbedPane) { JTabbedPane t = new JTabbedPane(); int selected = ((JTabbedPane) tab.getComponentAt(i)) .getSelectedIndex(); boolean analysis = false; ArrayList<Component> comps = new ArrayList<Component>(); for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)) .getTabCount(); j++) { Component c = ((JTabbedPane) tab.getComponentAt(i)) .getComponent(j); comps.add(c); } for (Component c : comps) { if (c instanceof Reb2Sac) { ((Reb2Sac) c).setSim(rename); analysis = true; } else if (c instanceof SBML_Editor) { String properties = root + separator + rename + separator + rename + ".sim"; new File(properties).renameTo(new File(properties .replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) c).isDirty(); ((SBML_Editor) c).setParamFileAndSimDir(properties, root + separator + rename); ((SBML_Editor) c).save(false, "", true); ((SBML_Editor) c).updateSBML(i, 0); ((SBML_Editor) c).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")) .renameTo(new File(properties)); } else if (c instanceof Graph) { // c.addMouseListener(this); Graph g = ((Graph) c); g.setDirectory(root + separator + rename); if (g.isTSDGraph()) { g.setGraphName(rename + ".grf"); } else { g.setGraphName(rename + ".prb"); } } else if (c instanceof Learn) { Learn l = ((Learn) c); l.setDirectory(root + separator + rename); } else if (c instanceof DataManager) { DataManager d = ((DataManager) c); d.setDirectory(root + separator + rename); } if (analysis) { if (c instanceof Reb2Sac) { t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1) .setName("Simulate"); } else if (c instanceof SBML_Editor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("SBML Editor"); } else if (c instanceof GCM2SBMLEditor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("GCM Editor"); } else if (c instanceof Graph) { if (((Graph) c).isTSDGraph()) { t.addTab("TSD Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("TSD Graph"); } else { t.addTab("Probability Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("ProbGraph"); } } else { t.addTab("Abstraction Options", c); t.getComponentAt(t.getComponents().length - 1) .setName(""); } } } if (analysis) { t.setSelectedIndex(selected); tab.setComponentAt(i, t); } tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } else { tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } } } refreshTree(); // updateAsyncViews(rename); updateViewNames(tree.getFile(), rename); } } } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("openGraph")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .contains(".grf")) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Number of molecules", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile().split( separator)[tree.getFile().split(separator).length - 1], true, false), "TSD Graph"); } else { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Percent", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile().split(separator)[tree .getFile().split(separator).length - 1], false, false), "Probability Graph"); } } } } public int getTab(String name) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { return i; } } return -1; } public void deleteDir(File dir) { int count = 0; do { File[] list = dir.listFiles(); System.gc(); for (int i = 0; i < list.length; i++) { if (list[i].isDirectory()) { deleteDir(list[i]); } else { list[i].delete(); } } count++; } while (!dir.delete() && count != 100); if (count == 100) { JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method adds a new project to recent list */ public void addRecentProject(String projDir) { // boolean newOne = true; for (int i = 0; i < numberRecentProj; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = 0; j <= i; j++) { String save = recentProjectPaths[j]; recentProjects[j] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } recentProjectPaths[j] = projDir; projDir = save; } for (int j = i + 1; j < numberRecentProj; j++) { if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } } return; } } if (numberRecentProj < 5) { numberRecentProj++; } for (int i = 0; i < numberRecentProj; i++) { String save = recentProjectPaths[i]; recentProjects[i] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[i]); } recentProjectPaths[i] = projDir; projDir = save; } } /** * This method refreshes the menu. */ public void refresh() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema, atacs); mainPanel.add(tree, "West"); mainPanel.validate(); } /** * This method refreshes the tree. */ public void refreshTree() { tree.fixTree(); mainPanel.validate(); updateGCM(); } /** * This method adds the given Component to a tab. */ public void addTab(String name, Component panel, String tabName) { tab.addTab(name, panel); // panel.addMouseListener(this); if (tabName != null) { tab.getComponentAt(tab.getTabCount() - 1).setName(tabName); } else { tab.getComponentAt(tab.getTabCount() - 1).setName(name); } tab.setSelectedIndex(tab.getTabCount() - 1); } /** * This method removes the given component from the tabs. */ public void removeTab(Component component) { tab.remove(component); } public JTabbedPane getTab() { return tab; } /** * Prompts the user to save work that has been done. */ public int save(int index, int autosave) { if (tab.getComponentAt(index).getName().contains(("GCM")) || tab.getComponentAt(index).getName().contains("LHPN")) { if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) { GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index); if (editor.isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { editor.save("gcm"); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { editor.save("gcm"); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { editor.save("gcm"); return 2; } else { return 3; } } } else if (tab.getComponentAt(index) instanceof LHPNEditor) { LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index); if (editor.isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { editor.save(); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { editor.save(); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { editor.save(); return 2; } else { return 3; } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } else if (tab.getComponentAt(index).getName().equals("SBML Editor")) { if (tab.getComponentAt(index) instanceof SBML_Editor) { if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 2; } else { return 3; } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } else if (tab.getComponentAt(index).getName().contains("Graph")) { if (tab.getComponentAt(index) instanceof Graph) { if (((Graph) tab.getComponentAt(index)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { ((Graph) tab.getComponentAt(index)).save(); return 2; } else { return 3; } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } else { if (tab.getComponentAt(index) instanceof JTabbedPane) { for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() != null) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() .equals("Simulate")) { if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save simulation option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("SBML Editor")) { if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("GCM Editor")) { if (((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveParams(false, ""); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveParams(false, ""); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveParams(false, ""); } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { if (((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } } } if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) { if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)) .save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)) .save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("Data Manager")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) { ((DataManager) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveChanges(tab.getTitleAt(index)); } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().contains("Graph")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { if (((Graph) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save graph changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)); g.save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)); g.save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)); g.save(); } } } } } } } } else if (tab.getComponentAt(index) instanceof JPanel) { if ((tab.getComponentAt(index)).getName().equals("Synthesis")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Synthesis) { if (((Synthesis) array[0]).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save synthesis option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } } } } } else if (tab.getComponentAt(index).getName().equals("Verification")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Verification) { if (((Verification) array[0]).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save verification option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((Verification) array[0]).save(); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((Verification) array[0]).save(); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((Verification) array[0]).save(); } } } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } } /** * Saves a circuit from a learn view to the project view */ public void saveGcm(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Saves a circuit from a learn view to the project view */ public void saveLhpn(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + filename)); BufferedReader in = new BufferedReader(new FileReader(path)); String str; while ((str = in.readLine()) != null) { out.write(str + "\n"); } in.close(); out.close(); out = new BufferedWriter(new FileWriter(root + separator + filename.replace(".lpn", ".vhd"))); in = new BufferedReader(new FileReader(path.replace(".lpn", ".vhd"))); while ((str = in.readLine()) != null) { out.write(str + "\n"); } in.close(); out.close(); out = new BufferedWriter(new FileWriter(root + separator + filename.replace(".lpn", ".vams"))); in = new BufferedReader(new FileReader(path.replace(".lpn", ".vams"))); while ((str = in.readLine()) != null) { out.write(str + "\n"); } in.close(); out.close(); out = new BufferedWriter(new FileWriter(root + separator + filename.replace(".lpn", "_top.vams"))); String[] learnPath = path.split(separator); String topVFile = path.replace(learnPath[learnPath.length - 1], "top.vams"); String[] cktPath = filename.split(separator); in = new BufferedReader(new FileReader(topVFile)); while ((str = in.readLine()) != null) { str = str.replace("module top", "module " + cktPath[cktPath.length - 1].replace(".lpn", "_top")); out.write(str + "\n"); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save LHPN.", "Error", JOptionPane.ERROR_MESSAGE); } } public void updateMenu(boolean logEnabled, boolean othersEnabled) { viewVHDL.setEnabled(othersEnabled); viewVerilog.setEnabled(othersEnabled); viewLHPN.setEnabled(othersEnabled); viewCoverage.setEnabled(othersEnabled); save.setEnabled(othersEnabled); viewLog.setEnabled(logEnabled); // Do saveas & save button too } /** * Returns the frame. */ public JFrame frame() { return frame; } public void mousePressed(MouseEvent e) { // log.addText(e.getSource().toString()); if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } } else { if (e.isPopupTrigger() && tree.getFile() != null) { frame.getGlassPane().setVisible(false); popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.addMouseListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.addMouseListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.addMouseListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.addMouseListener(this); createSBML.setActionCommand("createSBML"); JMenuItem createLHPN = new JMenuItem("Create LHPN File"); createLHPN.addActionListener(this); createLHPN.addMouseListener(this); createLHPN.setActionCommand("createLHPN"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.add(createLHPN); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (lema) { popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); // if (lema) { // popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem viewStateGraph = new JMenuItem("View State Graph"); viewStateGraph.addActionListener(this); viewStateGraph.addMouseListener(this); viewStateGraph.setActionCommand("viewState"); JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis"); markovAnalysis.addActionListener(this); markovAnalysis.addMouseListener(this); markovAnalysis.setActionCommand("markov"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } if (atacs || lema) { popup.add(createVerification); popup.addSeparator(); } popup.add(viewModel); popup.add(viewStateGraph); popup.add(markovAnalysis); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (tree.getFile() != null) { int index = tab.getSelectedIndex(); enableTabMenu(index); if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this, null, null); // sbml.addMouseListener(this); addTab(tree.getFile().split(separator)[tree.getFile().split( separator).length - 1], sbml, "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "VHDL Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".vams")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "VHDL Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this Verilog-AMS file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Petri Net Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this .g file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } LHPNFile lhpn = new LHPNFile(log); if (new File(directory + theFile).length() > 0) { // log.addText("here"); lhpn.load(directory + theFile); // log.addText("there"); } // log.addText("load completed"); File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { // log.addText("make Editor"); LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile, lhpn, this, log); // editor.addMouseListener(this); addTab(theFile, editor, "LHPN Editor"); // log.addText("Editor made"); } // String[] cmd = { "emacs", filename }; // Runtime.getRuntime().exec(cmd); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to view this LHPN file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "CSP Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this csp file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "HSE Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this hse file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "UNC Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this unc file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "RSG Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Spice Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this spice file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Number of molecules", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile() .split(separator)[tree.getFile().split( separator).length - 1], true, false), "TSD Graph"); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Percent", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile() .split(separator)[tree.getFile().split( separator).length - 1], false, false), "Probability Graph"); } } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } if (sim) { openSim(); } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else { if (lema) { openLearnLHPN(); } else { openLearn(); } } } } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities .convertPoint(glassPane, glassPanePoint, container); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); if (e != null) { deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e .getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e .getClickCount(), e.isPopupTrigger())); } if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); } } catch (Exception e1) { e1.printStackTrace(); } } } else { if (tree.getFile() != null) { if (e.isPopupTrigger() && tree.getFile() != null) { frame.getGlassPane().setVisible(false); popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.addMouseListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.addMouseListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.addMouseListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.addMouseListener(this); createSBML.setActionCommand("createSBML"); JMenuItem createLHPN = new JMenuItem("Create LHPN File"); createLHPN.addActionListener(this); createLHPN.addMouseListener(this); createLHPN.setActionCommand("createLHPN"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.add(createLHPN); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); // if (lema) { // popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem viewStateGraph = new JMenuItem("View State Graph"); viewStateGraph.addActionListener(this); viewStateGraph.addMouseListener(this); viewStateGraph.setActionCommand("viewState"); JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis"); markovAnalysis.addActionListener(this); markovAnalysis.addMouseListener(this); markovAnalysis.setActionCommand("markov"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } if (atacs || lema) { popup.add(createVerification); popup.addSeparator(); } popup.add(viewModel); popup.add(viewStateGraph); popup.add(markovAnalysis); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (!popup.isVisible()) { frame.getGlassPane().setVisible(true); } } } } public void mouseMoved(MouseEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } } public void mouseWheelMoved(MouseWheelEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); } } public void windowGainedFocus(WindowEvent e) { setGlassPane(true); } private void simulate(boolean isDot) throws Exception { if (isDot) { String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String[] dot = tree.getFile().split(separator); String sbmlFile = /* * root + separator + simName + separator + */(dot[dot.length - 1].substring(0, dot[dot.length - 1] .length() - 3) + "sbml"); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + simName + separator + sbmlFile); try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + separator + (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(), log, simTab, null, dot[dot.length - 1]); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); // abstraction.addMouseListener(this); simTab.addTab("Abstraction Options", abstraction); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (dot[dot.length - 1].contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, dot[dot.length - 1], this, log, true, simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); if (!gcm.getSBMLFile().equals("--none SBML_Editor sbml = new SBML_Editor( root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); simTab.addTab("SBML Elements", scroll); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(null); } } else { SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } else { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } SBMLDocument document = readSBML(tree.getFile()); String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String sbmlFile = tree.getFile(); String[] sbml1 = tree.getFile().split(separator); String sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((sbml1[sbml1.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } new FileOutputStream(new File(sbmlFileProp)).close(); /* * try { FileOutputStream out = new FileOutputStream(new * File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); * String doc = writer.writeToString(document); byte[] * output = doc.getBytes(); out.write(output); out.close(); * } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy sbml * file to output location.", "Error", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName .trim(), log, simTab, null, sbml1[sbml1.length - 1]); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); // abstraction.addMouseListener(this); simTab.addTab("Abstraction Options", abstraction); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (sbml1[sbml1.length - 1].contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, sbml1[sbml1.length - 1], this, log, true, simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); if (!gcm.getSBMLFile().equals("--none SBML_Editor sbml = new SBML_Editor( root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); simTab.addTab("SBML Elements", scroll); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(null); } } else { SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } } private void openLearn() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); Learn learn = new Learn(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "Number of molecules", tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "Time", this, open, log, null, true, true); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openLearnLHPN() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "Number of molecules", tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "Time", this, open, log, null, true, true); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openSynth() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel synthPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String synthFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn"; String synthFile2 = tree.getFile() + separator + ".syn"; Properties load = new Properties(); String synthesisFile = ""; try { if (new File(synthFile2).exists()) { FileInputStream in = new FileInputStream(new File(synthFile2)); load.load(in); in.close(); new File(synthFile2).delete(); } if (new File(synthFile).exists()) { FileInputStream in = new FileInputStream(new File(synthFile)); load.load(in); in.close(); if (load.containsKey("synthesis.file")) { synthesisFile = load.getProperty("synthesis.file"); synthesisFile = synthesisFile.split(separator)[synthesisFile .split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(synthesisFile)); load.store(out, synthesisFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(synthesisFile)) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } if (!(new File(root + separator + synthesisFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this); // synth.addMouseListener(this); synthPanel.add(synth); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], synthPanel, "Synthesis"); } } private void openVerify() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { // JPanel verPanel = new JPanel(); // JPanel abstPanel = new JPanel(); // JPanel verTab = new JTabbedPane(); // String graphFile = ""; /* * if (new File(tree.getFile()).isDirectory()) { String[] list = new * File(tree.getFile()).list(); int run = 0; for (int i = 0; i < * list.length; i++) { if (!(new File(list[i]).isDirectory()) && * list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; * j++) { end = list[i].charAt(list[i].length() - j) + end; } if * (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) * { if (list[i].contains("run-")) { int tempNum = * Integer.parseInt(list[i].substring(4, list[i] .length() - * end.length())); if (tempNum > run) { run = tempNum; // graphFile * = tree.getFile() + separator + // list[i]; } } } } } } */ String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String verFile = tree.getFile() + separator + verName + ".ver"; Properties load = new Properties(); String verifyFile = ""; try { if (new File(verFile).exists()) { FileInputStream in = new FileInputStream(new File(verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1]; } } // FileOutputStream out = new FileOutputStream(new // File(verifyFile)); // load.store(out, verifyFile); // out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(verifyFile)) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } if (!(new File(verFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Verification ver = new Verification(root + separator + verName, verName, "flag", log, this, lema, atacs); // ver.addMouseListener(this); // verPanel.add(ver); // AbstPane abst = new AbstPane(root + separator + verName, ver, // "flag", log, this, lema, // atacs); // abstPanel.add(abst); // verTab.add("verify", verPanel); // verTab.add("abstract", abstPanel); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], ver, "Verification"); } } private void openSim() { String filename = tree.getFile(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( filename.split(separator)[filename.split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (filename != null && !filename.equals("")) { if (new File(filename).isDirectory()) { if (new File(filename + separator + ".sim").exists()) { new File(filename + separator + ".sim").delete(); } String[] list = new File(filename).list(); String getAFile = ""; // String probFile = ""; String openFile = ""; // String graphFile = ""; String open = null; String openProb = null; int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals("sbml")) { getAFile = filename + separator + list[i]; } else if (end.equals(".xml") && getAFile.equals("")) { getAFile = filename + separator + list[i]; } else if (end.equals(".txt") && list[i].contains("sim-rep")) { // probFile = filename + separator + list[i]; } else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) { openFile = filename + separator + list[i]; } else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = filename + separator + // list[i]; } } else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) { // graphFile = filename + separator + // list[i]; } else if (end.contains("=")) { // graphFile = filename + separator + // list[i]; } } else if (end.equals(".grf")) { open = filename + separator + list[i]; } else if (end.equals(".prb")) { openProb = filename + separator + list[i]; } } else if (new File(filename + separator + list[i]).isDirectory()) { String[] s = new File(filename + separator + list[i]).list(); for (int j = 0; j < s.length; j++) { if (s[j].contains("sim-rep")) { // probFile = filename + separator + list[i] // + separator + } else if (s[j].contains(".tsd")) { // graphFile = filename + separator + // list[i] + separator + } } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"; String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; if (new File(pmsFile).exists()) { if (new File(simFile).exists()) { new File(pmsFile).delete(); } else { new File(pmsFile).renameTo(new File(simFile)); } } String sbmlLoadFile = ""; String gcmFile = ""; if (new File(simFile).exists()) { try { Scanner s = new Scanner(new File(simFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; if (sbmlLoadFile.equals("")) { JOptionPane .showMessageDialog( frame, "Unable to open view because " + "the sbml linked to this view is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!(new File(root + separator + sbmlLoadFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (s.hasNextLine()) { s.nextLine(); } s.close(); File f = new File(sbmlLoadFile); if (!f.exists()) { sbmlLoadFile = root + separator + f.getName(); } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else { sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1]; if (!new File(sbmlLoadFile).exists()) { sbmlLoadFile = getAFile; /* * JOptionPane.showMessageDialog(frame, "Unable * to load sbml file.", "Error", * JOptionPane.ERROR_MESSAGE); return; */ } } if (!new File(sbmlLoadFile).exists()) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1] + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1) .setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); if (!gcm.getSBMLFile().equals("--none SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1) .setName(""); gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); simTab.addTab("SBML Elements", scroll); simTab.getComponentAt(simTab.getComponents().length - 1) .setName(""); gcm.setSBMLParamFile(null); } } else { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } // if (open != null) { Graph tsdGraph = reb2sac.createGraph(open); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "TSD Graph"); /* * } else if (!graphFile.equals("")) { * simTab.addTab("TSD Graph", * reb2sac.createGraph(open)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } / else { JLabel noData = * new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } */ // if (openProb != null) { Graph probGraph = reb2sac.createProbGraph(openProb); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "ProbGraph"); /* * } else if (!probFile.equals("")) { * simTab.addTab("Probability Graph", * reb2sac.createProbGraph(openProb)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } else { JLabel noData1 = * new JLabel("No data available"); Font font1 = * noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } private class NewAction extends AbstractAction { NewAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(newProj); if (!async) { popup.add(newCircuit); popup.add(newModel); } else if (atacs) { popup.add(newVhdl); popup.add(newLhpn); popup.add(newCsp); popup.add(newHse); popup.add(newUnc); popup.add(newRsg); } else { popup.add(newVhdl); popup.add(newLhpn); popup.add(newSpice); } popup.add(graph); popup.add(probGraph); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class SaveAction extends AbstractAction { SaveAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(saveAsGcm); } else { popup.add(saveAsLhpn); } popup.add(saveAsGraph); if (!lema) { popup.add(saveAsSbml); popup.add(saveAsTemplate); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ImportAction extends AbstractAction { ImportAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(importDot); popup.add(importSbml); popup.add(importBioModel); } else if (atacs) { popup.add(importVhdl); popup.add(importLhpn); popup.add(importCsp); popup.add(importHse); popup.add(importUnc); popup.add(importRsg); } else { popup.add(importVhdl); popup.add(importLhpn); popup.add(importSpice); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ExportAction extends AbstractAction { ExportAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(exportCsv); popup.add(exportDat); popup.add(exportEps); popup.add(exportJpg); popup.add(exportPdf); popup.add(exportPng); popup.add(exportSvg); popup.add(exportTsd); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ModelAction extends AbstractAction { ModelAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(viewModGraph); popup.add(viewModBrowser); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } public void mouseClicked(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); } } } } public void mouseEntered(MouseEvent e) { if (e.getSource() == tree.tree) { setGlassPane(false); } else if (e.getSource() == popup) { popupFlag = true; setGlassPane(false); } else if (e.getSource() instanceof JMenuItem) { menuFlag = true; setGlassPane(false); } } public void mouseExited(MouseEvent e) { if (e.getSource() == tree.tree && !popupFlag && !menuFlag) { setGlassPane(true); } else if (e.getSource() == popup) { popupFlag = false; if (!menuFlag) { setGlassPane(true); } } else if (e.getSource() instanceof JMenuItem) { menuFlag = false; if (!popupFlag) { setGlassPane(true); } } } public void mouseDragged(MouseEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } catch (Exception e1) { } } } // public void componentHidden(ComponentEvent e) { // log.addText("hidden"); // setGlassPane(true); // public void componentResized(ComponentEvent e) { // log.addText("resized"); // public void componentMoved(ComponentEvent e) { // log.addText("moved"); // public void componentShown(ComponentEvent e) { // log.addText("shown"); public void windowLostFocus(WindowEvent e) { } // public void focusGained(FocusEvent e) { // public void focusLost(FocusEvent e) { // log.addText("focus lost"); public JMenuItem getExitButton() { return exit; } /** * This is the main method. It excecutes the BioSim GUI FrontEnd program. */ public static void main(String args[]) { boolean lemaFlag = false, atacsFlag = false; if (args.length > 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-lema")) { lemaFlag = true; } else if (args[i].equals("-atacs")) { atacsFlag = true; } } } if (!lemaFlag && !atacsFlag) { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the // classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname + " environment variable does not include\nthe" + " directory containing the libsbml library file."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment" + " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file."); System.exit(1); } catch (SecurityException e) { System.err.println("Could not load the libSBML library files due to a" + " security exception."); System.exit(1); } } new BioSim(lemaFlag, atacsFlag); } public void copySim(String newSim) { try { new File(root + separator + newSim).mkdir(); // new FileWriter(new File(root + separator + newSim + separator + // ".sim")).close(); String oldSim = tab.getTitleAt(tab.getSelectedIndex()); String[] s = new File(root + separator + oldSim).list(); String sbmlFile = ""; String propertiesFile = ""; String sbmlLoadFile = null; String gcmFile = null; for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLDocument document = readSBML(root + separator + oldSim + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + newSim + separator + ss); sbmlFile = root + separator + newSim + separator + ss; } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); propertiesFile = root + separator + newSim + separator + ss; } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring( ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else { out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); } FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); if (ss.substring(ss.length() - 4).equals(".pms")) { if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) { new File(root + separator + newSim + separator + ss).delete(); } else { new File(root + separator + newSim + separator + ss).renameTo(new File( root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim")); } ss = ss.substring(0, ss.length() - 4) + ".sim"; } if (ss.substring(ss.length() - 4).equals(".sim")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (scan.hasNextLine()) { scan.nextLine(); } scan.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile, gcmFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, newSim, root + separator + newSim + separator + newSim + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor"); if (!gcm.getSBMLFile().equals("--none SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); simTab.addTab("SBML Elements", scroll); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(null); } } else { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ tab.setComponentAt(tab.getSelectedIndex(), simTab); tab.setTitleAt(tab.getSelectedIndex(), newSim); tab.getComponentAt(tab.getSelectedIndex()).setName(newSim); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } public void refreshLearn(String learnName, boolean data) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnName)) { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals( "TSD Graph")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) { ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)) .refresh(); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null, "Number of molecules", learnName + " data", "tsd.printer", root + separator + learnName, "Time", this, null, log, null, true, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName( "TSD Graph"); } /* * } else { JLabel noData1 = new * JLabel("No data available"); Font font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData1); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("TSD Graph"); } */ } else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) { } else { if (lema) { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnLHPN(root + separator + learnName, log, this)); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn( root + separator + learnName, log, this)); } ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) .setName("Learn"); } /* * } else { JLabel noData = new * JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("Learn"); } */ } } } } } private void updateGCM() { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles(); tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename()); } } } public void updateAsyncViews(String updatedFile) { // log.addText(updatedFile); for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".ver"; String properties1 = root + separator + tab + separator + tab + ".synth"; String properties2 = root + separator + tab + separator + tab + ".lrn"; // log.addText(properties + "\n" + properties1 + "\n" + properties2 if (new File(properties).exists()) { // String check = ""; // try { // Scanner s = new Scanner(new File(properties)); // if (s.hasNextLine()) { // check = s.nextLine(); // check = check.split(separator)[check.split(separator).length // s.close(); // catch (Exception e) { // if (check.equals(updatedFile)) { Verification verify = ((Verification) (this.tab.getComponentAt(i))); verify.reload(updatedFile); } if (new File(properties1).exists()) { // String check = ""; // try { // Scanner s = new Scanner(new File(properties1)); // if (s.hasNextLine()) { // check = s.nextLine(); // check = check.split(separator)[check.split(separator).length // s.close(); // catch (Exception e) { // if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("Synthesis")) { // new File(properties).renameTo(new // File(properties.replace(".synth", // ".temp"))); // boolean dirty = ((SBML_Editor) // (sim.getComponentAt(j))).isDirty(); ((Synthesis) (sim.getComponentAt(j))).reload(updatedFile); // if (updatedFile.contains(".g")) { // GCMParser parser = new GCMParser(root + separator + // updatedFile); // GeneticNetwork network = parser.buildNetwork(); // GeneticNetwork.setRoot(root + File.separator); // network.mergeSBML(root + separator + tab + separator // + updatedFile.replace(".g", ".vhd")); // ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, // j, root // + separator + tab + separator // + updatedFile.replace(".g", ".vhd")); // else { // ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, // j, root // + separator + updatedFile); // ((SBML_Editor) // (sim.getComponentAt(j))).setDirty(dirty); // new File(properties).delete(); // new File(properties.replace(".synth", // ".temp")).renameTo(new // File( // properties)); // sim.setComponentAt(j + 1, ((SBML_Editor) // (sim.getComponentAt(j))) // .getElementsPanel()); // sim.getComponentAt(j + 1).setName(""); } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((LearnLHPN) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); ((LearnLHPN) (learn.getComponentAt(j))).reload(updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } } } public void updateViews(String updatedFile) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".sim"; String properties2 = root + separator + tab + separator + tab + ".lrn"; if (new File(properties).exists()) { String check = ""; try { Scanner s = new Scanner(new File(properties)); if (s.hasNextLine()) { check = s.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } s.close(); } catch (Exception e) { } if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("SBML Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty(); ((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true); if (updatedFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + updatedFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); } else { ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile); } ((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File( properties)); sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j))) .getElementsPanel()); sim.getComponentAt(j + 1).setName(""); } else if (sim.getComponentAt(j).getName().equals("GCM Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((GCM2SBMLEditor) (sim.getComponentAt(j))).isDirty(); ((GCM2SBMLEditor) (sim.getComponentAt(j))).saveParams(false, ""); ((GCM2SBMLEditor) (sim.getComponentAt(j))).reload(check.replace(".gcm", "")); ((GCM2SBMLEditor) (sim.getComponentAt(j))).refresh(); ((GCM2SBMLEditor) (sim.getComponentAt(j))).loadParams(); ((GCM2SBMLEditor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File( properties)); if (!((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile().equals( "--none SBML_Editor sbml = new SBML_Editor(root + separator + ((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile(), ((Reb2Sac) sim.getComponentAt(0)), log, this, root + separator + tab, root + separator + tab + separator + tab + ".sim"); sim.setComponentAt(j + 1, sbml.getElementsPanel()); sim.getComponentAt(j + 1).setName(""); ((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); sim.setComponentAt(j + 1, scroll); sim.getComponentAt(j + 1).setName(""); ((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(null); } } } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } ArrayList<String> saved = new ArrayList<String>(); if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { saved.add(this.tab.getTitleAt(i)); GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i); if (gcm.getSBMLFile().equals(updatedFile)) { gcm.save("save"); } } String[] files = new File(root).list(); for (String s : files) { if (s.contains(".gcm") && !saved.contains(s)) { GCMFile gcm = new GCMFile(); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(updatedFile)) { updateViews(s); } } } } } private void updateViewNames(String oldname, String newname) { File work = new File(root); String[] fileList = work.list(); String[] temp = oldname.split(separator); oldname = temp[temp.length - 1]; for (int i = 0; i < fileList.length; i++) { String tabTitle = fileList[i]; String properties = root + separator + tabTitle + separator + tabTitle + ".ver"; String properties1 = root + separator + tabTitle + separator + tabTitle + ".synth"; String properties2 = root + separator + tabTitle + separator + tabTitle + ".lrn"; if (new File(properties).exists()) { String check; Properties p = new Properties(); try { FileInputStream load = new FileInputStream(new File(properties)); p.load(load); load.close(); if (p.containsKey("verification.file")) { String[] getProp = p.getProperty("verification.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } if (check.equals(oldname)) { p.setProperty("verification.file", newname); FileOutputStream out = new FileOutputStream(new File(properties)); p.store(out, properties); } } catch (Exception e) { // log.addText("verification"); // e.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } } if (new File(properties1).exists()) { String check; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties1)); p.load(load); load.close(); if (p.containsKey("synthesis.file")) { String[] getProp = p.getProperty("synthesis.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } if (check.equals(oldname)) { p.setProperty("synthesis.file", newname); FileOutputStream out = new FileOutputStream(new File(properties1)); p.store(out, properties1); } } catch (Exception e) { // log.addText("synthesis"); // e.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } if (check.equals(oldname)) { p.setProperty("learn.file", newname); FileOutputStream out = new FileOutputStream(new File(properties2)); p.store(out, properties2); } } catch (Exception e) { // e.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } } } updateAsyncViews(newname); } private void enableTabMenu(int selectedTab) { treeSelected = false; // log.addText("tab menu"); if (selectedTab != -1) { tab.setSelectedIndex(selectedTab); } Component comp = tab.getSelectedComponent(); // if (comp != null) { // log.addText(comp.toString()); viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); if (comp instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(true); saveGcmAsLhpn.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); } else if (comp instanceof LHPNEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(true); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(true); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); } else if (comp instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(true); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); } else if (comp instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(true); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) comp).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); Boolean learn = false; for (Component c : ((JTabbedPane) comp).getComponents()) { if (c instanceof Learn) { learn = true; } } // int index = tab.getSelectedIndex(); if (component instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); if (learn) { runButton.setEnabled(false); } else { runButton.setEnabled(true); } refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); if (learn) { run.setEnabled(false); } else { run.setEnabled(true); } saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) component).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Reb2Sac) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { if (((Learn) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } saveButton.setEnabled(((Learn) component).getSaveGcmEnabled()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((Learn) component).getSaveGcmEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((Learn) component).getViewLogEnabled()); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // viewCoverage.setEnabled(((Learn) // component).getViewCoverageEnabled()); // SB saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof LearnLHPN) { if (((LearnLHPN) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } saveButton.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled()); viewVHDL.setEnabled(((LearnLHPN) component).getViewVHDLEnabled()); viewVerilog.setEnabled(((LearnLHPN) component).getViewVerilogEnabled()); viewLHPN.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof DataManager) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JPanel) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(true); viewRules.setEnabled(false); // always false?? // viewTrace.setEnabled(((Verification) // comp).getViewTraceEnabled()); viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); // Should // true // only // verification // Result // available??? viewCircuit.setEnabled(false); // always true??? // viewLog.setEnabled(((Verification) // comp).getViewLogEnabled()); viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); // Should // true // only // log // available??? viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(true); } else if (comp.getName().equals("Synthesis")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); // always true?? viewModGraph.setEnabled(true); viewModBrowser.setEnabled(true); // viewRules.setEnabled(((Synthesis) // comp).getViewRulesEnabled()); // viewTrace.setEnabled(((Synthesis) // comp).getViewTraceEnabled()); // viewCircuit.setEnabled(((Synthesis) // comp).getViewCircuitEnabled()); // viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled()); viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); // Always viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); // Always viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); } } else if (comp instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else { saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); } private void enableTreeMenu() { treeSelected = true; // log.addText(tree.getFile()); saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); exportMenu.setEnabled(false); save.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); saveGcmAsLhpn.setEnabled(false); if (tree.getFile() != null) { if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { viewModGraph.setEnabled(true); viewModGraph.setActionCommand("graph"); viewModBrowser.setEnabled(true); createAnal.setEnabled(true); createAnal.setActionCommand("simulate"); createLearn.setEnabled(true); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { viewModGraph.setEnabled(true); viewModGraph.setActionCommand("graphDot"); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSbml.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(true); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); save.setEnabled(true); // SB should be???? // saveas too ???? // viewLog should be available ??? saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { viewModel.setEnabled(true); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createAnal.setActionCommand("createSim"); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(true); viewLHPN.setEnabled(false); save.setEnabled(true); // SB should be???? // saveas too ???? // viewLog should be available ??? saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); if (new File(root + separator + "atacs.log").exists()) { viewLog.setEnabled(true); } else { viewLog.setEnabled(false); } viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); if (new File(root + separator + "atacs.log").exists()) { viewLog.setEnabled(true); } else { viewLog.setEnabled(false); } // not displaying the correct log too ????? SB viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(true); // SB true ??? since lpn save.setEnabled(true); // SB should exist ??? // saveas too??? saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; boolean learn = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } if (sim || synth || ver || learn) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } } public String getRoot() { return root; } public void setGlassPane(boolean visible) { frame.getGlassPane().setVisible(visible); } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, name + " already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { String[] views = canDelete(name); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { tab.remove(i); } } File dir = new File(fullPath); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } return true; } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to overwrite file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File", JOptionPane.ERROR_MESSAGE); return false; } } else { return false; } } else { return true; } } public void updateOpenSBML(String sbmlName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (sbmlName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof SBML_Editor) { SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null); this.tab.setComponentAt(i, newSBML); this.tab.getComponentAt(i).setName("SBML Editor"); newSBML.save(false, "", false); } } } } private String[] canDelete(String filename) { ArrayList<String> views = new ArrayList<String>(); String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } scan.close(); } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } else if (new File(root + separator + s + separator + s + ".ver").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("verification.file")) { String[] getProp = p.getProperty("verification.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } else if (new File(root + separator + s + separator + s + ".synth").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("synthesis.file")) { String[] getProp = p.getProperty("synthesis.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } if (check.equals(filename)) { views.add(s); } } } String[] usingViews = views.toArray(new String[0]); sort(usingViews); return usingViews; } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } private void reassignViews(String oldName, String newName) { String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { ArrayList<String> copy = new ArrayList<String>(); Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; if (check.equals(oldName)) { while (scan.hasNextLine()) { copy.add(scan.nextLine()); } scan.close(); FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim")); out.write((newName + "\n").getBytes()); for (String cop : copy) { out.write((cop + "\n").getBytes()); } out.close(); } else { scan.close(); } } } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; if (check.equals(oldName)) { p.setProperty("genenet.file", newName); FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn")); p.store(store, "Learn File Data"); store.close(); } } } catch (Exception e) { } } } } } protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText, String altText) { // URL imageURL = BioSim.class.getResource(imageName); // Create and initialize the button. JButton button = new JButton(); button.setActionCommand(actionCommand); button.setToolTipText(toolTipText); button.addActionListener(this); button.setIcon(new ImageIcon(imageName)); // if (imageURL != null) { //image found // button.setIcon(new ImageIcon(imageURL, altText)); // } else { //no image found // button.setText(altText); // System.err.println("Resource not found: " // + imageName); return button; } public static SBMLDocument readSBML(String filename) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename); JTextArea messageArea = new JTextArea(); messageArea.append("Conversion to SBML level " + SBML_LEVEL + " version " + SBML_VERSION + " produced the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; long numErrors = document.checkL2v4Compatibility(); if (numErrors > 0) { display = true; messageArea .append(" messageArea.append(filename); messageArea .append("\n for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } } if (display) { final JFrame f = new JFrame("SBML Conversion Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION); return document; } }
package risk; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RiskBoard { private List<Territory> territories; private int playerCount; /** * Colors of game pieces. **/ public enum Colors{ BLACK, BLUE, GREEN, PINK, RED, YELLOW; } // A new board will be blank, with no territories and no connections public RiskBoard(){ territories = new ArrayList<Territory>(); } /** * Will attempt to setup the board based on an input file. Territories * will be added first and then routes will be set up. * <p> * A valid file should contain Regions in the format "Region: Name". * followed by the names of territories. After all the territories * in that region should be a blank line. (You can have as many regions as you like.) * Following all the regions and territories, the routes are set up by starting * a line with "Routes:". This should be followed by a list of each connection * (routes are all bi-directional) in the format "Place-Place2". * * @param fileName the name of a file containing valid board information **/ public void setup(String fileName) { try { BufferedReader br = new BufferedReader(new FileReader(fileName)); while(br.ready()){ String input = br.readLine(); if (input.contains("Region: ")){ // setup regions this.setupRegions(br); }else if(input.contains("Routes:")){ // setup routes this.setupRoutes(br); } } } catch (FileNotFoundException e) { System.out.println("File not found: "); e.printStackTrace(); } catch (IOException e){ System.out.println("File read error: "); e.printStackTrace(); } } /** * Private method takes a BufferedReader and reads in each line, * adds connection to territory objects in the territories list until * it reaches a blank line or end of file. The accepted format is: * "Territory1-Terrotory2"; * * @param br a BufferedReader object of the file with setup information **/ private void setupRoutes(BufferedReader br) throws IOException { while(br.ready()){ String input = br.readLine(); if(input.equals("")) return; else { String[] route = input.split("-"); addConnection(route[0],route[1]); } } } /** * Method to add connections to territories. Note: all connections are 2 way. * Will ignore adds where either territory cannot be found. * * @paramfrom Territory to start in * @param to Territory to end in **/ public void addConnection(String from, String to){ Territory terraFrom = null; Territory terraTo = null; for(Territory terra : territories){ if (terra.getName().equals(from)){ terraFrom = terra; } else if(terra.getName().equals(to)){ terraTo = terra; } } if(terraFrom != null && terraTo != null){ terraFrom.addConnection(terraTo); terraTo.addConnection(terraFrom); } } /** * Looks up a territory and returns that territory's connections list. * * @param territory the territory to look up * @return a list of connections from the given territory */ public List<Territory> getConnections(String territory){ for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getConnections(); } } return null; } /** * Private method takes a BufferedReader and reads in each line, * creates a territory object, and adds it to the territories list until * it reaches a blank line or end of file. * * @param br a BufferedReader object of the file with setup information **/ private void setupRegions(BufferedReader br) throws IOException { while(br.ready()){ String input = br.readLine(); if(input.equals("")) return; else territories.add(new Territory(input)); } } /** * Get method for territories. * * @return the territories in List<Territory> form. **/ public List<Territory> getTerritories() {return territories;} /** * Method to get the number of troops in a particular territory. * Method will return 0 for calls without a valid name. * * @param territory the name of the territory to get info from * @return returns the number of troops in a territory **/ public int getTroops(String territory) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getTroops(); } } return 0; } /** * Method to add (positive number) or subtract (negative number) troops from a given territory. * Any calls without a valid name will be ignored. This method will check to ensure the number * of troops in a territory does not fall below 0. If it does, the number will be set to 0. * * @param territory the name of the territory to add to * @param num the number of troops to add(or subtract) **/ public void changeTroops(String territory, int num) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ int troops = terra.getTroops() + num; if(troops > 0){ terra.setTroops(troops); } else { terra.setTroops(0); } } } } /** * Will return the name of the faction holding the territroy given. * * @param territory the name of the territory to look up * @return a string with the name of the faction in control **/ public String getFaction(String territory) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getFaction(); } } return "None"; } /** * Sets the name of the faction for a partuicular territory. * * @param territory the name of the territory * @param faction the name of the faction to change it to **/ public void setFaction(String territory, String faction) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ terra.setFaction(faction); } } } /** * Method takes an attacking territory name and a defending * territory name, checks if it is a valid attack and rolls * with the most dice possible (3) if not given. If the defending * territory reaches 0 troops, the attacker invades. * * @param attacker the attacking territory * @param defender the defending territory * @param num the number of troops to attack with (1 - 3) */ public void attack(String attacker, String defender, int num) { int defendTroops = getTroops(defender); int attackTroops = getTroops(attacker); // Error check for same owner if(getFaction(defender).equals(getFaction(attacker))) return; // Error check num is not more than available troops. if (num > 3) num = 3; if (num > attackTroops-1) num = attackTroops-1; // Check for an empty territory, will end method if true. if(defendTroops <= 0) { setFaction(defender, getFaction(attacker)); changeTroops(defender, num); return; } // Find max troops available to defend. int dNum = 1; if (defendTroops > 1) dNum = 2; //dice rolls int[] defendRolls = getRolls(dNum); int[] attackRolls = getRolls(num); // take away troops based on the highest rolls (defender's advantage) if (dNum <= num){ for (int i = 0; i < defendRolls.length; i++){ if(defendRolls[i] >= attackRolls[i]) changeTroops(attacker, -1); else changeTroops(defender, -1); } } else { for (int i = 0; i < attackRolls.length; i++){ if(defendRolls[i] >= attackRolls[i]) changeTroops(attacker, -1); else changeTroops(defender, -1); } } /* Check for 0 troops in defending territory, if so * move # of attacking troops into territory and switch faction */ if(getTroops(defender) <= 0) { setFaction(defender, getFaction(attacker)); changeTroops(defender, num); } } /** * Overflow method to attack with max troops (3). **/ public void attack(String attacker, String defender) { attack(attacker, defender, 3); } /** * Helper method to roll a number of dice in succession. * * @param num the number of times to roll dice * @return an array with the number of dice rolled. **/ private int[] getRolls(int num) { int[] rolls = new int[num]; for(int i = 0; i< num; i++){ rolls[i] = rollDice(6); } Arrays.sort(rolls); return rolls; } /** * Helper method to roll a die. * * @param i the number of sides on the dice. * @return the dice roll **/ private int rollDice(int i) { return (int) (Math.random()*i) + 1; } }
package run; import be.ac.ulg.montefiore.run.jahmm.ObservationDiscrete; import entities.BOWFeatureVector; import entities.BaselineBOWFeatureVector; import entities.HMMFeatureVector; import entities.HMMSequence; import entities.NGGFeatureVector; import entities.SequenceInstance; import entities.WekaBOWFeatureVector; import entities.WekaBaselineBOWFeatureVector; import entities.WekaHMMFeatureVector; import entities.WekaNGGFeatureVector; import gr.demokritos.iit.jinsect.documentModel.representations.DocumentNGramGraph; import io.FAFileReader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import static java.util.Collections.rotate; import java.util.List; import representation.BOWHandler; import representation.BOW_SequenceAnalyst; import representation.BagOfWords; import representation.BaselineBOWHandler; import representation.BaselineBOW_SequenceAnalyst; import representation.BaselineBagOfWords; import representation.GenomicSequenceAnalyst; import representation.GenomicSequenceRepresentationHandler; import representation.HMM_SequenceAnalyst; import representation.HmmHandler; import representation.NGGHandler; import representation.NGG_SequenceAnalyst; import representation.NormalizedHmmHandler; import statistics.BinaryStatisticsEvaluator; import weka.core.Instances; import weka.core.converters.ArffSaver; /** * * @author nikos */ public class RunHandler { public void run(String NFR_pathfile, String NBS_pathfile, String folds, String representation_type, String classifier_type) throws IOException { FAFileReader reader = new FAFileReader(); // ManyInstancesPerFileConverter m = new ManyInstancesPerFileConverter(); ArrayList<SequenceInstance> NFR_instances = reader.getSequencesFromFile(NFR_pathfile); ArrayList<SequenceInstance> NBS_instances = reader.getSequencesFromFile(NBS_pathfile); // ArrayList<SequenceInstance> NBS_instances = new ArrayList<>(temp_NBS_instances.subList(0, NFR_instances.size())); GenomicSequenceAnalyst<List<ObservationDiscrete<HMMSequence.Packet>>> hmm_analyst = new HMM_SequenceAnalyst(); NGG_SequenceAnalyst ngg_analyst = new NGG_SequenceAnalyst(); BOW_SequenceAnalyst bow_analyst = new BOW_SequenceAnalyst(); BaselineBOW_SequenceAnalyst baselinebow_analyst = new BaselineBOW_SequenceAnalyst(); int nfolds = Integer.parseInt(folds); int NFRpartitionSize = NFR_instances.size() / nfolds; int NBSpartitionSize = NBS_instances.size() / nfolds; List<SequenceInstance> NFR_Seqs = new ArrayList<>(NFR_instances); List<SequenceInstance> NBS_Seqs = new ArrayList<>(NBS_instances); List<SequenceInstance> NFR_trainingSeqs; NFR_trainingSeqs = new ArrayList(); List<SequenceInstance> NBS_trainingSeqs; NBS_trainingSeqs = new ArrayList(); List<SequenceInstance> NFR_testingSeqs = null; NFR_testingSeqs = new ArrayList(); List<SequenceInstance> NBS_testingSeqs = null; NBS_testingSeqs = new ArrayList(); for (int i = 0; i < nfolds; i++) { initTrainingSeqs(nfolds, NFRpartitionSize, NFR_trainingSeqs, NFR_Seqs, NBSpartitionSize, NBS_trainingSeqs, NBS_Seqs); initTestSeqs(nfolds, NFRpartitionSize, NFR_Seqs, NFR_testingSeqs, NBSpartitionSize, NBS_Seqs, NBS_testingSeqs); if("HMM".equals(representation_type)) { /* Representing the sequences as HMMs */ List<List<ObservationDiscrete<HMMSequence.Packet>>> NFRTrainingHMM = hmm_analyst.represent(NFR_trainingSeqs); List<List<ObservationDiscrete<HMMSequence.Packet>>> NBSTrainingHMM = hmm_analyst.represent(NBS_trainingSeqs); /* The same with the testing sequences */ List<List<ObservationDiscrete<HMMSequence.Packet>>> NFRTestingHMM = hmm_analyst.represent(NFR_testingSeqs); List<List<ObservationDiscrete<HMMSequence.Packet>>> NBSTestingHMM = hmm_analyst.represent(NBS_testingSeqs); /* We train the two HMMs only by using the training HMM sequences */ long tic = System.nanoTime(); GenomicSequenceRepresentationHandler<List<ObservationDiscrete<HMMSequence.Packet>>> handler = new HmmHandler(); handler.train(NFRTrainingHMM, "Nucleosome Free Region"); handler.train(NBSTrainingHMM, "Nucleosome Binding Site"); long tac = System.nanoTime(); long elapsedTime = tac - tic; double seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for HMM training : " + seconds); /* Initializing the vectors we want to store */ ArrayList<HMMFeatureVector> NFRTrainingVectors = new ArrayList<>(); ArrayList<HMMFeatureVector> NBSTrainingVectors = new ArrayList<>(); ArrayList<HMMFeatureVector> NFRTestingVectors = new ArrayList<>(); ArrayList<HMMFeatureVector> NBSTestingVectors = new ArrayList<>(); /* Getting the feature vectors for each of our sequence lists */ for(List<ObservationDiscrete<HMMSequence.Packet>> NFRinstanceRepresentation : NFRTrainingHMM) { NFRTrainingVectors.add((HMMFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<ObservationDiscrete<HMMSequence.Packet>> NBSinstanceRepresentation : NBSTrainingHMM) { NBSTrainingVectors.add((HMMFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } for(List<ObservationDiscrete<HMMSequence.Packet>> NFRinstanceRepresentation : NFRTestingHMM) { NFRTestingVectors.add((HMMFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<ObservationDiscrete<HMMSequence.Packet>> NBSinstanceRepresentation : NBSTestingHMM) { NBSTestingVectors.add((HMMFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } //Get the Weka feature vectors WekaHMMFeatureVector HMMfv= new WekaHMMFeatureVector(); Instances Training_Instances = HMMfv.fillInstanceSet(NFRTrainingVectors, NBSTrainingVectors); Instances Testing_Instances = HMMfv.fillInstanceSet(NFRTestingVectors, NBSTestingVectors); try { saveFoldFiles(Training_Instances, i, Testing_Instances); } catch (IOException ioe) { ioe.printStackTrace(System.err); System.out.println("Could not output fold ARFF files " + "(perhaps ARFF directory is missing?). " + "Skipping..."); } tic = System.nanoTime(); // Perform classification and get Confusion Matrix BinaryStatisticsEvaluator ev = new BinaryStatisticsEvaluator(); double[][] ConfMatrix = ev.getConfusionMatrix(Training_Instances, Testing_Instances, classifier_type); tac = System.nanoTime(); elapsedTime = tac - tic; seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for HMM classification : " + seconds); // Print results System.out.println("Precision of model :" + ev.getPrecision(ConfMatrix)); System.out.println("Accuracy of model :" + ev.getAccuracy(ConfMatrix)); System.out.println("AUC of model :" + ev.getAUC(ConfMatrix)); System.out.println("Recall of model :" + ev.getRecall(ConfMatrix)); System.out.println("Specificity of model :" + ev.getSpecificity(ConfMatrix)); System.out.println("F-score of model :" + ev.getfScore(ConfMatrix)); rotate(NFR_Seqs, NFRpartitionSize); rotate(NBS_Seqs, NBSpartitionSize); clearSeqs(NFR_trainingSeqs, NBS_trainingSeqs, NFR_testingSeqs, NBS_testingSeqs); } if("Normalized_HMM".equals(representation_type)) { /* Representing the sequences as HMMs */ List<List<ObservationDiscrete<HMMSequence.Packet>>> NFRTrainingHMM = hmm_analyst.represent(NFR_trainingSeqs); List<List<ObservationDiscrete<HMMSequence.Packet>>> NBSTrainingHMM = hmm_analyst.represent(NBS_trainingSeqs); /* The same with the testing sequences */ List<List<ObservationDiscrete<HMMSequence.Packet>>> NFRTestingHMM = hmm_analyst.represent(NFR_testingSeqs); List<List<ObservationDiscrete<HMMSequence.Packet>>> NBSTestingHMM = hmm_analyst.represent(NBS_testingSeqs); /* We train the two HMMs only by using the training HMM sequences */ long tic = System.nanoTime(); GenomicSequenceRepresentationHandler<List<ObservationDiscrete<HMMSequence.Packet>>> handler = new NormalizedHmmHandler(); handler.train(NFRTrainingHMM, "Nucleosome Free Region"); handler.train(NBSTrainingHMM, "Nucleosome Binding Site"); long tac = System.nanoTime(); long elapsedTime = tac - tic; double seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for Normalized HMM training : " + seconds); /* Initializing the vectors we want to store */ ArrayList<HMMFeatureVector> NFRTrainingVectors = new ArrayList<>(); ArrayList<HMMFeatureVector> NBSTrainingVectors = new ArrayList<>(); ArrayList<HMMFeatureVector> NFRTestingVectors = new ArrayList<>(); ArrayList<HMMFeatureVector> NBSTestingVectors = new ArrayList<>(); /* Getting the feature vectors for each of our sequence lists */ for(List<ObservationDiscrete<HMMSequence.Packet>> NFRinstanceRepresentation : NFRTrainingHMM) { NFRTrainingVectors.add((HMMFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<ObservationDiscrete<HMMSequence.Packet>> NBSinstanceRepresentation : NBSTrainingHMM) { NBSTrainingVectors.add((HMMFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } for(List<ObservationDiscrete<HMMSequence.Packet>> NFRinstanceRepresentation : NFRTestingHMM) { NFRTestingVectors.add((HMMFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<ObservationDiscrete<HMMSequence.Packet>> NBSinstanceRepresentation : NBSTestingHMM) { NBSTestingVectors.add((HMMFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } //Get the Weka feature vectors WekaHMMFeatureVector HMMfv= new WekaHMMFeatureVector(); Instances Training_Instances = HMMfv.fillInstanceSet(NFRTrainingVectors, NBSTrainingVectors); Instances Testing_Instances = HMMfv.fillInstanceSet(NFRTestingVectors, NBSTestingVectors); // Store instances to related fold files in ARFF subdir (WARNING: It must exist) try { saveFoldFiles(Training_Instances, i, Testing_Instances); } catch (IOException ioe) { ioe.printStackTrace(System.err); System.out.println("Could not output fold ARFF files " + "(perhaps ARFF directory is missing?). " + "Skipping..."); } tic = System.nanoTime(); // Perform classification and get Confusion Matrix BinaryStatisticsEvaluator ev = new BinaryStatisticsEvaluator(); double[][] ConfMatrix = ev.getConfusionMatrix(Training_Instances, Testing_Instances, classifier_type); tac = System.nanoTime(); elapsedTime = tac - tic; seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for Normalized HMM classification : " + seconds); // Print results System.out.println("Precision of model :" + ev.getPrecision(ConfMatrix)); System.out.println("Accuracy of model :" + ev.getAccuracy(ConfMatrix)); System.out.println("AUC of model :" + ev.getAUC(ConfMatrix)); System.out.println("Recall of model :" + ev.getRecall(ConfMatrix)); System.out.println("Specificity of model :" + ev.getSpecificity(ConfMatrix)); System.out.println("F-score of model :" + ev.getfScore(ConfMatrix)); rotate(NFR_Seqs, NFRpartitionSize); rotate(NBS_Seqs, NBSpartitionSize); clearSeqs(NFR_trainingSeqs, NBS_trainingSeqs, NFR_testingSeqs, NBS_testingSeqs); } if("NGG".equals(representation_type)) { /* Representing the sequences as NGGs */ List<List<DocumentNGramGraph>> NFRTrainingNGG = ngg_analyst.represent(NFR_trainingSeqs); List<List<DocumentNGramGraph>> NBSTrainingNGG = ngg_analyst.represent(NBS_trainingSeqs); /* The same with the testing sequences */ List<List<DocumentNGramGraph>> NFRTestingNGG = ngg_analyst.represent(NFR_testingSeqs); List<List<DocumentNGramGraph>> NBSTestingNGG = ngg_analyst.represent(NBS_testingSeqs); /* We train the two NGGs only by using the training NGG sequences */ long tic = System.nanoTime(); NGGHandler handler = new NGGHandler(); handler.train(NFRTrainingNGG, "Nucleosome Free Region"); handler.train(NBSTrainingNGG, "Nucleosome Binding Site"); long tac = System.nanoTime(); long elapsedTime = tac - tic; double seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for NGG training : " + seconds); /* Initializing the vectors we want to store */ ArrayList<NGGFeatureVector> NFRTrainingVectors = new ArrayList<>(); ArrayList<NGGFeatureVector> NBSTrainingVectors = new ArrayList<>(); ArrayList<NGGFeatureVector> NFRTestingVectors = new ArrayList<>(); ArrayList<NGGFeatureVector> NBSTestingVectors = new ArrayList<>(); /* Getting the feature vectors for each of our sequence lists */ for(List<DocumentNGramGraph> NFRinstanceRepresentation : NFRTrainingNGG) { NFRTrainingVectors.add((NGGFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<DocumentNGramGraph> NBSinstanceRepresentation : NBSTrainingNGG) { NBSTrainingVectors.add((NGGFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } for(List<DocumentNGramGraph> NFRinstanceRepresentation : NFRTestingNGG) { NFRTestingVectors.add((NGGFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<DocumentNGramGraph> NBSinstanceRepresentation : NBSTestingNGG) { NBSTestingVectors.add((NGGFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } WekaNGGFeatureVector NGGfv= new WekaNGGFeatureVector(); Instances Training_Instances = NGGfv.fillInstanceSet(NFRTrainingVectors, NBSTrainingVectors, "train"); Instances Testing_Instances = NGGfv.fillInstanceSet(NFRTestingVectors, NBSTestingVectors, "test"); // Store instances to related fold files in ARFF subdir (WARNING: It must exist) try { saveFoldFiles(Training_Instances, i, Testing_Instances); } catch (IOException ioe) { ioe.printStackTrace(System.err); System.out.println("Could not output fold ARFF files " + "(perhaps ARFF directory is missing?). " + "Skipping..."); } tic = System.nanoTime(); // Perform classification and get Confusion Matrix BinaryStatisticsEvaluator ev = new BinaryStatisticsEvaluator(); double[][] ConfMatrix = ev.getConfusionMatrix(Training_Instances, Testing_Instances, classifier_type); tac = System.nanoTime(); elapsedTime = tac - tic; seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for NGG classification : " + seconds); outputResults(i, ev, ConfMatrix); rotate(NFR_Seqs, NFRpartitionSize); rotate(NBS_Seqs, NBSpartitionSize); clearSeqs(NFR_trainingSeqs, NBS_trainingSeqs, NFR_testingSeqs, NBS_testingSeqs); } if("BOW".equals(representation_type)) { /* Representing the sequences as BOWs */ List<List<BagOfWords>> NFRTrainingBOW = bow_analyst.represent(NFR_trainingSeqs); List<List<BagOfWords>> NBSTrainingBOW = bow_analyst.represent(NBS_trainingSeqs); /* The same with the testing sequences */ List<List<BagOfWords>> NFRTestingBOW = bow_analyst.represent(NFR_testingSeqs); List<List<BagOfWords>> NBSTestingBOW = bow_analyst.represent(NBS_testingSeqs); /* We train the two BOWs only by using the training BOW sequences */ long tic = System.nanoTime(); BOWHandler handler = new BOWHandler(); handler.train(NFRTrainingBOW, "Nucleosome Free Region"); handler.train(NBSTrainingBOW, "Nucleosome Binding Site"); long tac = System.nanoTime(); long elapsedTime = tac - tic; double seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for BOW training : " + seconds); /* Initializing the vectors we want to store */ ArrayList<BOWFeatureVector> NFRTrainingVectors = new ArrayList<>(); ArrayList<BOWFeatureVector> NBSTrainingVectors = new ArrayList<>(); ArrayList<BOWFeatureVector> NFRTestingVectors = new ArrayList<>(); ArrayList<BOWFeatureVector> NBSTestingVectors = new ArrayList<>(); for(List<BagOfWords> NFRinstanceRepresentation : NFRTrainingBOW) { NFRTrainingVectors.add((BOWFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<BagOfWords> NBSinstanceRepresentation : NBSTrainingBOW) { NBSTrainingVectors.add((BOWFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } for(List<BagOfWords> NFRinstanceRepresentation : NFRTestingBOW) { NFRTestingVectors.add((BOWFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<BagOfWords> NBSinstanceRepresentation : NBSTestingBOW) { NBSTestingVectors.add((BOWFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } WekaBOWFeatureVector BOWfv = new WekaBOWFeatureVector(); Instances Training_Instances = BOWfv.fillInstanceSet(NFRTrainingVectors, NBSTrainingVectors); Instances Testing_Instances = BOWfv.fillInstanceSet(NFRTestingVectors, NBSTestingVectors); // Store instances to related fold files in ARFF subdir (WARNING: It must exist) try { saveFoldFiles(Training_Instances, i, Testing_Instances); } catch (IOException ioe) { ioe.printStackTrace(System.err); System.out.println("Could not output fold ARFF files " + "(perhaps ARFF directory is missing?). " + "Skipping..."); } tic = System.nanoTime(); // Perform classification and get Confusion Matrix BinaryStatisticsEvaluator ev = new BinaryStatisticsEvaluator(); double[][] ConfMatrix = ev.getConfusionMatrix(Training_Instances, Testing_Instances, classifier_type); tac = System.nanoTime(); elapsedTime = tac - tic; seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for BOW classification : " + seconds); outputResults(i, ev, ConfMatrix); rotate(NFR_Seqs, NFRpartitionSize); rotate(NBS_Seqs, NBSpartitionSize); clearSeqs(NFR_trainingSeqs, NBS_trainingSeqs, NFR_testingSeqs, NBS_testingSeqs); } if("Baseline_BOW".equals(representation_type)) { /* Representing the sequences as BOWs */ List<List<BaselineBagOfWords>> NFRTrainingBOW = baselinebow_analyst.represent(NFR_trainingSeqs); List<List<BaselineBagOfWords>> NBSTrainingBOW = baselinebow_analyst.represent(NBS_trainingSeqs); /* The same with the testing sequences */ List<List<BaselineBagOfWords>> NFRTestingBOW = baselinebow_analyst.represent(NFR_testingSeqs); List<List<BaselineBagOfWords>> NBSTestingBOW = baselinebow_analyst.represent(NBS_testingSeqs); /* We train the two BOWs only by using the training BOW sequences */ long tic = System.nanoTime(); BaselineBOWHandler handler = new BaselineBOWHandler(); handler.train(NFRTrainingBOW, "Nucleosome Free Region"); handler.train(NBSTrainingBOW, "Nucleosome Binding Site"); long tac = System.nanoTime(); long elapsedTime = tac - tic; double seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for BOW training : " + seconds); /* Initializing the vectors we want to store */ ArrayList<BaselineBOWFeatureVector> NFRTrainingVectors = new ArrayList<>(); ArrayList<BaselineBOWFeatureVector> NBSTrainingVectors = new ArrayList<>(); ArrayList<BaselineBOWFeatureVector> NFRTestingVectors = new ArrayList<>(); ArrayList<BaselineBOWFeatureVector> NBSTestingVectors = new ArrayList<>(); for(List<BaselineBagOfWords> NFRinstanceRepresentation : NFRTrainingBOW) { NFRTrainingVectors.add((BaselineBOWFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<BaselineBagOfWords> NBSinstanceRepresentation : NBSTrainingBOW) { NBSTrainingVectors.add((BaselineBOWFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } for(List<BaselineBagOfWords> NFRinstanceRepresentation : NFRTestingBOW) { NFRTestingVectors.add((BaselineBOWFeatureVector) handler.getFeatureVector(NFRinstanceRepresentation, "Nucleosome Free Region")); } for(List<BaselineBagOfWords> NBSinstanceRepresentation : NBSTestingBOW) { NBSTestingVectors.add((BaselineBOWFeatureVector) handler.getFeatureVector(NBSinstanceRepresentation, "Nucleosome Binding Site")); } WekaBaselineBOWFeatureVector BBOWfv= new WekaBaselineBOWFeatureVector(); Instances Training_Instances = BBOWfv.fillInstanceSet(NFRTrainingVectors, NBSTrainingVectors); Instances Testing_Instances = BBOWfv.fillInstanceSet(NFRTestingVectors, NBSTestingVectors); // Store instances to related fold files in ARFF subdir (WARNING: It must exist) try { saveFoldFiles(Training_Instances, i, Testing_Instances); } catch (IOException ioe) { ioe.printStackTrace(System.err); System.out.println("Could not output fold ARFF files " + "(perhaps ARFF directory is missing?). " + "Skipping..."); } tic = System.nanoTime(); // Perform classification and get Confusion Matrix BinaryStatisticsEvaluator ev = new BinaryStatisticsEvaluator(); double[][] ConfMatrix = ev.getConfusionMatrix(Training_Instances, Testing_Instances, classifier_type); tac = System.nanoTime(); elapsedTime = tac - tic; seconds = (double)elapsedTime / 1000000000.0; System.out.println("time elapsed for BOW classification : " + seconds); outputResults(i, ev, ConfMatrix); rotate(NFR_Seqs, NFRpartitionSize); rotate(NBS_Seqs, NBSpartitionSize); clearSeqs(NFR_trainingSeqs, NBS_trainingSeqs, NFR_testingSeqs, NBS_testingSeqs); } } } protected void clearSeqs(List<SequenceInstance> NFR_trainingSeqs, List<SequenceInstance> NBS_trainingSeqs, List<SequenceInstance> NFR_testingSeqs, List<SequenceInstance> NBS_testingSeqs) { NFR_trainingSeqs.clear(); NBS_trainingSeqs.clear(); NFR_testingSeqs.clear(); NBS_testingSeqs.clear(); } protected void outputResults(int iFoldNo, BinaryStatisticsEvaluator ev, double[][] ConfMatrix) { // Print results System.out.println("\n=== Fold:" + iFoldNo + "==="); System.out.println("Precision of model :" + ev.getPrecision(ConfMatrix)); System.out.println("Accuracy of model :" + ev.getAccuracy(ConfMatrix));; System.out.println("AUC of model :" + ev.getAUC(ConfMatrix)); System.out.println("Recall of model :" + ev.getRecall(ConfMatrix)); System.out.println("Specificity of model :" + ev.getSpecificity(ConfMatrix)); System.out.println("F-score of model :" + ev.getfScore(ConfMatrix)); } protected void saveFoldFiles(Instances Training_Instances, int i, Instances Testing_Instances) throws IOException { // Store instances to related fold files in ARFF subdir (WARNING: It must exist) ArffSaver asSaver = new ArffSaver(); asSaver.setInstances(Training_Instances); asSaver.setFile(new File(String.format("ARFF/train-fold%d.arff", i))); asSaver.writeBatch(); asSaver.setInstances(Testing_Instances); asSaver.setFile(new File(String.format("ARFF/test-fold%d.arff", i))); asSaver.writeBatch(); } protected void initTestSeqs(int nfolds, int NFRpartitionSize, List<SequenceInstance> NFR_Seqs, List<SequenceInstance> NFR_testingSeqs, int NBSpartitionSize, List<SequenceInstance> NBS_Seqs, List<SequenceInstance> NBS_testingSeqs) { /* Initializing the testing sequences */ for(int j = (nfolds-1)*NFRpartitionSize; j < NFR_Seqs.size(); j++) { NFR_testingSeqs.add(NFR_Seqs.get(j)); } for(int j = (nfolds-1)*NBSpartitionSize; j < NBS_Seqs.size(); j++) { NBS_testingSeqs.add(NBS_Seqs.get(j)); } } protected void initTrainingSeqs(int nfolds, int NFRpartitionSize, List<SequenceInstance> NFR_trainingSeqs, List<SequenceInstance> NFR_Seqs, int NBSpartitionSize, List<SequenceInstance> NBS_trainingSeqs, List<SequenceInstance> NBS_Seqs) { /* Initializing the training sequences */ for(int j = 0; j < (nfolds-1)*NFRpartitionSize; j++) { NFR_trainingSeqs.add(NFR_Seqs.get(j)); } for(int j = 0; j < (nfolds-1)*NBSpartitionSize; j++) { NBS_trainingSeqs.add(NBS_Seqs.get(j)); } } }
package students.filters; import weka.core.Attribute; import weka.core.Instances; import weka.core.RevisionUtils; import weka.filters.SimpleBatchFilter; public class IndependentComponetFilter extends SimpleBatchFilter { /** for serialization. */ private static final long serialVersionUID = -5416810876710954131L; @Override public String globalInfo() { return "Performs Independent Component Analysis and transformation " + "of the data using the FastICA algorithm ignoring the class " + "label."; } @Override protected Instances determineOutputFormat(Instances inputFormat) throws Exception { return new Instances(inputFormat, 0); } @Override protected Instances process(Instances instances) throws Exception { // Test that there is no missing data and only contains numeric attributes // TODO: needs args for max_iter, tolerance // Convert instances to matrix ignoring class labels // Process the data through FastICA // Convert results back to Instances return null; } public String getRevision() { return RevisionUtils.extract("$Revision: 1.0 $"); } }
package com.treasure_data.jdbc; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.ProxyAuthenticator; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class TestProxy { private static Logger logger = LoggerFactory.getLogger(TestProxy.class); private HttpProxyServer proxyServer; private int proxyPort; private static int findAvailablePort() throws IOException { ServerSocket socket = new ServerSocket(0); try { int port = socket.getLocalPort(); return port; } finally { socket.close(); } } private static final String PROXY_USER = "test"; private static final String PROXY_PASS = "helloproxy"; @Before public void setUp() throws Exception { this.proxyPort = findAvailablePort(); this.proxyServer = DefaultHttpProxyServer.bootstrap().withPort(proxyPort).withProxyAuthenticator(new ProxyAuthenticator() { @Override public boolean authenticate(String user, String pass) { return user.equals(PROXY_USER) && pass.equals(PROXY_PASS); } }).start(); } @After public void tearDown() throws Exception { if(this.proxyServer != null) { proxyServer.stop(); } } @Test public void connectThroughProxy() throws IOException, SQLException { Connection conn = TestProductionEnv.newConnection(String.format( "jdbc:td://api.treasuredata.com/hivebench_tiny;useSSL=true;type=presto;httpproxyhost=localhost;httpproxyport=%d;httpproxyuser=%s;httpproxypassword=%s", proxyPort, PROXY_USER, PROXY_PASS), new Properties() ); Statement stat = conn.createStatement(); stat.execute("select count(*) from hivebench_tiny.uservisits"); ResultSet rs = stat.getResultSet(); assertTrue(rs.next()); int rowCount = rs.getInt(1); assertEquals(10000, rowCount); stat.close(); conn.close(); } private static void assertFunction(Properties prop, String sqlProjection, String expectedAnswer) throws IOException, SQLException { Connection conn = TestProductionEnv.newPrestoConnection("hivebench_tiny", prop); Statement stat = conn.createStatement(); String sql = String.format("select %s from uservisits", sqlProjection); stat.execute(sql); ResultSet rs = stat.getResultSet(); assert(rs.next()); String col = rs.getString(1); logger.debug("result: " + col); rs.close(); stat.close(); conn.close(); } private Properties getJdbcProxyConfig() { Properties prop = new Properties(); prop.setProperty("httpproxyhost", "localhost"); prop.setProperty("httpproxyport", Integer.toString(proxyPort)); prop.setProperty("httpproxyuser", PROXY_USER); prop.setProperty("httpproxypassword", PROXY_PASS); return prop; } @Test public void proxyConfigViaProperties() throws IOException, SQLException { assertFunction(getJdbcProxyConfig(), "count(*)", "10000"); } @Test public void proxyConfigViaSystemProperties() throws IOException, SQLException { Properties prop = new Properties(); String prevProxyHost = System.setProperty("http.proxyHost", "localhost"); String prevProxyPort = System.setProperty("http.proxyPort", Integer.toString(proxyPort)); String prevProxyUser = System.setProperty("http.proxyUser", PROXY_USER); String prevProxyPass = System.setProperty("http.proxyPassword", PROXY_PASS); try { assertFunction(prop, "count(*)", "10000"); } finally { if(prevProxyHost != null) { System.setProperty("http.proxyHost", prevProxyHost); } if(prevProxyPort != null) { System.setProperty("http.proxyPort", prevProxyPort); } if(prevProxyUser != null) { System.setProperty("http.proxyUser", prevProxyUser); } if(prevProxyPass != null) { System.setProperty("http.proxyPassword", prevProxyPass); } } } @Ignore("failing test for CLT-735") @Test public void detectWrongProxyPassword() throws IOException, SQLException { Properties prop = getJdbcProxyConfig(); prop.setProperty("httpproxyuser", "testtest"); // set a wrong password Connection conn = TestProductionEnv.newPrestoConnection("hivebench_tiny", prop); Statement stat = conn.createStatement(); try { stat.execute("select count(*) from uservisits"); } catch(SQLException e) { // Should display authentication failure message here logger.error("authentication failure", e); return; } ResultSet rs = stat.getResultSet(); String result = rs.getString(1); logger.debug("result: " + result); fail("should not reach here"); } }
package imagej.ops; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import imagej.module.Module; import net.imglib2.type.numeric.real.DoubleType; import org.junit.Test; import org.scijava.ItemIO; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Tests {@link OpMatchingService}. * * @author Curtis Rueden */ public class OpMatchingServiceTest extends AbstractOpTest { /** Tests {@link OpMatchingService#findModule}. */ @Test public void testFindModule() { final DoubleType value = new DoubleType(123.456); final Module moduleByName = matcher.findModule("nan", null, value); assertSame(value, moduleByName.getInput("arg")); assertFalse(Double.isNaN(value.get())); moduleByName.run(); assertTrue(Double.isNaN(value.get())); value.set(987.654); final Module moduleByType = matcher.findModule(null, NaNOp.class, value); assertSame(value, moduleByType.getInput("arg")); assertFalse(Double.isNaN(value.get())); moduleByType.run(); assertTrue(Double.isNaN(value.get())); } /** Tests support for matching when there are optional parameters. */ @Test public void testOptionalParams() { Module m; try { m = matcher.findModule(null, OptionalParams.class, 1, 2, 3, 4, 5, 6, 7); fail("Expected IllegalArgumentException for 7 args"); } catch (final IllegalArgumentException exc) { // NB: Expected. } m = matcher.findModule(null, OptionalParams.class, 1, 2, 3, 4, 5, 6); assertValues(m, 1, 2, 3, 4, 5, 6, -7); m = matcher.findModule(null, OptionalParams.class, 1, 2, 3, 4, 5); assertValues(m, 1, 2, 3, 4, -5, 5, -7); m = matcher.findModule(null, OptionalParams.class, 1, 2, 3, 4); assertValues(m, 1, 2, 3, -4, -5, 4, -7); m = matcher.findModule(null, OptionalParams.class, 1, 2, 3); assertValues(m, 1, -2, 2, -4, -5, 3, -7); try { m = matcher.findModule(null, OptionalParams.class, 1, 2); fail("Expected IllegalArgumentException for 2 args"); } catch (final IllegalArgumentException exc) { // NB: Expected. } } // -- Helper methods -- private void assertValues(final Module m, final int a, final int b, final int c, final int d, final int e, final int f, final int result) { assertEquals(a, num(m.getInput("a"))); assertEquals(b, num(m.getInput("b"))); assertEquals(c, num(m.getInput("c"))); assertEquals(d, num(m.getInput("d"))); assertEquals(e, num(m.getInput("e"))); assertEquals(f, num(m.getInput("f"))); assertEquals(result, num(m.getOutput("result"))); } private int num(final Object o) { return (Integer) o; } // -- Helper classes -- /** A test {@link Op}. */ @Plugin(type = Op.class, name = "nan") public static class NaNOp extends AbstractInplaceFunction<DoubleType> { @Override public DoubleType compute(final DoubleType argument) { argument.set(Double.NaN); return argument; } } @Plugin(type = Op.class) public static class OptionalParams implements Op { @Parameter private int a = -1; @Parameter(required = false) private int b = -2; @Parameter private int c = -3; @Parameter(required = false) private int d = -4; @Parameter(required = false) private int e = -5; @Parameter private int f = -6; @Parameter(type = ItemIO.OUTPUT) private int result = -7; @Override public void run() { // NB: No action needed. } } }
package org.animotron.games.web; import org.animotron.ATest; import org.animotron.expression.JExpression; import org.animotron.statement.compare.WITH; import org.animotron.statement.operator.AN; import org.animotron.statement.operator.DEF; import org.animotron.statement.query.ANY; import org.animotron.statement.query.GET; import org.animotron.statement.relation.USE; import org.junit.Test; import static org.animotron.expression.JExpression._; import static org.animotron.expression.JExpression.value; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class HtmlTest extends ATest { @Test public void test_00() throws Throwable { testAnimo("def el \"<\" (id this el) \">\" (an get 2) \"</\" (id this el) \">\"."); testAnimo("def p el."); assertStringResult("p 'para'", "<p>para</p>"); } @Test public void test_01() throws Throwable { testAnimo("def el \"<\" (id this el) \">\" (an get 2) \"</\" (id this el) \">\"."); testAnimo("def ul el."); testAnimo("def li el."); assertStringResult("ul li 1", "<ul><li>1</li></ul>"); } @Test public void test_03() throws Throwable { testAnimo("def el \"<\" (id this el) \">\" (each (get 2) (an)) \"</\" (id this el) \">\"."); testAnimo("def ul el."); testAnimo("def li el."); assertStringResult("ul li 1", "<ul><li>1</li></ul>"); } }
package org.owasp.esapi.codecs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class CodecTest extends TestCase { private static final char[] EMPTY_CHAR_ARRAY = new char[0]; private static final Character LESS_THAN = Character.valueOf('<'); private static final Character SINGLE_QUOTE = Character.valueOf('\''); private HTMLEntityCodec htmlCodec = new HTMLEntityCodec(); private PercentCodec percentCodec = new PercentCodec(); private JavaScriptCodec javaScriptCodec = new JavaScriptCodec(); private VBScriptCodec vbScriptCodec = new VBScriptCodec(); private CSSCodec cssCodec = new CSSCodec(); private MySQLCodec mySQLCodecANSI = new MySQLCodec( MySQLCodec.ANSI_MODE ); private MySQLCodec mySQLCodecStandard = new MySQLCodec( MySQLCodec.MYSQL_MODE ); private OracleCodec oracleCodec = new OracleCodec(); private UnixCodec unixCodec = new UnixCodec(); private WindowsCodec windowsCodec = new WindowsCodec(); /** * Instantiates a new access reference map test. * * @param testName * the test name */ public CodecTest(String testName) { super(testName); } /** * {@inheritDoc} * @throws Exception */ protected void setUp() throws Exception { // none } /** * {@inheritDoc} * @throws Exception */ protected void tearDown() throws Exception { // none } /** * Suite. * * @return the test */ public static Test suite() { TestSuite suite = new TestSuite(CodecTest.class); return suite; } public void testHtmlEncode() { assertEquals( "test", htmlCodec.encode( EMPTY_CHAR_ARRAY, "test") ); } public void testPercentEncode() { assertEquals( "%3c", percentCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testJavaScriptEncode() { assertEquals( "\\x3C", javaScriptCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testVBScriptEncode() { assertEquals( "chrw(60)", vbScriptCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testCSSEncode() { assertEquals( "\\3c ", cssCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testMySQLANSCIEncode() { assertEquals( "\'\'", mySQLCodecANSI.encode(EMPTY_CHAR_ARRAY, "\'") ); } public void testMySQLStandardEncode() { assertEquals( "\\<", mySQLCodecStandard.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testOracleEncode() { assertEquals( "\'\'", oracleCodec.encode(EMPTY_CHAR_ARRAY, "\'") ); } public void testUnixEncode() { assertEquals( "\\<", unixCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testWindowsEncode() { assertEquals( "^<", windowsCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testHtmlEncodeChar() { assertEquals( "&lt;", htmlCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testPercentEncodeChar() { assertEquals( "%3c", percentCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testJavaScriptEncodeChar() { assertEquals( "\\x3C", javaScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testVBScriptEncodeChar() { assertEquals( "chrw(60)", vbScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testCSSEncodeChar() { assertEquals( "\\3c ", cssCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testMySQLANSIEncodeChar() { assertEquals( "\'\'", mySQLCodecANSI.encodeCharacter(EMPTY_CHAR_ARRAY, SINGLE_QUOTE)); } public void testMySQLStandardEncodeChar() { assertEquals( "\\<", mySQLCodecStandard.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testOracleEncodeChar() { assertEquals( "\'\'", oracleCodec.encodeCharacter(EMPTY_CHAR_ARRAY, SINGLE_QUOTE) ); } public void testUnixEncodeChar() { assertEquals( "\\<", unixCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testWindowsEncodeChar() { assertEquals( "^<", windowsCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testHtmlDecodeDecimalEntities() { assertEquals( "test!", htmlCodec.decode("&#116;&#101;&#115;&#116;!") ); } public void testHtmlDecodeHexEntitites() { assertEquals( "test!", htmlCodec.decode("&#x74;&#x65;&#x73;&#x74;!") ); } public void testHtmlDecodeInvalidAttribute() { assertEquals( "&jeff;", htmlCodec.decode("&jeff;") ); } public void testPercentDecode() { assertEquals( "<", percentCodec.decode("%3c") ); } public void testJavaScriptDecodeBackSlashHex() { assertEquals( "<", javaScriptCodec.decode("\\x3c") ); } public void testVBScriptDecode() { assertEquals( "<", vbScriptCodec.decode("\"<") ); } public void testCSSDecode() { assertEquals( "<", cssCodec.decode("\\<") ); } public void testMySQLANSIDecode() { assertEquals( "\'", mySQLCodecANSI.decode("\'\'") ); } public void testMySQLStandardDecode() { assertEquals( "<", mySQLCodecStandard.decode("\\<") ); } public void testOracleDecode() { assertEquals( "\'", oracleCodec.decode("\'\'") ); } public void testUnixDecode() { assertEquals( "<", unixCodec.decode("\\<") ); } public void testWindowsDecode() { assertEquals( "<", windowsCodec.decode("^<") ); } public void testHtmlDecodeCharLessThan() { assertEquals( LESS_THAN, htmlCodec.decodeCharacter(new PushbackString("&lt;")) ); } public void testPercentDecodeChar() { assertEquals( LESS_THAN, percentCodec.decodeCharacter(new PushbackString("%3c") )); } public void testJavaScriptDecodeCharBackSlashHex() { assertEquals( LESS_THAN, javaScriptCodec.decodeCharacter(new PushbackString("\\x3c") )); } public void testVBScriptDecodeChar() { assertEquals( LESS_THAN, vbScriptCodec.decodeCharacter(new PushbackString("\"<") )); } public void testCSSDecodeCharBackSlashHex() { assertEquals( LESS_THAN, cssCodec.decodeCharacter(new PushbackString("\\3c") )); } public void testMySQLANSIDecodCharQuoteQuote() { assertEquals( SINGLE_QUOTE, mySQLCodecANSI.decodeCharacter(new PushbackString("\'\'") )); } public void testMySQLStandardDecodeCharBackSlashLessThan() { assertEquals( LESS_THAN, mySQLCodecStandard.decodeCharacter(new PushbackString("\\<") )); } public void testOracleDecodeCharBackSlashLessThan() { assertEquals( SINGLE_QUOTE, oracleCodec.decodeCharacter(new PushbackString("\'\'") )); } public void testUnixDecodeCharBackSlashLessThan() { assertEquals( LESS_THAN, unixCodec.decodeCharacter(new PushbackString("\\<") )); } public void testWindowsDecodeCharCarrotLessThan() { assertEquals( LESS_THAN, windowsCodec.decodeCharacter(new PushbackString("^<") )); } }
package test.kalang.tool; import kalang.Script; import kalang.tool.KalangShell; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Kason Yang */ public class KalangShellTest { public KalangShellTest() { } @Test public void test(){ KalangShell shell = new KalangShell(); Script script = shell.parseScript("Test", "println(\"test\");", "Test.kl"); assertEquals(Script.SUCCESS, script.run()); } }
package ua.nykyforov.geoip; import com.maxmind.geoip2.record.Country; import com.sun.istack.internal.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ua.nykyforov.geoip.dbip.api.DbIpClient; import ua.nykyforov.geoip.dbip.api.GeoEntity; import ua.nykyforov.geoip.maxmind.MaxMindGeoService; import java.util.Objects; import java.util.concurrent.ThreadLocalRandom; import static ua.nykyforov.util.IOUtils.getResourceFile; /** * @author Serhii Nykyforov */ public class DbIpVsMaxMind { private static final Logger LOG = LoggerFactory.getLogger("Geo"); private static final int THRESHOLD = 1_000; private static final String UNKNOWN_COUNTRY = "Unknown"; private static MaxMindGeoService mmClient; private static DbIpClient dbIpClient; public static void main(String[] args) { dbIpClient = new DbIpClient(getResourceFile(Global.DB_IP_DATABASE_NAME)); mmClient = MaxMindGeoService.fromResource(Global.MAX_MIND_DATABASE_NAME); int cntOfCountriesKnownForMM = 0; int cntOfCountriesKnownForDbIp = 0; for (int i = 0; i < THRESHOLD; i++) { String ipAddress = genRandomIpAddress(); Country mmCountry = safelyGetCountryFromMaxMind(ipAddress); GeoEntity dbIpCountry = safelyGetCountryFromDbIp(ipAddress); String mmCountryName = mmCountry == null ? UNKNOWN_COUNTRY : mmCountry.getName(); String mmCountryCode = mmCountry == null ? UNKNOWN_COUNTRY : mmCountry.getIsoCode(); String dbIpCountryName = dbIpCountry == null ? UNKNOWN_COUNTRY : dbIpCountry.getCountry(); String dbIpCountryCode = dbIpCountry == null ? UNKNOWN_COUNTRY : dbIpCountry.getCountryCode(); if (isCountryDefined(mmCountryName)) { cntOfCountriesKnownForMM++; } if (isCountryDefined(dbIpCountryName)) { cntOfCountriesKnownForDbIp++; } if (!Objects.equals(mmCountryName, dbIpCountryName) && !Objects.equals(mmCountryCode, dbIpCountryCode)) { LOG.warn("{} maxMind: {}, dbIp: {}", ipAddress, mmCountryName, dbIpCountry); } } LOG.info("MaxMind knows countries: {} ({})", cntOfCountriesKnownForMM, THRESHOLD); LOG.info("DB-IP knows countries: {} ({})", cntOfCountriesKnownForDbIp, THRESHOLD); } @Nullable private static Country safelyGetCountryFromMaxMind(String ipAddress) { try { return mmClient.findCountryByIp(ipAddress); } catch (Exception ignored) { } return null; } @Nullable private static GeoEntity safelyGetCountryFromDbIp(String ipAddress) { try { return dbIpClient.lookup(ipAddress); } catch (Exception ignored) { } return null; } private static String genRandomIpAddress() { ThreadLocalRandom r = ThreadLocalRandom.current(); return String.valueOf(r.nextInt(0, 256)) + '.' + r.nextInt(0, 256) + '.' + r.nextInt(0, 256) + '.' + r.nextInt(0, 256); } private static boolean isCountryDefined(String country) { return country != null && !Objects.equals(country, UNKNOWN_COUNTRY); } }
package org.apache.jcs.access; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Enumeration; import java.util.StringTokenizer; import org.apache.jcs.access.exception.CacheException; import org.apache.jcs.engine.behavior.IElementAttributes; import org.apache.jcs.engine.ElementAttributes; import org.apache.jcs.engine.control.group.GroupCacheHub; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jcs.engine.control.event.TestElementEventHandler; /** * Allows the user to run common cache commands fromt he command line for a test * cache. * * @author <a href="mailto:asmuts@yahoo.com">Aaron Smuts</a> * @created January 15, 2002 */ public class TestCacheAccess { private final static Log log = LogFactory.getLog( TestCacheAccess.class ); static GroupCacheAccess cache_control = null; /** * Test harness. * * @param args The command line arguments */ public static void main( String[] args ) { try { try { //CacheManager cacheMgr = CacheManagerFactory.getInstance(); //CacheAttributes cattr = new CacheAttributes(); //cattr.setMaxObjects( 10 ); //cattr.setUseDisk( true ); //CacheAccess cache_control= CacheAccess.getAccess( "testCache" ); //cache_control= GroupCacheAccess.getGroupAccess( "testGroupCache" ); // start the local cache witht he appropriate props file GroupCacheHub.getInstance( args[0] ); cache_control = GroupCacheAccess.getGroupAccess( "testCache1" ); // not necessary if you don't set default element attributes try { cache_control.defineGroup( "gr" ); } catch ( CacheException ce ) { p( ce.toString() + " /n" + ce.getMessage() ); } try { cache_control.defineGroup( "gr2" ); } catch ( CacheException ce ) { p( ce.toString() + " /n" + ce.getMessage() ); } GroupCacheAccess cache_control2 = GroupCacheAccess.getGroupAccess( "testCache2" ); p( "cache_control = " + cache_control ); // process user input till done boolean notDone = true; String message = null; // wait to dispose BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); help(); while ( notDone ) { p( "enter command:" ); message = br.readLine(); if ( message.startsWith( "help" ) ) { help(); } // else // if ( message.startsWith( "removeLateralDirect" ) ) // removeLateralDirect( message ); else if ( message.startsWith( "getAttributeNames" ) ) { long n_start = System.currentTimeMillis(); String groupName = null; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { groupName = t.trim(); } } getAttributeNames( groupName ); long n_end = System.currentTimeMillis(); p( " } else if ( message.startsWith( "dispose" ) ) { cache_control.dispose(); notDone = false; System.exit( -1 ); } else // get multiple from a region if ( message.startsWith( "getm" ) ) { int num = 0; boolean show = true; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { try { num = Integer.parseInt( t.trim() ); } catch ( NumberFormatException nfe ) { p( t + "not a number" ); } } else if ( tcnt == 3 ) { show = new Boolean( t ).booleanValue(); } } if ( tcnt < 2 ) { p( "usage: get numbertoget show values[true|false]" ); } else { long n_start = System.currentTimeMillis(); for ( int n = 0; n < num; n++ ) { try { Object obj = cache_control.get( "key" + n ); if ( show && obj != null ) { p( obj.toString() ); } } catch ( Exception e ) { log.error( e ); } } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "getg" ) ) { String key = null; String group = null; boolean show = true; boolean auto = true; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { key = t.trim(); } else if ( tcnt == 3 ) { group = t.trim(); } else if ( tcnt == 4 ) { show = new Boolean( t ).booleanValue(); } if ( tcnt == 5 ) { auto = new Boolean( t ).booleanValue(); } } if ( tcnt < 2 ) { p( "usage: get key show values[true|false]" ); } else { long n_start = System.currentTimeMillis(); try { Object obj = cache_control.getFromGroup( key, group ); if ( show && obj != null ) { p( obj.toString() ); } } catch ( Exception e ) { log.error( e ); } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "getag" ) ) { // get auto from group int num = 0; String group = null; boolean show = true; boolean auto = true; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { num = Integer.parseInt( t.trim() ); } else if ( tcnt == 3 ) { group = t.trim(); } else if ( tcnt == 4 ) { show = new Boolean( t ).booleanValue(); } if ( tcnt == 5 ) { auto = new Boolean( t ).booleanValue(); } } if ( tcnt < 2 ) { p( "usage: get key show values[true|false]" ); } else { long n_start = System.currentTimeMillis(); try { for ( int a = 0; a < num; a++ ) { Object obj = cache_control.getFromGroup( "keygr" + a, group ); if ( show && obj != null ) { p( obj.toString() ); } } } catch ( Exception e ) { log.error( e ); } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "get" ) ) { // plain old get String key = null; boolean show = true; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { key = t.trim(); } else if ( tcnt == 3 ) { show = new Boolean( t ).booleanValue(); } } if ( tcnt < 2 ) { p( "usage: get key show values[true|false]" ); } else { long n_start = System.currentTimeMillis(); try { Object obj = cache_control.get( key ); if ( show && obj != null ) { p( obj.toString() ); } } catch ( Exception e ) { log.error( e ); } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "putg" ) ) { String group = null; String key = null; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { key = t.trim(); } else if ( tcnt == 3 ) { group = t.trim(); } } if ( tcnt < 3 ) { p( "usage: putg key group" ); } else { // IElementAttributes attrp = new ElementAttributes(); // attrp.setIsLateral(true); // attrp.setIsRemote(true); long n_start = System.currentTimeMillis(); cache_control.putInGroup( key, group, "data from putg ----asdfasfas-asfasfas-asfas in group " + group ); long n_end = System.currentTimeMillis(); p( " } } else // put automatically if ( message.startsWith( "putag" ) ) { String group = null; int num = 0; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { num = Integer.parseInt( t.trim() ); } else if ( tcnt == 3 ) { group = t.trim(); } } if ( tcnt < 3 ) { p( "usage: putag num group" ); } else { // IElementAttributes attrp = new ElementAttributes(); // attrp.setIsLateral(true); // attrp.setIsRemote(true); long n_start = System.currentTimeMillis(); for ( int a = 0; a < num; a++ ) { cache_control.putInGroup( "keygr" + a, group, "data " + a + " from putag ----asdfasfas-asfasfas-asfas in group " + group ); } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "putm" ) ) { String numS = message.substring( message.indexOf( " " ) + 1, message.length() ); int num = Integer.parseInt( numS.trim() ); if ( numS == null ) { p( "usage: putm numbertoput" ); } else { // IElementAttributes attrp = new ElementAttributes(); //attrp.setIsEternal(false); //attrp.setMaxLifeSeconds(30); // attrp.setIsLateral(true); // attrp.setIsRemote(true); long n_start = System.currentTimeMillis(); for ( int n = 0; n < num; n++ ) { cache_control.put( "key" + n, "data" + n + " put from ta = junk" ); } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "pute" ) ) { String numS = message.substring( message.indexOf( " " ) + 1, message.length() ); int num = Integer.parseInt( numS.trim() ); if ( numS == null ) { p( "usage: putme numbertoput" ); } else { // IElementAttributes attrp = new ElementAttributes(); //attrp.setIsEternal(false); //attrp.setMaxLifeSeconds(30); // attrp.setIsLateral(true); // attrp.setIsRemote(true); long n_start = System.currentTimeMillis(); for ( int n = 0; n < num; n++ ) { IElementAttributes attrp = cache_control.getElementAttributes(); TestElementEventHandler hand = new TestElementEventHandler(); attrp.addElementEventHandler( hand ); cache_control.put( "key" + n, "data" + n + " put from ta = junk", attrp ); } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "put" ) ) { String key = null; String val = null; StringTokenizer toke = new StringTokenizer( message ); int tcnt = 0; while ( toke.hasMoreElements() ) { tcnt++; String t = ( String ) toke.nextElement(); if ( tcnt == 2 ) { key = t.trim(); } else if ( tcnt == 3 ) { val = t.trim(); } } if ( tcnt < 3 ) { p( "usage: put key val" ); } else { // IElementAttributes attrp = new ElementAttributes(); // attrp.setIsLateral(true); // attrp.setIsRemote(true); long n_start = System.currentTimeMillis(); // cache_control.put( key, val, attrp.copy() ); cache_control.put( key, val ); long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "remove" ) ) { String key = message.substring( message.indexOf( " " ) + 1, message.length() ); cache_control.remove( key ); p( "removed " + key ); } else if ( message.startsWith( "deattr" ) ) { IElementAttributes ae = cache_control.getElementAttributes( ); p( "Default IElementAttributes " + ae ); } else if ( message.startsWith( "cloneattr" ) ) { String numS = message.substring( message.indexOf( " " ) + 1, message.length() ); int num = Integer.parseInt( numS.trim() ); if ( numS == null ) { p( "usage: put numbertoput" ); } else { IElementAttributes attrp = new ElementAttributes(); long n_start = System.currentTimeMillis(); for ( int n = 0; n < num; n++ ) { attrp.copy(); } long n_end = System.currentTimeMillis(); p( " } } else if ( message.startsWith( "switch" ) ) { String numS = message.substring( message.indexOf( " " ) + 1, message.length() ); try { int num = Integer.parseInt( numS.trim() ); } catch ( Exception e ) { p( "usage: switch number" ); p( " 1 == testCache1" ); } if ( numS == null ) { p( "usage: switch number" ); p( " 1 == testCache1" ); } else { cache_control = GroupCacheAccess.getGroupAccess( "testCache" + numS ); p( "switched to cache = " + "testCache" + numS ); p( cache_control.toString() ); } } } } catch ( Exception e ) { p( e.toString() ); e.printStackTrace( System.out ); } } catch ( Exception e ) { p( e.toString() ); e.printStackTrace( System.out ); } } // end main /** Description of the Method */ public static void p( String s ) { System.out.println( s ); } /** Description of the Method */ public static void help() { p( "\n\n\n\n" ); p( "type 'dispose' to dispose of the cache" ); p( "type 'getm num show[false|true]' to get num automatically from a region" ); p( "type 'putm num' to put num automatically to a region" ); p( "type 'remove key' to remove" ); p( "type 'get key show' to get" ); p( "type 'getg key group show' to get" ); p( "type 'getag num group show' to get automatically from a group" ); p( "type 'getAttributeNames group' to get a list og the group elements" ); p( "type 'putg key group val' to put" ); p( "type 'putag num group' to put automatically from a group" ); p( "type 'put key val' to put" ); p( "type 'stats' to get stats" ); p( "type 'deattr' to get teh default element attributes" ); p( "type 'cloneattr num' to clone attr" ); // p( "type 'removeLateralDirect key' to remove lateral" ); p( "type 'switch number' to switch to testCache[number], 1 == testCache1" ); p( "type 'help' for commands" ); } // /** // * Description of the Method // * // */ // public static void removeLateralDirect( String message ) // String key = null; // StringTokenizer toke = new StringTokenizer( message ); // int tcnt = 0; // while ( toke.hasMoreElements() ) // tcnt++; // String t = ( String ) toke.nextElement(); // if ( tcnt == 2 ) // key = t.trim(); // if ( tcnt < 2 ) // key = "ALL"; // cache_control.removeLateralDirect( key ); // p( "called delete multicast for key " + key ); // end help /** Gets the attributeNames attribute of the TestCacheAccess class */ static void getAttributeNames( String groupName ) { Enumeration enum = cache_control.getAttributeNames( groupName ); p( "enum = " + enum ); while ( enum.hasMoreElements() ) { p( "=" + ( String ) enum.nextElement() ); } } } // end test
package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for DateTime. * * @author Stephen Colebourne */ public class TestDateTime_Properties extends TestCase { // Summer time: // 1968-02-18 to 1971-10-31 - +01:00 all year round! // 1972 UK Mar 19 - Oct 29 // 1973 UK Mar 18 - Oct 28 private static final DateTimeZone PARIS = DateTimeZone.getInstance("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.getInstance("Europe/London"); // 1970-06-09 private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 1970-04-05 private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 1971-05-06 private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTime_Properties.class); } public TestDateTime_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); Locale.setDefault(locale); zone = null; } public void testPropertyGetEra() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().era(), test.era().getField()); assertEquals("era", test.era().getName()); assertEquals("Property[era]", test.era().toString()); assertSame(test, test.era().getReadableInstant()); assertSame(test, test.era().getDateTime()); assertEquals(1, test.era().get()); assertEquals("AD", test.era().getAsText()); assertEquals("ap. J.-C.", test.era().getAsText(Locale.FRENCH)); assertEquals("AD", test.era().getAsShortText()); assertEquals("ap. J.-C.", test.era().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().eras(), test.era().getDurationField()); assertEquals(null, test.era().getRangeDurationField()); assertEquals(2, test.era().getMaximumTextLength(null)); assertEquals(9, test.era().getMaximumTextLength(Locale.FRENCH)); assertEquals(2, test.era().getMaximumShortTextLength(null)); assertEquals(9, test.era().getMaximumShortTextLength(Locale.FRENCH)); } public void testPropertyGetYearOfEra() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().yearOfEra(), test.yearOfEra().getField()); assertEquals("yearOfEra", test.yearOfEra().getName()); assertEquals("Property[yearOfEra]", test.yearOfEra().toString()); assertSame(test, test.yearOfEra().getReadableInstant()); assertSame(test, test.yearOfEra().getDateTime()); assertEquals(1972, test.yearOfEra().get()); assertEquals("1972", test.yearOfEra().getAsText()); assertEquals("1972", test.yearOfEra().getAsText(Locale.FRENCH)); assertEquals("1972", test.yearOfEra().getAsShortText()); assertEquals("1972", test.yearOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfEra().getDurationField()); assertEquals(null, test.yearOfEra().getRangeDurationField()); assertEquals(9, test.yearOfEra().getMaximumTextLength(null)); assertEquals(9, test.yearOfEra().getMaximumShortTextLength(null)); } public void testPropertyGetCenturyOfEra() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().centuryOfEra(), test.centuryOfEra().getField()); assertEquals("centuryOfEra", test.centuryOfEra().getName()); assertEquals("Property[centuryOfEra]", test.centuryOfEra().toString()); assertSame(test, test.centuryOfEra().getReadableInstant()); assertSame(test, test.centuryOfEra().getDateTime()); assertEquals(19, test.centuryOfEra().get()); assertEquals("19", test.centuryOfEra().getAsText()); assertEquals("19", test.centuryOfEra().getAsText(Locale.FRENCH)); assertEquals("19", test.centuryOfEra().getAsShortText()); assertEquals("19", test.centuryOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().centuries(), test.centuryOfEra().getDurationField()); assertEquals(null, test.centuryOfEra().getRangeDurationField()); assertEquals(7, test.centuryOfEra().getMaximumTextLength(null)); assertEquals(7, test.centuryOfEra().getMaximumShortTextLength(null)); } public void testPropertyGetYearOfCentury() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().yearOfCentury(), test.yearOfCentury().getField()); assertEquals("yearOfCentury", test.yearOfCentury().getName()); assertEquals("Property[yearOfCentury]", test.yearOfCentury().toString()); assertSame(test, test.yearOfCentury().getReadableInstant()); assertSame(test, test.yearOfCentury().getDateTime()); assertEquals(72, test.yearOfCentury().get()); assertEquals("72", test.yearOfCentury().getAsText()); assertEquals("72", test.yearOfCentury().getAsText(Locale.FRENCH)); assertEquals("72", test.yearOfCentury().getAsShortText()); assertEquals("72", test.yearOfCentury().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfCentury().getDurationField()); assertEquals(test.getChronology().centuries(), test.yearOfCentury().getRangeDurationField()); assertEquals(2, test.yearOfCentury().getMaximumTextLength(null)); assertEquals(2, test.yearOfCentury().getMaximumShortTextLength(null)); } public void testPropertyGetYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertSame(test, test.year().getReadableInstant()); assertSame(test, test.year().getDateTime()); assertEquals(1972, test.year().get()); assertEquals("1972", test.year().getAsText()); assertEquals("1972", test.year().getAsText(Locale.FRENCH)); assertEquals("1972", test.year().getAsShortText()); assertEquals("1972", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292277023, test.year().getMaximumValue()); assertEquals(292277023, test.year().getMaximumValueOverall()); } public void testPropertyLeapYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertEquals(true, test.year().isLeap()); assertEquals(1, test.year().getLeapAmount()); assertEquals(test.getChronology().days(), test.year().getLeapDurationField()); test = new DateTime(1971, 6, 9, 0, 0, 0, 0); assertEquals(false, test.year().isLeap()); assertEquals(0, test.year().getLeapAmount()); assertEquals(test.getChronology().days(), test.year().getLeapDurationField()); } public void testPropertyAddYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().addToCopy(9); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1981-06-09T00:00:00.000+01:00", copy.toString()); copy = test.year().addToCopy(0); assertEquals("1972-06-09T00:00:00.000+01:00", copy.toString()); copy = test.year().addToCopy(292277023 - 1972); assertEquals(292277023, copy.getYear()); try { test.year().addToCopy(292277023 - 1972 + 1); fail(); } catch (IllegalArgumentException ex) {} copy = test.year().addToCopy(-1972); assertEquals(0, copy.getYear()); copy = test.year().addToCopy(-1973); assertEquals(-1, copy.getYear()); try { test.year().addToCopy(-292275054 - 1972 - 1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyAddWrapFieldYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().addWrapFieldToCopy(9); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1981-06-09T00:00:00.000+01:00", copy.toString()); copy = test.year().addWrapFieldToCopy(0); assertEquals(1972, copy.getYear()); copy = test.year().addWrapFieldToCopy(292277023 - 1972 + 1); assertEquals(-292275054, copy.getYear()); copy = test.year().addWrapFieldToCopy(-292275054 - 1972 - 1); assertEquals(292277023, copy.getYear()); } public void testPropertySetYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().setCopy(1960); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1960-06-09T00:00:00.000+01:00", copy.toString()); } public void testPropertySetTextYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().setCopy("1960"); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1960-06-09T00:00:00.000+01:00", copy.toString()); } public void testPropertyCompareToYear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.year().compareTo(test2) < 0); assertEquals(true, test2.year().compareTo(test1) > 0); assertEquals(true, test1.year().compareTo(test1) == 0); try { test1.year().compareTo(null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyGetMonthOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getReadableInstant()); assertSame(test, test.monthOfYear().getDateTime()); assertEquals(6, test.monthOfYear().get()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new DateTime(1972, 7, 9, 0, 0, 0, 0); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyLeapMonthOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertEquals(false, test.monthOfYear().isLeap()); assertEquals(0, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); test = new DateTime(1972, 2, 9, 0, 0, 0, 0); assertEquals(true, test.monthOfYear().isLeap()); assertEquals(1, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); test = new DateTime(1971, 6, 9, 0, 0, 0, 0); assertEquals(false, test.monthOfYear().isLeap()); assertEquals(0, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); test = new DateTime(1971, 2, 9, 0, 0, 0, 0); assertEquals(false, test.monthOfYear().isLeap()); assertEquals(0, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); } public void testPropertyAddMonthOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().addToCopy(6); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-12-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(7); assertEquals("1973-01-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(-5); assertEquals("1972-01-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(-6); assertEquals("1971-12-09T00:00:00.000Z", copy.toString()); test = new DateTime(1972, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addToCopy(1); assertEquals("1972-01-31T00:00:00.000Z", test.toString()); assertEquals("1972-02-29T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(2); assertEquals("1972-03-31T00:00:00.000+01:00", copy.toString()); copy = test.monthOfYear().addToCopy(3); assertEquals("1972-04-30T00:00:00.000+01:00", copy.toString()); test = new DateTime(1971, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addToCopy(1); assertEquals("1971-02-28T00:00:00.000+01:00", copy.toString()); } public void testPropertyAddWrapFieldMonthOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().addWrapFieldToCopy(4); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-10-09T00:00:00.000+01:00", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(8); assertEquals("1972-02-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(-8); assertEquals("1972-10-09T00:00:00.000+01:00", copy.toString()); test = new DateTime(1972, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addWrapFieldToCopy(1); assertEquals("1972-01-31T00:00:00.000Z", test.toString()); assertEquals("1972-02-29T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(2); assertEquals("1972-03-31T00:00:00.000+01:00", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(3); assertEquals("1972-04-30T00:00:00.000+01:00", copy.toString()); test = new DateTime(1973, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addWrapFieldToCopy(1); assertEquals("1973-01-31T00:00:00.000Z", test.toString()); assertEquals("1973-02-28T00:00:00.000Z", copy.toString()); } public void testPropertySetMonthOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().setCopy(12); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-12-09T00:00:00.000Z", copy.toString()); test = new DateTime(1972, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().setCopy(2); assertEquals("1972-02-29T00:00:00.000Z", copy.toString()); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMonthOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().setCopy("12"); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-12-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().setCopy("December"); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-12-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().setCopy("Dec"); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-12-09T00:00:00.000Z", copy.toString()); } public void testPropertyCompareToMonthOfYear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyGetDayOfMonth() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertSame(test, test.dayOfMonth().getReadableInstant()); assertSame(test, test.dayOfMonth().getDateTime()); assertEquals(9, test.dayOfMonth().get()); assertEquals("9", test.dayOfMonth().getAsText()); assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("9", test.dayOfMonth().getAsShortText()); assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); assertEquals(false, test.dayOfMonth().isLeap()); assertEquals(0, test.dayOfMonth().getLeapAmount()); assertEquals(null, test.dayOfMonth().getLeapDurationField()); } public void testPropertyGetMaxMinValuesDayOfMonth() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); test = new DateTime(1972, 7, 9, 0, 0, 0, 0); assertEquals(31, test.dayOfMonth().getMaximumValue()); test = new DateTime(1972, 2, 9, 0, 0, 0, 0); assertEquals(29, test.dayOfMonth().getMaximumValue()); test = new DateTime(1971, 2, 9, 0, 0, 0, 0); assertEquals(28, test.dayOfMonth().getMaximumValue()); } public void testPropertyAddDayOfMonth() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().addToCopy(9); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-18T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(21); assertEquals("1972-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(22); assertEquals("1972-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(22 + 30); assertEquals("1972-07-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(22 + 31); assertEquals("1972-08-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("1972-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfMonth().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("1973-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfMonth().addToCopy(-8); assertEquals("1972-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(-9); assertEquals("1972-05-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); assertEquals("1972-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfMonth().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); assertEquals("1971-12-31T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldDayOfMonth() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().addWrapFieldToCopy(21); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(22); assertEquals("1972-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(-12); assertEquals("1972-06-27T00:00:00.000+01:00", copy.toString()); test = new DateTime(1972, 7, 9, 0, 0, 0, 0); copy = test.dayOfMonth().addWrapFieldToCopy(21); assertEquals("1972-07-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(22); assertEquals("1972-07-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(23); assertEquals("1972-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(-12); assertEquals("1972-07-28T00:00:00.000+01:00", copy.toString()); } public void testPropertySetDayOfMonth() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().setCopy(12); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-12T00:00:00.000+01:00", copy.toString()); try { test.dayOfMonth().setCopy(31); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfMonth().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDayOfMonth() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().setCopy("12"); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-12T00:00:00.000+01:00", copy.toString()); } public void testPropertyCompareToDayOfMonth() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyGetDayOfYear() { // 31+29+31+30+31+9 = 161 DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfYear(), test.dayOfYear().getField()); assertEquals("dayOfYear", test.dayOfYear().getName()); assertEquals("Property[dayOfYear]", test.dayOfYear().toString()); assertSame(test, test.dayOfYear().getReadableInstant()); assertSame(test, test.dayOfYear().getDateTime()); assertEquals(161, test.dayOfYear().get()); assertEquals("161", test.dayOfYear().getAsText()); assertEquals("161", test.dayOfYear().getAsText(Locale.FRENCH)); assertEquals("161", test.dayOfYear().getAsShortText()); assertEquals("161", test.dayOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.dayOfYear().getRangeDurationField()); assertEquals(3, test.dayOfYear().getMaximumTextLength(null)); assertEquals(3, test.dayOfYear().getMaximumShortTextLength(null)); assertEquals(false, test.dayOfYear().isLeap()); assertEquals(0, test.dayOfYear().getLeapAmount()); assertEquals(null, test.dayOfYear().getLeapDurationField()); } public void testPropertyGetMaxMinValuesDayOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertEquals(1, test.dayOfYear().getMinimumValue()); assertEquals(1, test.dayOfYear().getMinimumValueOverall()); assertEquals(366, test.dayOfYear().getMaximumValue()); assertEquals(366, test.dayOfYear().getMaximumValueOverall()); test = new DateTime(1970, 6, 9, 0, 0, 0, 0); assertEquals(365, test.dayOfYear().getMaximumValue()); assertEquals(366, test.dayOfYear().getMaximumValueOverall()); } public void testPropertyAddDayOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().addToCopy(9); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-18T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(21); assertEquals("1972-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(22); assertEquals("1972-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("1972-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("1973-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addToCopy(-8); assertEquals("1972-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(-9); assertEquals("1972-05-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); assertEquals("1972-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); assertEquals("1971-12-31T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldDayOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().addWrapFieldToCopy(21); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(22); assertEquals("1972-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(-12); assertEquals("1972-05-28T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(205); assertEquals("1972-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(206); assertEquals("1972-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(-160); assertEquals("1972-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(-161); assertEquals("1972-12-31T00:00:00.000Z", copy.toString()); } public void testPropertySetDayOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().setCopy(12); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-01-12T00:00:00.000Z", copy.toString()); try { test.dayOfYear().setCopy(367); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDayOfYear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().setCopy("12"); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-01-12T00:00:00.000Z", copy.toString()); } public void testPropertyCompareToDayOfYear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfYear().compareTo(test2) < 0); assertEquals(true, test2.dayOfYear().compareTo(test1) > 0); assertEquals(true, test1.dayOfYear().compareTo(test1) == 0); try { test1.dayOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfYear().compareTo(dt2) < 0); assertEquals(true, test2.dayOfYear().compareTo(dt1) > 0); assertEquals(true, test1.dayOfYear().compareTo(dt1) == 0); try { test1.dayOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyGetWeekOfWeekyear() { // 1970-01-01 = Thu // 1970-12-31 = Thu (+364 days) // 1971-12-30 = Thu (+364 days) // 1972-01-03 = Mon W1 // 1972-01-31 = Mon (+28 days) W5 // 1972-02-28 = Mon (+28 days) W9 // 1972-03-27 = Mon (+28 days) W13 // 1972-04-24 = Mon (+28 days) W17 // 1972-05-23 = Mon (+28 days) W21 // 1972-06-05 = Mon (+14 days) W23 // 1972-06-09 = Fri // 1972-12-25 = Mon W52 // 1973-01-01 = Mon W1 DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().weekOfWeekyear(), test.weekOfWeekyear().getField()); assertEquals("weekOfWeekyear", test.weekOfWeekyear().getName()); assertEquals("Property[weekOfWeekyear]", test.weekOfWeekyear().toString()); assertSame(test, test.weekOfWeekyear().getReadableInstant()); assertSame(test, test.weekOfWeekyear().getDateTime()); assertEquals(23, test.weekOfWeekyear().get()); assertEquals("23", test.weekOfWeekyear().getAsText()); assertEquals("23", test.weekOfWeekyear().getAsText(Locale.FRENCH)); assertEquals("23", test.weekOfWeekyear().getAsShortText()); assertEquals("23", test.weekOfWeekyear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().weeks(), test.weekOfWeekyear().getDurationField()); assertEquals(test.getChronology().weekyears(), test.weekOfWeekyear().getRangeDurationField()); assertEquals(2, test.weekOfWeekyear().getMaximumTextLength(null)); assertEquals(2, test.weekOfWeekyear().getMaximumShortTextLength(null)); assertEquals(false, test.weekOfWeekyear().isLeap()); assertEquals(0, test.weekOfWeekyear().getLeapAmount()); assertEquals(null, test.weekOfWeekyear().getLeapDurationField()); } public void testPropertyGetMaxMinValuesWeekOfWeekyear() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertEquals(1, test.weekOfWeekyear().getMinimumValue()); assertEquals(1, test.weekOfWeekyear().getMinimumValueOverall()); assertEquals(52, test.weekOfWeekyear().getMaximumValue()); assertEquals(53, test.weekOfWeekyear().getMaximumValueOverall()); test = new DateTime(1970, 6, 9, 0, 0, 0, 0); assertEquals(53, test.weekOfWeekyear().getMaximumValue()); assertEquals(53, test.weekOfWeekyear().getMaximumValueOverall()); } public void testPropertyAddWeekOfWeekyear() { DateTime test = new DateTime(1972, 6, 5, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().addToCopy(1); assertEquals("1972-06-05T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-12T00:00:00.000+01:00", copy.toString()); copy = test.weekOfWeekyear().addToCopy(29); assertEquals("1972-12-25T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addToCopy(30); assertEquals("1973-01-01T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addToCopy(-22); assertEquals("1972-01-03T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addToCopy(-23); assertEquals("1971-12-27T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldWeekOfWeekyear() { DateTime test = new DateTime(1972, 6, 5, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().addWrapFieldToCopy(1); assertEquals("1972-06-05T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-12T00:00:00.000+01:00", copy.toString()); copy = test.weekOfWeekyear().addWrapFieldToCopy(29); assertEquals("1972-12-25T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addWrapFieldToCopy(30); assertEquals("1972-01-03T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addWrapFieldToCopy(-23); assertEquals("1972-12-25T00:00:00.000Z", copy.toString()); } public void testPropertySetWeekOfWeekyear() { DateTime test = new DateTime(1972, 6, 5, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().setCopy(4); assertEquals("1972-06-05T00:00:00.000+01:00", test.toString()); assertEquals("1972-01-24T00:00:00.000Z", copy.toString()); try { test.weekOfWeekyear().setCopy(53); fail(); } catch (IllegalArgumentException ex) {} try { test.weekOfWeekyear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextWeekOfWeekyear() { DateTime test = new DateTime(1972, 6, 5, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().setCopy("4"); assertEquals("1972-06-05T00:00:00.000+01:00", test.toString()); assertEquals("1972-01-24T00:00:00.000Z", copy.toString()); } public void testPropertyCompareToWeekOfWeekyear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.weekOfWeekyear().compareTo(test2) < 0); assertEquals(true, test2.weekOfWeekyear().compareTo(test1) > 0); assertEquals(true, test1.weekOfWeekyear().compareTo(test1) == 0); try { test1.weekOfWeekyear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.weekOfWeekyear().compareTo(dt2) < 0); assertEquals(true, test2.weekOfWeekyear().compareTo(dt1) > 0); assertEquals(true, test1.weekOfWeekyear().compareTo(dt1) == 0); try { test1.weekOfWeekyear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyGetDayOfWeek() { // 1970-01-01 = Thu // 1970-12-31 = Thu (+364 days) // 1971-12-30 = Thu (+364 days) // 1972-01-03 = Mon // 1972-01-31 = Mon (+28 days) // 1972-02-28 = Mon (+28 days) // 1972-03-27 = Mon (+28 days) // 1972-04-24 = Mon (+28 days) // 1972-05-23 = Mon (+28 days) // 1972-06-05 = Mon (+14 days) // 1972-06-09 = Fri DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfWeek(), test.dayOfWeek().getField()); assertEquals("dayOfWeek", test.dayOfWeek().getName()); assertEquals("Property[dayOfWeek]", test.dayOfWeek().toString()); assertSame(test, test.dayOfWeek().getReadableInstant()); assertSame(test, test.dayOfWeek().getDateTime()); assertEquals(5, test.dayOfWeek().get()); assertEquals("Friday", test.dayOfWeek().getAsText()); assertEquals("vendredi", test.dayOfWeek().getAsText(Locale.FRENCH)); assertEquals("Fri", test.dayOfWeek().getAsShortText()); assertEquals("ven.", test.dayOfWeek().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfWeek().getDurationField()); assertEquals(test.getChronology().weeks(), test.dayOfWeek().getRangeDurationField()); assertEquals(9, test.dayOfWeek().getMaximumTextLength(null)); assertEquals(8, test.dayOfWeek().getMaximumTextLength(Locale.FRENCH)); assertEquals(3, test.dayOfWeek().getMaximumShortTextLength(null)); assertEquals(4, test.dayOfWeek().getMaximumShortTextLength(Locale.FRENCH)); assertEquals(1, test.dayOfWeek().getMinimumValue()); assertEquals(1, test.dayOfWeek().getMinimumValueOverall()); assertEquals(7, test.dayOfWeek().getMaximumValue()); assertEquals(7, test.dayOfWeek().getMaximumValueOverall()); assertEquals(false, test.dayOfWeek().isLeap()); assertEquals(0, test.dayOfWeek().getLeapAmount()); assertEquals(null, test.dayOfWeek().getLeapDurationField()); } public void testPropertyAddDayOfWeek() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().addToCopy(1); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-10T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(21); assertEquals("1972-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(22); assertEquals("1972-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("1972-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfWeek().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("1973-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfWeek().addToCopy(-8); assertEquals("1972-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(-9); assertEquals("1972-05-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); assertEquals("1972-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfWeek().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); assertEquals("1971-12-31T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldDayOfWeek() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().addWrapFieldToCopy(1); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-10T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addWrapFieldToCopy(3); assertEquals("1972-06-05T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addWrapFieldToCopy(-12); assertEquals("1972-06-11T00:00:00.000+01:00", copy.toString()); test = new DateTime(1972, 6, 2, 0, 0, 0, 0); copy = test.dayOfWeek().addWrapFieldToCopy(3); assertEquals("1972-06-02T00:00:00.000+01:00", test.toString()); assertEquals("1972-05-29T00:00:00.000+01:00", copy.toString()); } public void testPropertySetDayOfWeek() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().setCopy(4); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-08T00:00:00.000+01:00", copy.toString()); try { test.dayOfWeek().setCopy(8); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfWeek().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDayOfWeek() { DateTime test = new DateTime(1972, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().setCopy("4"); assertEquals("1972-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1972-06-08T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().setCopy("Mon"); assertEquals("1972-06-05T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().setCopy("Tuesday"); assertEquals("1972-06-06T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().setCopy("lundi", Locale.FRENCH); assertEquals("1972-06-05T00:00:00.000+01:00", copy.toString()); } public void testPropertyCompareToDayOfWeek() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfWeek().compareTo(test2) < 0); assertEquals(true, test2.dayOfWeek().compareTo(test1) > 0); assertEquals(true, test1.dayOfWeek().compareTo(test1) == 0); try { test1.dayOfWeek().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfWeek().compareTo(dt2) < 0); assertEquals(true, test2.dayOfWeek().compareTo(dt1) > 0); assertEquals(true, test1.dayOfWeek().compareTo(dt1) == 0); try { test1.dayOfWeek().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hu.sch.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Transient; /** * * @author hege */ @Embeddable public class Szemeszter implements Serializable { protected String id; public Szemeszter() { id = "200020011"; } public Szemeszter(Integer elsoEv, Integer masodikEv, boolean osziFelev) { if (elsoEv > 2030 || elsoEv < 2000 || masodikEv > 2030 || masodikEv < 2000) { throw new IllegalArgumentException("Az évnek 2000 és 2030 között kell lennie"); } setId(elsoEv.toString() + masodikEv.toString() + (osziFelev ? "1" : "2")); } @Column(name = "semester", length = 9, columnDefinition = "character(9)", nullable = false) public String getId() { return id; } public void setId(String id) { this.id = id; } @Transient public boolean isOsziFelev() { Long sem = Long.parseLong(id); return Long.lowestOneBit(sem) == 1; } public void setOsziFelev(boolean osziFelev) { setId(getElsoEv().toString() + getMasodikEv().toString() + (osziFelev ? "1" : "2")); } @Transient public Integer getElsoEv() { return Integer.parseInt(id.substring(0, 4)); } public void setElsoEv(Integer elsoEv) { if (elsoEv > 2030 || elsoEv < 2000) { throw new IllegalArgumentException("Az évnek 2000 és 2030 között kell lennie"); } setId(elsoEv.toString() + getMasodikEv().toString() + (isOsziFelev() ? "1" : "2")); } @Transient public Integer getMasodikEv() { return Integer.parseInt(id.substring(4, 8)); } public void setMasodikEv(Integer masodikEv) { if (masodikEv > 2030 || masodikEv < 2000) { throw new IllegalArgumentException("Az évnek 2000 és 2030 között kell lennie"); } setId(getElsoEv() + masodikEv.toString() + (isOsziFelev() ? "1" : "2")); } @Override public String toString() { StringBuilder b = new StringBuilder(getElsoEv().toString()); b.append("/"); b.append(getMasodikEv().toString()); b.append(" "); b.append(isOsziFelev() ? "ősz" : "tavasz"); return b.toString(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Szemeszter other = (Szemeszter) obj; if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 47 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } }
package com.tpcstld.twozerogame; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.View; import java.util.ArrayList; public class MainView extends View { //Intenal Constants static final int BASE_ANIMATION_TIME = 100000000; private static final float MERGING_ACCELERATION = (float) -0.5; private static final float INITIAL_VELOCITY = (1 - MERGING_ACCELERATION) / 4; public final int numCellTypes = 21; private final BitmapDrawable[] bitmapCell = new BitmapDrawable[numCellTypes]; public final MainGame game; //Internal variables private final Paint paint = new Paint(); public boolean hasSaveState = false; public boolean continueButtonEnabled = false; public int startingX; public int startingY; public int endingX; public int endingY; //Icon variables public int sYIcons; public int sXNewGame; public int sXUndo; public int iconSize; //Misc boolean refreshLastTime = true; //Timing private long lastFPSTime = System.nanoTime(); //Text private float titleTextSize; private float bodyTextSize; private float headerTextSize; private float instructionsTextSize; private float gameOverTextSize; //Layout variables private int cellSize = 0; private float textSize = 0; private float cellTextSize = 0; private int gridWidth = 0; private int textPaddingSize; private int iconPaddingSize; //Assets private Drawable backgroundRectangle; private Drawable lightUpRectangle; private Drawable fadeRectangle; private Bitmap background = null; private BitmapDrawable loseGameOverlay; private BitmapDrawable winGameContinueOverlay; private BitmapDrawable winGameFinalOverlay; //Text variables private int sYAll; private int titleStartYAll; private int bodyStartYAll; private int eYAll; private int titleWidthHighScore; private int titleWidthScore; public MainView(Context context) { super(context); Resources resources = context.getResources(); //Loading resources game = new MainGame(context, this); try { //Getting assets backgroundRectangle = resources.getDrawable(R.drawable.background_rectangle); lightUpRectangle = resources.getDrawable(R.drawable.light_up_rectangle); fadeRectangle = resources.getDrawable(R.drawable.fade_rectangle); this.setBackgroundColor(resources.getColor(R.color.background)); Typeface font = Typeface.createFromAsset(resources.getAssets(), "ClearSans-Bold.ttf"); paint.setTypeface(font); paint.setAntiAlias(true); } catch (Exception e) { System.out.println("Error getting assets?"); } setOnTouchListener(new InputListener(this)); game.newGame(); } private static int log2(int n) { if (n <= 0) throw new IllegalArgumentException(); return 31 - Integer.numberOfLeadingZeros(n); } @Override public void onDraw(Canvas canvas) { //Reset the transparency of the screen canvas.drawBitmap(background, 0, 0, paint); drawScoreText(canvas); if (!game.isActive() && !game.aGrid.isAnimationActive()) { drawNewGameButton(canvas, true); } drawCells(canvas); if (!game.isActive()) { drawEndGameState(canvas); } if (!game.canContinue()) { drawEndlessText(canvas); } //Refresh the screen if there is still an animation running if (game.aGrid.isAnimationActive()) { invalidate(startingX, startingY, endingX, endingY); tick(); //Refresh one last time on game end. } else if (!game.isActive() && refreshLastTime) { invalidate(); refreshLastTime = false; } } @Override protected void onSizeChanged(int width, int height, int oldw, int oldh) { super.onSizeChanged(width, height, oldw, oldh); getLayout(width, height); createBitmapCells(); createBackgroundBitmap(width, height); createOverlays(); } private void drawDrawable(Canvas canvas, Drawable draw, int startingX, int startingY, int endingX, int endingY) { draw.setBounds(startingX, startingY, endingX, endingY); draw.draw(canvas); } private void drawCellText(Canvas canvas, int value) { int textShiftY = centerText(); if (value >= 8) { paint.setColor(getResources().getColor(R.color.text_white)); } else { paint.setColor(getResources().getColor(R.color.text_black)); } canvas.drawText("" + value, 1, 1 - textShiftY, paint); } private void drawScoreText(Canvas canvas) { //Drawing the score text: Ver 2 paint.setTextSize(bodyTextSize); paint.setTextAlign(Paint.Align.CENTER); int bodyWidthHighScore = (int) (paint.measureText("" + game.highScore)); int bodyWidthScore = (int) (paint.measureText("" + game.score)); int textWidthHighScore = Math.max(titleWidthHighScore, bodyWidthHighScore) + textPaddingSize * 2; int textWidthScore = Math.max(titleWidthScore, bodyWidthScore) + textPaddingSize * 2; int textMiddleHighScore = textWidthHighScore / 2; int textMiddleScore = textWidthScore / 2; int eXHighScore = endingX; int sXHighScore = eXHighScore - textWidthHighScore; int eXScore = sXHighScore - textPaddingSize; int sXScore = eXScore - textWidthScore; //Outputting high-scores box backgroundRectangle.setBounds(sXHighScore, sYAll, eXHighScore, eYAll); backgroundRectangle.draw(canvas); paint.setTextSize(titleTextSize); paint.setColor(getResources().getColor(R.color.text_brown)); canvas.drawText(getResources().getString(R.string.high_score), sXHighScore + textMiddleHighScore, titleStartYAll, paint); paint.setTextSize(bodyTextSize); paint.setColor(getResources().getColor(R.color.text_white)); canvas.drawText(String.valueOf(game.highScore), sXHighScore + textMiddleHighScore, bodyStartYAll, paint); //Outputting scores box backgroundRectangle.setBounds(sXScore, sYAll, eXScore, eYAll); backgroundRectangle.draw(canvas); paint.setTextSize(titleTextSize); paint.setColor(getResources().getColor(R.color.text_brown)); canvas.drawText(getResources().getString(R.string.score), sXScore + textMiddleScore, titleStartYAll, paint); paint.setTextSize(bodyTextSize); paint.setColor(getResources().getColor(R.color.text_white)); canvas.drawText(String.valueOf(game.score), sXScore + textMiddleScore, bodyStartYAll, paint); } private void drawNewGameButton(Canvas canvas, boolean lightUp) { if (lightUp) { drawDrawable(canvas, lightUpRectangle, sXNewGame, sYIcons, sXNewGame + iconSize, sYIcons + iconSize ); } else { drawDrawable(canvas, backgroundRectangle, sXNewGame, sYIcons, sXNewGame + iconSize, sYIcons + iconSize ); } drawDrawable(canvas, getResources().getDrawable(R.drawable.ic_action_refresh), sXNewGame + iconPaddingSize, sYIcons + iconPaddingSize, sXNewGame + iconSize - iconPaddingSize, sYIcons + iconSize - iconPaddingSize ); } private void drawUndoButton(Canvas canvas) { drawDrawable(canvas, backgroundRectangle, sXUndo, sYIcons, sXUndo + iconSize, sYIcons + iconSize ); drawDrawable(canvas, getResources().getDrawable(R.drawable.ic_action_undo), sXUndo + iconPaddingSize, sYIcons + iconPaddingSize, sXUndo + iconSize - iconPaddingSize, sYIcons + iconSize - iconPaddingSize ); } private void drawHeader(Canvas canvas) { //Drawing the header paint.setTextSize(headerTextSize); paint.setColor(getResources().getColor(R.color.text_black)); paint.setTextAlign(Paint.Align.LEFT); int textShiftY = centerText() * 2; int headerStartY = sYAll - textShiftY; canvas.drawText(getResources().getString(R.string.header), startingX, headerStartY, paint); } private void drawInstructions(Canvas canvas) { //Drawing the instructions paint.setTextSize(instructionsTextSize); paint.setTextAlign(Paint.Align.LEFT); int textShiftY = centerText() * 2; canvas.drawText(getResources().getString(R.string.instructions), startingX, endingY - textShiftY + textPaddingSize, paint); } private void drawBackground(Canvas canvas) { drawDrawable(canvas, backgroundRectangle, startingX, startingY, endingX, endingY); } //Renders the set of 16 background squares. private void drawBackgroundGrid(Canvas canvas) { Resources resources = getResources(); Drawable backgroundCell = resources.getDrawable(R.drawable.cell_rectangle); // Outputting the game grid for (int xx = 0; xx < game.numSquaresX; xx++) { for (int yy = 0; yy < game.numSquaresY; yy++) { int sX = startingX + gridWidth + (cellSize + gridWidth) * xx; int eX = sX + cellSize; int sY = startingY + gridWidth + (cellSize + gridWidth) * yy; int eY = sY + cellSize; drawDrawable(canvas, backgroundCell, sX, sY, eX, eY); } } } private void drawCells(Canvas canvas) { paint.setTextSize(textSize); paint.setTextAlign(Paint.Align.CENTER); // Outputting the individual cells for (int xx = 0; xx < game.numSquaresX; xx++) { for (int yy = 0; yy < game.numSquaresY; yy++) { int sX = startingX + gridWidth + (cellSize + gridWidth) * xx; int eX = sX + cellSize; int sY = startingY + gridWidth + (cellSize + gridWidth) * yy; int eY = sY + cellSize; Tile currentTile = game.grid.getCellContent(xx, yy); if (currentTile != null) { //Get and represent the value of the tile int value = currentTile.getValue(); int index = log2(value); //Check for any active animations ArrayList<AnimationCell> aArray = game.aGrid.getAnimationCell(xx, yy); boolean animated = false; for (int i = aArray.size() - 1; i >= 0; i AnimationCell aCell = aArray.get(i); //If this animation is not active, skip it if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) { animated = true; } if (!aCell.isActive()) { continue; } if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) { // Spawning animation double percentDone = aCell.getPercentageDone(); float textScaleSize = (float) (percentDone); paint.setTextSize(textSize * textScaleSize); float cellScaleSize = cellSize / 2 * (1 - textScaleSize); bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize)); bitmapCell[index].draw(canvas); } else if (aCell.getAnimationType() == MainGame.MERGE_ANIMATION) { // Merging Animation double percentDone = aCell.getPercentageDone(); float textScaleSize = (float) (1 + INITIAL_VELOCITY * percentDone + MERGING_ACCELERATION * percentDone * percentDone / 2); paint.setTextSize(textSize * textScaleSize); float cellScaleSize = cellSize / 2 * (1 - textScaleSize); bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize)); bitmapCell[index].draw(canvas); } else if (aCell.getAnimationType() == MainGame.MOVE_ANIMATION) { // Moving animation double percentDone = aCell.getPercentageDone(); int tempIndex = index; if (aArray.size() >= 2) { tempIndex = tempIndex - 1; } int previousX = aCell.extras[0]; int previousY = aCell.extras[1]; int currentX = currentTile.getX(); int currentY = currentTile.getY(); int dX = (int) ((currentX - previousX) * (cellSize + gridWidth) * (percentDone - 1) * 1.0); int dY = (int) ((currentY - previousY) * (cellSize + gridWidth) * (percentDone - 1) * 1.0); bitmapCell[tempIndex].setBounds(sX + dX, sY + dY, eX + dX, eY + dY); bitmapCell[tempIndex].draw(canvas); } animated = true; } //No active animations? Just draw the cell if (!animated) { bitmapCell[index].setBounds(sX, sY, eX, eY); bitmapCell[index].draw(canvas); } } } } } private void drawEndGameState(Canvas canvas) { double alphaChange = 1; continueButtonEnabled = false; for (AnimationCell animation : game.aGrid.globalAnimation) { if (animation.getAnimationType() == MainGame.FADE_GLOBAL_ANIMATION) { alphaChange = animation.getPercentageDone(); } } BitmapDrawable displayOverlay = null; if (game.gameWon()) { if (game.canContinue()) { continueButtonEnabled = true; displayOverlay = winGameContinueOverlay; } else { displayOverlay = winGameFinalOverlay; } } else if (game.gameLost()) { displayOverlay = loseGameOverlay; } if (displayOverlay != null) { displayOverlay.setBounds(startingX, startingY, endingX, endingY); displayOverlay.setAlpha((int) (255 * alphaChange)); displayOverlay.draw(canvas); } } private void drawEndlessText(Canvas canvas) { paint.setTextAlign(Paint.Align.LEFT); paint.setTextSize(bodyTextSize); paint.setColor(getResources().getColor(R.color.text_black)); canvas.drawText(getResources().getString(R.string.endless), startingX, sYIcons - centerText() * 2, paint); } private void createEndGameStates(Canvas canvas, boolean win, boolean showButton) { int width = endingX - startingX; int length = endingY - startingY; int middleX = width / 2; int middleY = length / 2; if (win) { lightUpRectangle.setAlpha(127); drawDrawable(canvas, lightUpRectangle, 0, 0, width, length); lightUpRectangle.setAlpha(255); paint.setColor(getResources().getColor(R.color.text_white)); paint.setAlpha(255); paint.setTextSize(gameOverTextSize); paint.setTextAlign(Paint.Align.CENTER); int textBottom = middleY - centerText(); canvas.drawText(getResources().getString(R.string.you_win), middleX, textBottom, paint); paint.setTextSize(bodyTextSize); String text = showButton ? getResources().getString(R.string.go_on) : getResources().getString(R.string.for_now); canvas.drawText(text, middleX, textBottom + textPaddingSize * 2 - centerText() * 2, paint); } else { fadeRectangle.setAlpha(127); drawDrawable(canvas, fadeRectangle, 0, 0, width, length); fadeRectangle.setAlpha(255); paint.setColor(getResources().getColor(R.color.text_black)); paint.setAlpha(255); paint.setTextSize(gameOverTextSize); paint.setTextAlign(Paint.Align.CENTER); canvas.drawText(getResources().getString(R.string.game_over), middleX, middleY - centerText(), paint); } } private void createBackgroundBitmap(int width, int height) { background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(background); drawHeader(canvas); drawNewGameButton(canvas, false); drawUndoButton(canvas); drawBackground(canvas); drawBackgroundGrid(canvas); drawInstructions(canvas); } private void createBitmapCells() { Resources resources = getResources(); int[] cellRectangleIds = getCellRectangleIds(); paint.setTextAlign(Paint.Align.CENTER); for (int xx = 1; xx < bitmapCell.length; xx++) { int value = (int) Math.pow(2, xx); paint.setTextSize(cellTextSize); float tempTextSize = cellTextSize * cellSize * 0.9f / Math.max(cellSize * 0.9f, paint.measureText(String.valueOf(value))); paint.setTextSize(tempTextSize); Bitmap bitmap = Bitmap.createBitmap(cellSize, cellSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawDrawable(canvas, resources.getDrawable(cellRectangleIds[xx]), 0, 0, cellSize, cellSize); drawCellText(canvas, value); bitmapCell[xx] = new BitmapDrawable(resources, bitmap); } } private int[] getCellRectangleIds() { int[] cellRectangleIds = new int[numCellTypes]; cellRectangleIds[0] = R.drawable.cell_rectangle; cellRectangleIds[1] = R.drawable.cell_rectangle_2; cellRectangleIds[2] = R.drawable.cell_rectangle_4; cellRectangleIds[3] = R.drawable.cell_rectangle_8; cellRectangleIds[4] = R.drawable.cell_rectangle_16; cellRectangleIds[5] = R.drawable.cell_rectangle_32; cellRectangleIds[6] = R.drawable.cell_rectangle_64; cellRectangleIds[7] = R.drawable.cell_rectangle_128; cellRectangleIds[8] = R.drawable.cell_rectangle_256; cellRectangleIds[9] = R.drawable.cell_rectangle_512; cellRectangleIds[10] = R.drawable.cell_rectangle_1024; cellRectangleIds[11] = R.drawable.cell_rectangle_2048; for (int xx = 12; xx < cellRectangleIds.length; xx++) { cellRectangleIds[xx] = R.drawable.cell_rectangle_4096; } return cellRectangleIds; } private void createOverlays() { Resources resources = getResources(); //Initalize overlays Bitmap bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); createEndGameStates(canvas, true, true); winGameContinueOverlay = new BitmapDrawable(resources, bitmap); bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); createEndGameStates(canvas, true, false); winGameFinalOverlay = new BitmapDrawable(resources, bitmap); bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); createEndGameStates(canvas, false, false); loseGameOverlay = new BitmapDrawable(resources, bitmap); } private void tick() { long currentTime = System.nanoTime(); game.aGrid.tickAll(currentTime - lastFPSTime); lastFPSTime = currentTime; } public void resyncTime() { lastFPSTime = System.nanoTime(); } private void getLayout(int width, int height) { cellSize = Math.min(width / (game.numSquaresX + 1), height / (game.numSquaresY + 3)); gridWidth = cellSize / 7; int screenMiddleX = width / 2; int screenMiddleY = height / 2; int boardMiddleY = screenMiddleY + cellSize / 2; iconSize = cellSize / 2; paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(cellSize); textSize = cellSize * cellSize / Math.max(cellSize, paint.measureText("0000")); cellTextSize = textSize; titleTextSize = textSize / 3; bodyTextSize = (int) (textSize / 1.5); instructionsTextSize = (int) (textSize / 1.5); headerTextSize = textSize * 2; gameOverTextSize = textSize * 2; textPaddingSize = (int) (textSize / 3); iconPaddingSize = (int) (textSize / 5); //Grid Dimensions double halfNumSquaresX = game.numSquaresX / 2d; double halfNumSquaresY = game.numSquaresY / 2d; startingX = (int) (screenMiddleX - (cellSize + gridWidth) * halfNumSquaresX - gridWidth / 2); endingX = (int) (screenMiddleX + (cellSize + gridWidth) * halfNumSquaresX + gridWidth / 2); startingY = (int) (boardMiddleY - (cellSize + gridWidth) * halfNumSquaresY - gridWidth / 2); endingY = (int) (boardMiddleY + (cellSize + gridWidth) * halfNumSquaresY + gridWidth / 2); paint.setTextSize(titleTextSize); int textShiftYAll = centerText(); //static variables sYAll = (int) (startingY - cellSize * 1.5); titleStartYAll = (int) (sYAll + textPaddingSize + titleTextSize / 2 - textShiftYAll); bodyStartYAll = (int) (titleStartYAll + textPaddingSize + titleTextSize / 2 + bodyTextSize / 2); titleWidthHighScore = (int) (paint.measureText(getResources().getString(R.string.high_score))); titleWidthScore = (int) (paint.measureText(getResources().getString(R.string.score))); paint.setTextSize(bodyTextSize); textShiftYAll = centerText(); eYAll = (int) (bodyStartYAll + textShiftYAll + bodyTextSize / 2 + textPaddingSize); sYIcons = (startingY + eYAll) / 2 - iconSize / 2; sXNewGame = (endingX - iconSize); sXUndo = sXNewGame - iconSize * 3 / 2 - iconPaddingSize; resyncTime(); } private int centerText() { return (int) ((paint.descent() + paint.ascent()) / 2); } }
package base; import java.util.*; import java.io.*; public class BaseMain { public static BaseInjection inj=null; private static BaseInput binput = new BaseInput(); private static boolean settedInputData = false; //private static boolean InputCustomizable = false; protected static void resetBaseInput(){ binput = new BaseInput(); } public static boolean setInputData(String data){ if(!settedInputData){ try{ System.setIn(new ByteArrayInputStream(data.getBytes())); settedInputData =true; resetBaseInput(); return true; }catch(Exception e){ } } return false; } public static BaseInput getInput(){ return binput; } public static void onBeforeCode(Scanner sc,Object...objects){ } public static void onAfterCode(Scanner sc,Object...objects){ } //private final static Scanner sc = new Scanner(System.in); public static Scanner getScanner(){ return binput.getScanner(); } public static void print(Object s){ System.out.print(s); } public static void printline(String s){ System.out.println(s); } public static void printf(String format,Object...objects){ System.out.printf(format, objects); } }
package gov.nih.nci.calab.ui.workflow; /** * This class saves user entered new Run information * into the database. * * @author caLAB Team */ import gov.nih.nci.calab.ui.core.AbstractBaseAction; import gov.nih.nci.calab.dto.security.SecurityBean; import gov.nih.nci.calab.service.common.LookupService; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorActionForm; import org.apache.struts.validator.DynaValidatorForm; import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean; import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService; public class CreateRunAction extends AbstractBaseAction { private static Logger logger = Logger.getLogger(CreateRunAction.class); public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; HttpSession session = request.getSession(); ActionMessages messages=new ActionMessages(); try { // TODO fill in details for aliquot information */ DynaValidatorForm theForm = (DynaValidatorForm) form; //Get Prameters from form elements //Run info /* String assayId = (String) theForm.get("assay"); String runBy = (String) theForm.get("runBy"); String runDate = (String) theForm.get("runDate"); String creator = ""; if (session.getAttribute("user") != null) { SecurityBean user = (SecurityBean) session.getAttribute("user"); creator = user.getLoginId(); } String creationDate = StringUtils.convertDateToString(new Date(), "MM/dd/yyyy"); ExecuteWorkflowService workflowService=new ExecuteWorkflowService(); //Save Run String runId = workflowService.saveRun(assayId,runBy,runDate,creator,creationDate); //File info String[] inFileName = (String[]) theForm.get("inFileName"); String[] outFileName = (String[]) theForm.get("outFileName"); String fileURI = ""; //Get from File Upload module //Save File info workflowService.saveFileInfo(fileURI, inFileName,runId); workflowService.saveFileInfo(fileURI, outFileName,runId); //Other info String assayType = (String) theForm.get("assayType"); String runName = "Run 1"; String aliquotIds = (String) theForm.get("aliquotIds"); String allAliquotIds = (String) theForm.get("allAliquotIds"); String fileSubmissionDate = (String) theForm.get("fileSubmissionDate"); String fileSubmitter = (String) theForm.get("fileSubmitter"); String fileMaskStatus = (String) theForm.get("fileMaskStatus"); */ //Bean //ExecuteWorkflowBean executeworkflow = new ExecuteWorkflowBean(inFileName, outFileName, assayType, assayName,runName, runDate, runBy, createdDate, createdBy, aliquotIds,allAliquotIds, fileSubmissionDate, fileSubmitter, fileMaskStatus); //set to Request object //request.setAttribute("executeworkflow", executeworkflow); //set Forward forward = mapping.findForward("success"); System.out.print(">>>>SUCCESS CREATE RUN"); } catch (Exception e) { ActionMessage error=new ActionMessage("error.createRun"); messages.add("error", error); saveMessages(request, messages); logger.error("Caught exception when executing Run", e); forward = mapping.getInputForward(); } return forward; } public boolean loginRequired() { // temporarily set to false until login module is working return false; // return true; } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.Concept; import gov.nih.nci.ncicb.cadsr.domain.DataElement; import gov.nih.nci.ncicb.cadsr.domain.ObjectClass; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEventType; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ReviewableUMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ValueMeaningNode; import gov.nih.nci.ncicb.cadsr.loader.util.RunMode; import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil; import gov.nih.nci.ncicb.cadsr.loader.util.DEMappingUtil; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JOptionPane; import javax.swing.JPanel; public class ButtonPanel extends JPanel implements ActionListener, PropertyChangeListener { private JButton switchButton; private JCheckBox reviewButton; private NavigationButtonPanel navigationButtonPanel; private AddButtonPanel addButtonPanel; private ApplyButtonPanel applyButtonPanel; private List<NavigationListener> navigationListeners = new ArrayList<NavigationListener>(); private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); private ConceptEditorPanel conceptEditorPanel; private Editable viewPanel; private Editable editable; static final String PREVIEW = "PREVIEW", SETUP = "SETUP", SWITCH = "SWITCH", DELETEBUTTON = "DELETEBUTTON"; static final String SWITCH_TO_DE = "Map to CDE", SWITCH_TO_OC = "Map to OC", SWITCH_TO_CONCEPT = "Map to Concepts"; private RunMode runMode = null; public void addPropertyChangeListener(PropertyChangeListener l) { propChangeListeners.add(l); applyButtonPanel.addPropertyChangeListener(l); } public ButtonPanel(ConceptEditorPanel conceptEditorPanel, Editable viewPanel, Editable editable) { this.conceptEditorPanel = conceptEditorPanel; this.viewPanel = viewPanel; this.editable = editable; UserSelections selections = UserSelections.getInstance(); runMode = (RunMode)(selections.getProperty("MODE")); switchButton = new JButton(); ReviewableUMLNode revNode = (ReviewableUMLNode)conceptEditorPanel.getNode(); switchButton.setActionCommand(SWITCH); switchButton.addActionListener(this); navigationButtonPanel = new NavigationButtonPanel(); addButtonPanel = new AddButtonPanel(conceptEditorPanel); applyButtonPanel = new ApplyButtonPanel(viewPanel, revNode); this.add(addButtonPanel); this.add(applyButtonPanel); this.add(navigationButtonPanel); this.add(switchButton); } public void update() { applyButtonPanel.update(); if(editable instanceof DEPanel) { DataElement de = (DataElement)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(de.getPublicId())) { setSwitchButtonText(ButtonPanel.SWITCH_TO_CONCEPT); } else { setSwitchButtonText(ButtonPanel.SWITCH_TO_DE); } } else if(editable instanceof OCPanel) { ObjectClass oc = (ObjectClass)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(oc.getPublicId())) { setSwitchButtonText(ButtonPanel.SWITCH_TO_CONCEPT); } else { setSwitchButtonText(ButtonPanel.SWITCH_TO_OC); } } else if(editable == null) { return; } } public void addReviewListener(ReviewListener listener) { // reviewListeners.add(listener); applyButtonPanel.addReviewListener(listener); } public void addNavigationListener(NavigationListener listener) { navigationListeners.add(listener); navigationButtonPanel.addNavigationListener(listener); applyButtonPanel.addNavigationListener(listener); } public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals(SETUP)) { initButtonPanel(); } else if (e.getPropertyName().equals(SWITCH)) { switchButton.setEnabled((Boolean)e.getNewValue()); } addButtonPanel.propertyChange(e); applyButtonPanel.propertyChange(e); } private void fireNavigationEvent(NavigationEvent event) { for(NavigationListener l : navigationListeners) l.navigate(event); } private void setSwitchButtonText(String text) { switchButton.setText(text); } public void setEnabled(boolean enabled) { addButtonPanel.setVisible(enabled); applyButtonPanel.setVisible(enabled); if (enabled) { // enabling does not necessarily enable every single button initButtonPanel(); return; } // addButton.setEnabled(false); // saveButton.setEnabled(false); switchButton.setEnabled(false); // reviewButton.setEnabled(false); } private void initButtonPanel() { Concept[] concepts = conceptEditorPanel.getConcepts(); UMLNode node = conceptEditorPanel.getNode(); boolean reviewButtonState = false; if(concepts.length == 0) { if(node instanceof ValueMeaningNode) { reviewButtonState = true; } else reviewButtonState = false; } else reviewButtonState = true; switchButton.setVisible(editable instanceof DEPanel); if(editable instanceof DEPanel) { DataElement de = (DataElement)node.getUserObject(); if(DEMappingUtil.isMappedToLocalVD(de)) switchButton.setEnabled(false); } // disable add if DEPanel is showing if(editable instanceof DEPanel) { DataElement de = (DataElement)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(de.getPublicId())) { addButtonPanel.setVisible(false); reviewButtonState = true; } else { addButtonPanel.setVisible(true); } } else if(editable instanceof OCPanel) { ObjectClass oc = (ObjectClass)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(oc.getPublicId())) { addButtonPanel.setVisible(false); reviewButtonState = true; } else { addButtonPanel.setVisible(true); } } else if(editable == null) { addButtonPanel.setVisible(true); } applyButtonPanel.init(reviewButtonState); } public void setEditablePanel(Editable editable) { this.editable = editable; } public void navigate(NavigationEvent evt) { applyButtonPanel.navigate(evt); } private void firePropertyChangeEvent(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) l.propertyChange(evt); } public void actionPerformed(ActionEvent evt) { AbstractButton button = (AbstractButton)evt.getSource(); if(button.getActionCommand().equals(SWITCH)) { if(switchButton.getText().equals(SWITCH_TO_DE)) { ((UMLElementViewPanel)viewPanel).switchCards(UMLElementViewPanel.DE_PANEL_KEY); switchButton.setText(SWITCH_TO_CONCEPT); addButtonPanel.setVisible(false); } else if (switchButton.getText().equals(SWITCH_TO_CONCEPT)) { ((UMLElementViewPanel)viewPanel).switchCards(UMLElementViewPanel.CONCEPT_PANEL_KEY); if(editable instanceof DEPanel) { switchButton.setText(SWITCH_TO_DE); conceptEditorPanel.getVDPanel().updateNode(conceptEditorPanel.getNode()); } else if(editable instanceof OCPanel) { switchButton.setText(SWITCH_TO_OC); } else if(editable == null) { } addButtonPanel.setVisible(true); } else if(switchButton.getText().equals(SWITCH_TO_OC)) { ((UMLElementViewPanel)viewPanel).switchCards(UMLElementViewPanel.OC_PANEL_KEY); switchButton.setText(SWITCH_TO_CONCEPT); } } } }
package com.sensei.test; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.net.URL; import java.net.URLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.DefaultSimilarity; import org.apache.lucene.util.Version; import org.json.JSONObject; import org.mortbay.jetty.Server; import proj.zoie.api.IndexReaderFactory; import proj.zoie.api.ZoieIndexReader; import proj.zoie.api.indexing.ZoieIndexableInterpreter; import proj.zoie.impl.indexing.ZoieConfig; import proj.zoie.impl.indexing.ZoieSystem; import com.browseengine.bobo.api.BoboIndexReader; import com.browseengine.bobo.api.BrowseFacet; import com.browseengine.bobo.api.BrowseSelection; import com.browseengine.bobo.api.FacetAccessible; import com.browseengine.bobo.api.FacetSpec; import com.browseengine.bobo.api.FacetSpec.FacetSortSpec; import com.browseengine.bobo.facets.data.FacetDataCache; import com.browseengine.bobo.facets.data.FacetDataFetcher; import com.linkedin.norbert.NorbertException; import com.linkedin.norbert.cluster.ClusterShutdownException; import com.linkedin.norbert.javacompat.cluster.ClusterClient; import com.linkedin.norbert.javacompat.cluster.ZooKeeperClusterClient; import com.linkedin.norbert.javacompat.network.NetworkClientConfig; import com.sensei.conf.SenseiServerBuilder; import com.sensei.search.cluster.client.SenseiNetworkClient; import com.sensei.search.nodes.SenseiBroker; import com.sensei.search.nodes.SenseiIndexReaderDecorator; import com.sensei.search.nodes.SenseiQueryBuilderFactory; import com.sensei.search.nodes.SenseiServer; import com.sensei.search.nodes.impl.NoopIndexingManager; import com.sensei.search.nodes.impl.SimpleQueryBuilderFactory; import com.sensei.search.req.SenseiHit; import com.sensei.search.req.SenseiRequest; import com.sensei.search.req.SenseiResult; import com.sensei.search.svc.api.SenseiService; import com.sensei.search.svc.impl.HttpRestSenseiServiceImpl; public class TestSensei extends AbstractSenseiTestCase { static File ConfDir1 = new File("src/test/conf/node1"); static File ConfDir2 = new File("src/test/conf/node2"); static File IndexDir = new File("index/test"); static URL SenseiUrl = null; private static final Logger logger = Logger.getLogger(TestSensei.class); public static FacetDataFetcher facetDataFetcher = new FacetDataFetcher() { public Object fetch(BoboIndexReader reader, int doc) { FacetDataCache dataCache = (FacetDataCache)reader.getFacetData("groupid"); return dataCache.valArray.getRawValue(dataCache.orderArray.get(doc)); } public void cleanup(BoboIndexReader reader) { } }; public static FacetDataFetcher facetDataFetcherFixedLengthLongArray = new FacetDataFetcher() { private int counter = 0; public Object fetch(BoboIndexReader reader, int doc) { FacetDataCache dataCache = (FacetDataCache)reader.getFacetData("groupid"); long[] val = new long[2]; val[0] = counter%5; ++counter; Long groupId = (Long)dataCache.valArray.getRawValue(dataCache.orderArray.get(doc)); if (groupId == null) val[1] = 0; else val[1] = groupId; return val; } public void cleanup(BoboIndexReader reader) { counter = 0; } }; public TestSensei() { super(); } public TestSensei(String testName) { super(testName); } public static <T> IndexReaderFactory<ZoieIndexReader<BoboIndexReader>> buildReaderFactory(File file,ZoieIndexableInterpreter<T> interpreter){ ZoieSystem<BoboIndexReader,T> zoieSystem = new ZoieSystem<BoboIndexReader,T>(file,interpreter,new SenseiIndexReaderDecorator(),new StandardAnalyzer(Version.LUCENE_34),new DefaultSimilarity(),1000,300000,true,ZoieConfig.DEFAULT_VERSION_COMPARATOR,false); zoieSystem.getAdminMBean().setFreshness(50); zoieSystem.start(); return zoieSystem; } public static Map<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>> buildZoieFactoryMap(ZoieIndexableInterpreter<?> interpreter,Map<Integer,File> partFileMap){ Map<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>> partReaderMap = new HashMap<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>>(); Set<Entry<Integer,File>> entrySet = partFileMap.entrySet(); for (Entry<Integer,File> entry : entrySet){ partReaderMap.put(entry.getKey(), buildReaderFactory(entry.getValue(), interpreter)); } return partReaderMap; } static SenseiBroker broker = null; static SenseiService httpRestSenseiService = null; static SenseiServer node1; static SenseiServer node2; static Server httpServer1; static Server httpServer2; static boolean rmrf(File f) { if (f != null) { if (f.isDirectory()) { for (File sub : f.listFiles()) { if (!rmrf(sub)) return false; } } else return f.delete(); } return true; } static JSONObject search(JSONObject req) throws Exception { URLConnection conn = SenseiUrl.openConnection(); conn.setDoOutput(true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); String reqStr = req.toString(); System.out.println("req: " + reqStr); writer.write(reqStr, 0, reqStr.length()); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) sb.append(line); String res = sb.toString(); System.out.println("res: " + res); return new JSONObject(res); } static { // Try to remove pre-existing test index files: try { SenseiUrl = new URL("http://localhost:8079/sensei"); } catch (Exception e) { e.printStackTrace(); } try { rmrf(IndexDir); } catch (Exception e) { // Ignore. } SenseiServerBuilder senseiServerBuilder1 = null; SenseiServerBuilder senseiServerBuilder2 = null; try { senseiServerBuilder1 = new SenseiServerBuilder(ConfDir1); node1 = senseiServerBuilder1.buildServer(); httpServer1 = senseiServerBuilder1.buildHttpRestServer(); logger.info("Node 1 created."); } catch (Exception e) { e.printStackTrace(); } try { senseiServerBuilder2 = new SenseiServerBuilder(ConfDir2); node2 = senseiServerBuilder2.buildServer(); httpServer2 = senseiServerBuilder2.buildHttpRestServer(); logger.info("Node 2 created."); } catch (Exception e) { e.printStackTrace(); } // register the request-response messages broker = null; try { broker = new SenseiBroker(networkClient, clusterClient, loadBalancerFactory); broker.setTimeoutMillis(0); } catch (NorbertException ne) { logger.info("shutting down cluster...", ne); try { clusterClient.shutdown(); } catch (ClusterShutdownException e) { logger.info(e.getMessage(), e); } finally { } } httpRestSenseiService = new HttpRestSenseiServiceImpl("http", "localhost", 8079, "/sensei"); logger.info("Cluster client started"); Runtime.getRuntime().addShutdownHook(new Thread(){ public void run(){ try{ broker.shutdown(); } catch(Throwable t){} try{ httpRestSenseiService.shutdown(); } catch(Throwable t){} try{ node1.shutdown(); } catch(Throwable t){} try{ httpServer1.stop(); } catch(Throwable t){} try{ node2.shutdown(); } catch(Throwable t){} try{ httpServer2.stop(); } catch(Throwable t){} try{ networkClient.shutdown(); } catch(Throwable t){} try{ clusterClient.shutdown(); } catch(Throwable t){} } }); try { node1.start(true); } catch (Exception e) { e.printStackTrace(); } try { httpServer1.start(); } catch (Exception e) { e.printStackTrace(); } logger.info("Node 1 started"); try { node2.start(true); } catch (Exception e) { e.printStackTrace(); } try { httpServer2.start(); } catch (Exception e) { e.printStackTrace(); } logger.info("Node 2 started"); try { SenseiRequest req = new SenseiRequest(); SenseiResult res = null; int count = 0; do { Thread.sleep(5000); res = broker.browse(req); System.out.println(""+res.getNumHits()+" loaded..."); ++count; } while (count < 20 && res.getNumHits() < 15000); // Thread.sleep(500000); } catch (Exception e) { e.printStackTrace(); } } private void setspec(SenseiRequest req, FacetSpec spec) { req.setFacetSpec("color", spec); req.setFacetSpec("category", spec); req.setFacetSpec("city", spec); req.setFacetSpec("makemodel", spec); req.setFacetSpec("year", spec); req.setFacetSpec("price", spec); req.setFacetSpec("mileage", spec); req.setFacetSpec("tags", spec); } public void testTotalCount() throws Exception { logger.info("executing test case testTotalCount"); SenseiRequest req = new SenseiRequest(); SenseiResult res = broker.browse(req); assertEquals("wrong total number of hits" + req + res, 15000, res.getNumHits()); logger.info("request:" + req + "\nresult:" + res); } public void testTotalCountWithFacetSpec() throws Exception { logger.info("executing test case testTotalCountWithFacetSpec"); SenseiRequest req = new SenseiRequest(); FacetSpec facetSpecall = new FacetSpec(); facetSpecall.setMaxCount(1000000); facetSpecall.setExpandSelection(true); facetSpecall.setMinHitCount(0); facetSpecall.setOrderBy(FacetSortSpec.OrderHitsDesc); FacetSpec facetSpec = new FacetSpec(); facetSpec.setMaxCount(5); setspec(req, facetSpec); req.setCount(5); setspec(req, facetSpecall); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); verifyFacetCount(res, "year", "[1993 TO 1994]", 3090); } public void testSelection() throws Exception { logger.info("executing test case testSelection"); FacetSpec facetSpecall = new FacetSpec(); facetSpecall.setMaxCount(1000000); facetSpecall.setExpandSelection(true); facetSpecall.setMinHitCount(0); facetSpecall.setOrderBy(FacetSortSpec.OrderHitsDesc); FacetSpec facetSpec = new FacetSpec(); facetSpec.setMaxCount(5); SenseiRequest req = new SenseiRequest(); req.setCount(3); facetSpecall.setMaxCount(3); setspec(req, facetSpecall); BrowseSelection sel = new BrowseSelection("year"); String selVal = "[2001 TO 2002]"; sel.addValue(selVal); req.addSelection(sel); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); assertEquals(2907, res.getNumHits()); String selName = "year"; verifyFacetCount(res, selName, selVal, 2907); verifyFacetCount(res, "year", "[1993 TO 1994]", 3090); } public void testSelectionNot() throws Exception { logger.info("executing test case testSelectionNot"); FacetSpec facetSpecall = new FacetSpec(); facetSpecall.setMaxCount(1000000); facetSpecall.setExpandSelection(true); facetSpecall.setMinHitCount(0); facetSpecall.setOrderBy(FacetSortSpec.OrderHitsDesc); FacetSpec facetSpec = new FacetSpec(); facetSpec.setMaxCount(5); SenseiRequest req = new SenseiRequest(); req.setCount(3); facetSpecall.setMaxCount(3); setspec(req, facetSpecall); BrowseSelection sel = new BrowseSelection("year"); sel.addNotValue("[2001 TO 2002]"); req.addSelection(sel); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); assertEquals(12093, res.getNumHits()); verifyFacetCount(res, "year", "[1993 TO 1994]", 3090); } public void testGroupBy() throws Exception { logger.info("executing test case testGroupBy"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy("groupid"); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); } public void testGroupByWithGroupedHits() throws Exception { logger.info("executing test case testGroupBy"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy("groupid"); req.setMaxPerGroup(8); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); // use httpRestSenseiService res = httpRestSenseiService.doQuery(req); logger.info("request:" + req + "\nresult:" + res); hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); } public void testGroupByVirtual() throws Exception { logger.info("executing test case testGroupByVirtual"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy("virtual_groupid"); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); } public void testGroupByVirtualWithGroupedHits() throws Exception { logger.info("executing test case testGroupByVirtualWithGroupedHits"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy("virtual_groupid"); req.setMaxPerGroup(8); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); } public void testGroupByFixedLengthLongArray() throws Exception { logger.info("executing test case testGroupByFixedLengthLongArray"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy("virtual_groupid_fixedlengthlongarray"); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); } public void testGroupByFixedLengthLongArrayWithGroupedHits() throws Exception { logger.info("executing test case testGroupByFixedLengthLongArrayWithGroupedHits"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy("virtual_groupid_fixedlengthlongarray"); req.setMaxPerGroup(8); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); } public void testSelectionTerm() throws Exception { logger.info("executing test case Selection term"); String req = "{\"selections\":[{\"term\":{\"color\":{\"value\":\"red\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testSelectionTerms() throws Exception { logger.info("executing test case Selection terms"); String req = "{\"selections\":[{\"terms\":{\"tags\":{\"values\":[\"mp3\",\"moon-roof\"],\"excludes\":[\"leather\"],\"operator\":\"or\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4483, res.getInt("numhits")); } public void testSelectionRange() throws Exception { //2000 1548; //2001 1443; //2002 1464; // [2000 TO 2002] ==> 4455 // (2000 TO 2002) ==> 1443 // (2000 TO 2002] ==> 2907 // [2000 TO 2002) ==> 2991 { logger.info("executing test case Selection range [2000 TO 2002]"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":true,\"include_upper\":true,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4455, res.getInt("numhits")); } { logger.info("executing test case Selection range (2000 TO 2002)"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":false,\"include_upper\":false,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1443, res.getInt("numhits")); } { logger.info("executing test case Selection range (2000 TO 2002]"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":false,\"include_upper\":true,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2907, res.getInt("numhits")); } { logger.info("executing test case Selection range [2000 TO 2002)"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":true,\"include_upper\":false,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2991, res.getInt("numhits")); } } public void testMatchAllWithBoostQuery() throws Exception { logger.info("executing test case MatchAllQuery"); String req = "{\"query\": {\"match_all\": {\"boost\": \"1.2\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); } public void testQueryStringQuery() throws Exception { logger.info("executing test case testQueryStringQuery"); String req = "{\"query\": {\"query_string\": {\"query\": \"red AND cool\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1070, res.getInt("numhits")); } public void testMatchAllQuery() throws Exception { logger.info("executing test case testMatchAllQuery"); String req = "{\"query\": {\"match_all\": {}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); } public void testUIDQuery() throws Exception { logger.info("executing test case testUIDQuery"); String req = "{\"query\": {\"ids\": {\"values\": [\"1\", \"2\", \"3\"], \"excludes\": [\"2\"]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2, res.getInt("numhits")); assertEquals("the first uid is wrong", 1, res.getJSONArray("hits").getJSONObject(0).getInt("uid")); assertEquals("the second uid is wrong", 3, res.getJSONArray("hits").getJSONObject(1).getInt("uid")); } public void testTextQuery() throws Exception { logger.info("executing test case testTextQuery"); String req = "{\"query\": {\"text\": {\"contents\": { \"value\": \"red cool\", \"operator\": \"and\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1070, res.getInt("numhits")); } public void testTermQuery() throws Exception { logger.info("executing test case testTermQuery"); String req = "{\"query\":{\"term\":{\"color\":\"red\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testTermsQuery() throws Exception { logger.info("executing test case testTermQuery"); String req = "{\"query\":{\"terms\":{\"tags\":{\"values\":[\"leather\",\"moon-roof\"],\"excludes\":[\"hybrid\"],\"minimum_match\":0,\"operator\":\"or\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 5777, res.getInt("numhits")); } public void testBooleanQuery() throws Exception { logger.info("executing test case testBooleanQuery"); String req = "{\"query\":{\"bool\":{\"must_not\":{\"term\":{\"category\":\"compact\"}},\"must\":{\"term\":{\"color\":\"red\"}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1652, res.getInt("numhits")); } public void testDistMaxQuery() throws Exception { //color red ==> 2160 //color blue ==> 1104 logger.info("executing test case testDistMaxQuery"); String req = "{\"query\":{\"dis_max\":{\"tie_breaker\":0.7,\"queries\":[{\"term\":{\"color\":\"red\"}},{\"term\":{\"color\":\"blue\"}}],\"boost\":1.2}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } // public void testPathQuery() throws Exception // //color red ==> 2160 // //color blue ==> 1104 // logger.info("executing test case testDistMaxQuery"); // String req = "{\"query\":{\"dis_max\":{\"tie_breaker\":0.7,\"queries\":[{\"term\":{\"color\":\"red\"}},{\"term\":{\"color\":\"blue\"}}],\"boost\":1.2}}}"; // JSONObject res = search(new JSONObject(req)); // assertEquals("numhits is wrong", 3264, res.getInt("numhits")); public void testPrefixQuery() throws Exception { //color blue ==> 1104 logger.info("executing test case testPrefixQuery"); String req = "{\"query\":{\"prefix\":{\"color\":{\"value\":\"blu\",\"boost\":2}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1104, res.getInt("numhits")); } public void testWildcardQuery() throws Exception { //color blue ==> 1104 logger.info("executing test case testWildcardQuery"); String req = "{\"query\":{\"wildcard\":{\"color\":{\"value\":\"bl*e\",\"boost\":2}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1104, res.getInt("numhits")); } public void testRangeQuery() throws Exception { logger.info("executing test case testRangeQuery"); String req = "{\"query\":{\"range\":{\"year\":{\"to\":2000,\"boost\":2,\"from\":1999,\"_noOptimize\":false}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } public void testRangeQuery2() throws Exception { logger.info("executing test case testRangeQuery2"); String req = "{\"query\":{\"range\":{\"year\":{\"to\":\"2000\",\"boost\":2,\"from\":\"1999\",\"_noOptimize\":true,\"_type\":\"int\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } public void testFilteredQuery() throws Exception { logger.info("executing test case testFilteredQuery"); String req ="{\"query\":{\"filtered\":{\"query\":{\"term\":{\"color\":\"red\"}},\"filter\":{\"range\":{\"year\":{\"to\":2000,\"from\":1999}}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 447, res.getInt("numhits")); } public void testSpanTermQuery() throws Exception { logger.info("executing test case testSpanTermQuery"); String req = "{\"query\":{\"span_term\":{\"color\":\"red\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testSpanOrQuery() throws Exception { logger.info("executing test case testSpanOrQuery"); String req = "{\"query\":{\"span_or\":{\"clauses\":[{\"span_term\":{\"color\":\"red\"}},{\"span_term\":{\"color\":\"blue\"}}]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testSpanNotQuery() throws Exception { logger.info("executing test case testSpanNotQuery"); String req = "{\"query\":{\"span_not\":{\"exclude\":{\"span_term\":{\"contents\":\"red\"}},\"include\":{\"span_term\":{\"contents\":\"compact\"}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4596, res.getInt("numhits")); } public void testSpanNearQuery1() throws Exception { logger.info("executing test case testSpanNearQuery1"); String req = "{\"query\":{\"span_near\":{\"in_order\":false,\"collect_payloads\":false,\"slop\":12,\"clauses\":[{\"span_term\":{\"contents\":\"red\"}},{\"span_term\":{\"contents\":\"compact\"}},{\"span_term\":{\"contents\":\"hybrid\"}}]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 274, res.getInt("numhits")); } public void testSpanNearQuery2() throws Exception { logger.info("executing test case testSpanNearQuery2"); String req = "{\"query\":{\"span_near\":{\"in_order\":true,\"collect_payloads\":false,\"slop\":0,\"clauses\":[{\"span_term\":{\"contents\":\"red\"}},{\"span_term\":{\"contents\":\"compact\"}},{\"span_term\":{\"contents\":\"favorite\"}}]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 63, res.getInt("numhits")); } public void testSpanFirstQuery() throws Exception { logger.info("executing test case testSpanFirstQuery"); String req = "{\"query\":{\"span_first\":{\"match\":{\"span_term\":{\"color\":\"red\"}},\"end\":2}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testUIDFilter() throws Exception { logger.info("executing test case testUIDFilter"); String req = "{\"filter\": {\"ids\": {\"values\": [\"1\", \"2\", \"3\"], \"excludes\": [\"2\"]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2, res.getInt("numhits")); assertEquals("the first uid is wrong", 1, res.getJSONArray("hits").getJSONObject(0).getInt("uid")); assertEquals("the second uid is wrong", 3, res.getJSONArray("hits").getJSONObject(1).getInt("uid")); } public void testAndFilter() throws Exception { logger.info("executing test case testAndFilter"); String req = "{\"filter\":{\"and\":[{\"term\":{\"tags\":\"mp3\",\"_noOptimize\":false}},{\"term\":{\"color\":\"red\",\"_noOptimize\":false}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 439, res.getInt("numhits")); } public void testOrFilter() throws Exception { logger.info("executing test case testOrFilter"); String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":true}},{\"term\":{\"color\":\"red\",\"_noOptimize\":true}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testOrFilter2() throws Exception { logger.info("executing test case testOrFilter2"); String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":false}},{\"term\":{\"color\":\"red\",\"_noOptimize\":false}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testOrFilter3() throws Exception { logger.info("executing test case testOrFilter3"); String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":true}},{\"term\":{\"color\":\"red\",\"_noOptimize\":false}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testBooleanFilter() throws Exception { logger.info("executing test case testBooleanFilter"); String req = "{\"filter\":{\"bool\":{\"must_not\":{\"term\":{\"category\":\"compact\"}},\"should\":[{\"term\":{\"color\":\"red\"}},{\"term\":{\"color\":\"green\"}}],\"must\":{\"term\":{\"color\":\"red\"}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1652, res.getInt("numhits")); } public void testQueryFilter() throws Exception { logger.info("executing test case testQueryFilter"); String req = "{\"filter\": {\"query\":{\"range\":{\"year\":{\"to\":2000,\"boost\":2,\"from\":1999,\"_noOptimize\":false}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } /* Need to fix the bug in bobo and kamikazi, for details see the following two test cases:*/ // public void testAndFilter() throws Exception // logger.info("executing test case testAndFilter"); // String req = "{\"filter\":{\"and\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":false}},{\"query\":{\"term\":{\"category\":\"compact\"}}}]}}"; // JSONObject res = search(new JSONObject(req)); // assertEquals("numhits is wrong", 508, res.getInt("numhits")); // public void testQueryFilter2() throws Exception // logger.info("executing test case testQueryFilter2"); // String req = "{\"filter\": {\"query\":{\"term\":{\"category\":\"compact\"}}}}"; // JSONObject res = search(new JSONObject(req)); // assertEquals("numhits is wrong", 1104, res.getInt("numhits")); /* another weird bug may exist somewhere in bobo or kamikazi.*/ /* In the following two test cases, when modifying the first one by changing "tags" to "tag", it is supposed that * Only the first test case is not correct, but the second one also throw one NPE, which is weird. * */ // public void testAndFilter() throws Exception // logger.info("executing test case testAndFilter"); // String req = "{\"filter\":{\"and\":[{\"term\":{\"tag\":\"mp3\",\"_noOptimize\":false}},{\"query\":{\"term\":{\"color\":\"red\"}}}]}}"; // JSONObject res = search(new JSONObject(req)); // assertEquals("numhits is wrong", 439, res.getInt("numhits")); // public void testOrFilter() throws Exception // logger.info("executing test case testOrFilter"); // String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":false}},{\"query\":{\"term\":{\"color\":\"red\"}}}]}}"; // JSONObject res = search(new JSONObject(req)); // assertEquals("numhits is wrong", 3264, res.getInt("numhits")); public void testTermFilter() throws Exception { logger.info("executing test case testTermFilter"); String req = "{\"filter\":{\"term\":{\"color\":\"red\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testTermsFilter() throws Exception { logger.info("executing test case testTermsFilter"); String req = "{\"filter\":{\"terms\":{\"tags\":{\"values\":[\"leather\",\"moon-roof\"],\"excludes\":[\"hybrid\"],\"minimum_match\":0,\"operator\":\"or\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 5777, res.getInt("numhits")); } public void testRangeFilter() throws Exception { logger.info("executing test case testRangeFilter"); String req = "{\"filter\":{\"range\":{\"year\":{\"to\":2000,\"boost\":2,\"from\":1999,\"_noOptimize\":false}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } public void testRangeFilter2() throws Exception { logger.info("executing test case testRangeFilter2"); String req = "{\"filter\":{\"range\":{\"year\":{\"to\":\"2000\",\"boost\":2,\"from\":\"1999\",\"_noOptimize\":true,\"_type\":\"int\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } /** * @param res * result * @param selName * the field name of the facet * @param selVal * the value for which to check the count * @param count * the expected count of the given value. If count>0, we verify the count. If count=0, it either has to NOT exist or it is 0. * If count <0, it must not exist. */ private void verifyFacetCount(SenseiResult res, String selName, String selVal, int count) { FacetAccessible year = res.getFacetAccessor(selName); List<BrowseFacet> browsefacets = year.getFacets(); int index = indexOfFacet(selVal, browsefacets); if (count>0) { assertTrue("should contain a BrowseFacet for " + selVal, index >= 0); BrowseFacet bf = browsefacets.get(index); assertEquals(selVal + " has wrong count ", count, bf.getFacetValueHitCount()); } else if (count == 0) { if (index >= 0) { // count has to be 0 BrowseFacet bf = browsefacets.get(index); assertEquals(selVal + " has wrong count ", count, bf.getFacetValueHitCount()); } } else { assertTrue("should not contain a BrowseFacet for " + selVal, index < 0); } } private int indexOfFacet(String selVal, List<BrowseFacet> browsefacets) { for (int i = 0; i < browsefacets.size(); i++) { if (browsefacets.get(i).getValue().equals(selVal)) return i; } return -1; } }
package org.jaxen.util; import java.util.Iterator; import java.util.NoSuchElementException; /** * Simple utility class that wraps an iterator around one object. * This is a little more efficent than creating a one-object list. * */ public class SingleObjectIterator implements Iterator { private Object object; private boolean seen; public SingleObjectIterator(Object object) { this.object = object; this.seen = false; } public boolean hasNext() { return ! this.seen; } public Object next() { if ( hasNext() ) { this.seen = true; return this.object; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }
package org.jsmpp.session; import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketTimeoutException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.jsmpp.DefaultPDUReader; import org.jsmpp.DefaultPDUSender; import org.jsmpp.InvalidCommandLengthException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUReader; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.SynchronizedPDUSender; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindType; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.connection.Connection; import org.jsmpp.util.MessageId; import org.jsmpp.util.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public class SMPPServerSession extends AbstractSession implements ServerSession { private static final Logger logger = LoggerFactory.getLogger(SMPPServerSession.class); private final Connection conn; private final DataInputStream in; private final OutputStream out; private final PDUReader pduReader; private SMPPServerSessionContext sessionContext = new SMPPServerSessionContext(this); private final ServerResponseHandler responseHandler = new ResponseHandlerImpl(); private ServerMessageReceiverListener messageReceiverListener; private final EnquireLinkSender enquireLinkSender; private BindRequestReceiver bindRequestReceiver = new BindRequestReceiver(responseHandler); public SMPPServerSession(Connection conn, SessionStateListener sessionStateListener, ServerMessageReceiverListener messageReceiverListener, int pduProcessorDegree) { this(conn, sessionStateListener, messageReceiverListener, pduProcessorDegree, new SynchronizedPDUSender( new DefaultPDUSender()), new DefaultPDUReader()); } public SMPPServerSession(Connection conn, SessionStateListener sessionStateListener, ServerMessageReceiverListener messageReceiverListener, int pduProcessorDegree, PDUSender pduSender, PDUReader pduReader) { super(pduSender); this.conn = conn; this.messageReceiverListener = messageReceiverListener; this.pduReader = pduReader; this.in = new DataInputStream(conn.getInputStream()); this.out = conn.getOutputStream(); enquireLinkSender = new EnquireLinkSender(); addSessionStateListener(new BoundStateListener()); addSessionStateListener(sessionStateListener); setPduProcessorDegree(pduProcessorDegree); sessionContext.open(); } public BindRequest waitForBind(long timeout) throws IllegalStateException, TimeoutException { if (getSessionState().equals(SessionState.OPEN)) { new PDUReaderWorker().start(); try { return bindRequestReceiver.waitForRequest(timeout); } catch (IllegalStateException e) { throw new IllegalStateException("Invocation of waitForBind() has been made", e); } catch (TimeoutException e) { close(); throw e; } } else { throw new IllegalStateException("waitForBind() should be invoked on OPEN state, actual state is " + SessionState.OPEN); } } private synchronized boolean isReadPdu() { SessionState sessionState = sessionContext.getSessionState(); return sessionState.isBound() || sessionState.equals(SessionState.OPEN); } public void deliverShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { DeliverSmCommandTask task = new DeliverSmCommandTask(pduSender(), serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocoId, protocoId, registeredDelivery, dataCoding, shortMessage, optionalParameters); executeSendCommand(task, getTransactionTimer()); } /* (non-Javadoc) * @see org.jsmpp.session.ServerSession#alertNotification(int, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.OptionalParameter[]) */ public void alertNotification(int sequenceNumber, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber esmeAddrTon, NumberingPlanIndicator esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException, IOException { pduSender().sendAlertNotification(connection().getOutputStream(), sequenceNumber, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, esmeAddrTon.value(), esmeAddrNpi.value(), esmeAddr, optionalParameters); } private MessageId fireAcceptSubmitSm(SubmitSm submitSm) throws ProcessRequestException { if (messageReceiverListener != null) { return messageReceiverListener.onAcceptSubmitSm(submitSm, this); } throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } private SubmitMultiResult fireAcceptSubmitMulti(SubmitMulti submitMulti) throws ProcessRequestException { if (messageReceiverListener != null) { return messageReceiverListener.onAcceptSubmitMulti(submitMulti, this); } throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } private QuerySmResult fireAcceptQuerySm(QuerySm querySm) throws ProcessRequestException { if (messageReceiverListener != null) { return messageReceiverListener.onAcceptQuerySm(querySm, this); } throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } private void fireAcceptReplaceSm(ReplaceSm replaceSm) throws ProcessRequestException { if (messageReceiverListener != null) { messageReceiverListener.onAcceptReplaceSm(replaceSm, this); } else { throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } } private void fireAcceptCancelSm(CancelSm cancelSm) throws ProcessRequestException { if (messageReceiverListener != null) { messageReceiverListener.onAcceptCancelSm(cancelSm, this); } else { throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } } @Override protected Connection connection() { return conn; } @Override protected AbstractSessionContext sessionContext() { return sessionContext; } @Override protected GenericMessageReceiverListener messageReceiverListener() { return messageReceiverListener; } public ServerMessageReceiverListener getMessageReceiverListener() { return messageReceiverListener; } public void setMessageReceiverListener( ServerMessageReceiverListener messageReceiverListener) { this.messageReceiverListener = messageReceiverListener; } private class ResponseHandlerImpl implements ServerResponseHandler { @SuppressWarnings("unchecked") public PendingResponse<Command> removeSentItem(int sequenceNumber) { return removePendingResponse(sequenceNumber); } public void notifyUnbonded() { sessionContext.unbound(); } public void sendEnquireLinkResp(int sequenceNumber) throws IOException { logger.debug("Sending enquire_link_resp"); pduSender().sendEnquireLinkResp(out, sequenceNumber); } public void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException { pduSender().sendGenericNack(out, commandStatus, sequenceNumber); } public void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException { pduSender().sendHeader(out, originalCommandId | SMPPConstant.MASK_CID_RESP, commandStatus, sequenceNumber); } public void sendUnbindResp(int sequenceNumber) throws IOException { pduSender().sendUnbindResp(out, SMPPConstant.STAT_ESME_ROK, sequenceNumber); } public void sendBindResp(String systemId, BindType bindType, int sequenceNumber) throws IOException { sessionContext.bound(bindType); try { pduSender().sendBindResp(out, bindType.responseCommandId(), sequenceNumber, systemId); } catch (PDUStringException e) { logger.error("Failed sending bind response", e); // TODO uudashr: we have double checking when accept the bind request } } public void processBind(Bind bind) { bindRequestReceiver.notifyAcceptBind(bind); } public MessageId processSubmitSm(SubmitSm submitSm) throws ProcessRequestException { return fireAcceptSubmitSm(submitSm); } public void sendSubmitSmResponse(MessageId messageId, int sequenceNumber) throws IOException { try { pduSender().sendSubmitSmResp(out, sequenceNumber, messageId.getValue()); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of MessageId should be save. */ logger.error("SYSTEM ERROR. Failed sending submitSmResp", e); } } public SubmitMultiResult processSubmitMulti(SubmitMulti submitMulti) throws ProcessRequestException { return fireAcceptSubmitMulti(submitMulti); } public void sendSubmitMultiResponse( SubmitMultiResult submiitMultiResult, int sequenceNumber) throws IOException { try { pduSender().sendSubmitMultiResp(out, sequenceNumber, submiitMultiResult.getMessageId(), submiitMultiResult.getUnsuccessDeliveries()); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of the response parameter has been validated. */ logger.error("SYSTEM ERROR. Failed sending submitMultiResp", e); } } public QuerySmResult processQuerySm(QuerySm querySm) throws ProcessRequestException { return fireAcceptQuerySm(querySm); } public void sendQuerySmResp(String messageId, String finalDate, MessageState messageState, byte errorCode, int sequenceNumber) throws IOException { try { pduSender().sendQuerySmResp(out, sequenceNumber, messageId, finalDate, messageState, errorCode); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of parsed messageId has been validated. */ logger.error("SYSTEM ERROR. Failed sending cancelSmResp", e); } } public DataSmResult processDataSm(DataSm dataSm) throws ProcessRequestException { return fireAcceptDataSm(dataSm); } // TODO uudashr: we can generalize this method public void sendDataSmResp(DataSmResult dataSmResult, int sequenceNumber) throws IOException { try { pduSender().sendDataSmResp(out, sequenceNumber, dataSmResult.getMessageId(), dataSmResult.getOptionalParameters()); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of MessageId should be save. */ logger.error("SYSTEM ERROR. Failed sending dataSmResp", e); } } public void processCancelSm(CancelSm cancelSm) throws ProcessRequestException { fireAcceptCancelSm(cancelSm); } public void sendCancelSmResp(int sequenceNumber) throws IOException { pduSender().sendCancelSmResp(out, sequenceNumber); } public void processReplaceSm(ReplaceSm replaceSm) throws ProcessRequestException { fireAcceptReplaceSm(replaceSm); } public void sendReplaceSmResp(int sequenceNumber) throws IOException { pduSender().sendReplaceSmResp(out, sequenceNumber); } } private class PDUReaderWorker extends Thread { private ExecutorService executorService = Executors.newFixedThreadPool(getPduProcessorDegree()); private Runnable onIOExceptionTask = new Runnable() { public void run() { close(); }; }; @Override public void run() { logger.info("Starting PDUReaderWorker with processor degree:{} ...", getPduProcessorDegree()); while (isReadPdu()) { readPDU(); } close(); executorService.shutdown(); logger.info("PDUReaderWorker stop"); } private void readPDU() { try { Command pduHeader = null; byte[] pdu = null; pduHeader = pduReader.readPDUHeader(in); pdu = pduReader.readPDU(in, pduHeader); PDUProcessServerTask task = new PDUProcessServerTask(pduHeader, pdu, sessionContext.getStateProcessor(), sessionContext, responseHandler, onIOExceptionTask); executorService.execute(task); } catch (InvalidCommandLengthException e) { logger.warn("Receive invalid command length", e); try { pduSender().sendGenericNack(out, SMPPConstant.STAT_ESME_RINVCMDLEN, 0); } catch (IOException ee) { logger.warn("Failed sending generic nack", ee); } unbindAndClose(); } catch (SocketTimeoutException e) { notifyNoActivity(); } catch (IOException e) { close(); } } /** * Notify for no activity. */ private void notifyNoActivity() { logger.debug("No activity notified"); enquireLinkSender.enquireLink(); } } private class EnquireLinkSender extends Thread { private final AtomicBoolean sendingEnquireLink = new AtomicBoolean(false); @Override public void run() { logger.info("Starting EnquireLinkSender"); while (isReadPdu()) { while (!sendingEnquireLink.compareAndSet(true, false) && isReadPdu()) { synchronized (sendingEnquireLink) { try { sendingEnquireLink.wait(500); } catch (InterruptedException e) { } } } if (!isReadPdu()) { break; } try { sendEnquireLink(); } catch (ResponseTimeoutException e) { close(); } catch (InvalidResponseException e) { // lets unbind gracefully unbindAndClose(); } catch (IOException e) { close(); } } logger.info("EnquireLinkSender stop"); } /** * This method will send enquire link asynchronously. */ public void enquireLink() { if (sendingEnquireLink.compareAndSet(false, true)) { synchronized (sendingEnquireLink) { sendingEnquireLink.notify(); } } } } private class BoundStateListener implements SessionStateListener { public void onStateChange(SessionState newState, SessionState oldState, Object source) { if (newState.isBound()) { enquireLinkSender.start(); } } } }
package hudson.tasks; import hudson.AbortException; import hudson.FilePath; import hudson.Functions; import hudson.Launcher; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Label; import hudson.model.Result; import static hudson.tasks.LogRotatorTest.build; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Collections; import java.util.List; import hudson.remoting.VirtualChannel; import hudson.slaves.DumbSlave; import jenkins.MasterToSlaveFileCallable; import jenkins.util.VirtualFile; import org.hamcrest.Matchers; import org.jenkinsci.plugins.structs.describable.DescribableModel; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.*; import static org.junit.Assume.*; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.jvnet.hudson.test.recipes.LocalData; public class ArtifactArchiverTest { @Rule public JenkinsRule j = new JenkinsRule(); @Test @Issue("JENKINS-3227") public void testEmptyDirectories() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); Publisher artifactArchiver = new ArtifactArchiver("dir/"); project.getPublishersList().replaceBy(Collections.singleton(artifactArchiver)); project.getBuildersList().replaceBy(Collections.singleton(new TestBuilder() { public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { FilePath dir = build.getWorkspace().child("dir"); dir.child("subdir1").mkdirs(); FilePath subdir2 = dir.child("subdir2"); subdir2.mkdirs(); subdir2.child("file").write("content", "UTF-8"); return true; } })); assertEquals(Result.SUCCESS, build(project)); // File artifacts = project.getBuildByNumber(1).getArtifactsDir(); File[] kids = artifacts.listFiles(); assertEquals(1, kids.length); assertEquals("dir", kids[0].getName()); kids = kids[0].listFiles(); assertEquals(1, kids.length); assertEquals("subdir2", kids[0].getName()); kids = kids[0].listFiles(); assertEquals(1, kids.length); assertEquals("file", kids[0].getName()); } @Test @Issue("JENKINS-10502") public void testAllowEmptyArchive() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); ArtifactArchiver aa = new ArtifactArchiver("f"); assertFalse(aa.getAllowEmptyArchive()); aa.setAllowEmptyArchive(true); project.getPublishersList().replaceBy(Collections.singleton(aa)); assertEquals("(no artifacts)", Result.SUCCESS, build(project)); assertFalse(project.getBuildByNumber(1).getHasArtifacts()); } @Issue("JENKINS-21958") @Test public void symlinks() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { FilePath ws = build.getWorkspace(); if (ws == null) { return false; } FilePath dir = ws.child("dir"); dir.mkdirs(); dir.child("fizz").write("contents", null); dir.child("lodge").symlinkTo("fizz", listener); return true; } }); ArtifactArchiver aa = new ArtifactArchiver("dir/lodge"); aa.setAllowEmptyArchive(true); p.getPublishersList().add(aa); FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); FilePath ws = b.getWorkspace(); assertNotNull(ws); assumeTrue("May not be testable on Windows:\n" + JenkinsRule.getLog(b), ws.child("dir/lodge").exists()); List<FreeStyleBuild.Artifact> artifacts = b.getArtifacts(); assertEquals(1, artifacts.size()); FreeStyleBuild.Artifact artifact = artifacts.get(0); assertEquals("dir/lodge", artifact.relativePath); VirtualFile[] kids = b.getArtifactManager().root().child("dir").list(); assertEquals(1, kids.length); assertEquals("lodge", kids[0].getName()); // do not check that it .exists() since its target has not been archived } @Issue("SECURITY-162") @Test public void outsideSymlinks() throws Exception { final FreeStyleProject p = j.createFreeStyleProject(); p.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { FilePath ws = build.getWorkspace(); if (ws == null) { return false; } ws.child("hack").symlinkTo(p.getConfigFile().getFile().getAbsolutePath(), listener); return true; } }); p.getPublishersList().add(new ArtifactArchiver("hack", "", false, true)); FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); List<FreeStyleBuild.Artifact> artifacts = b.getArtifacts(); assertEquals(1, artifacts.size()); FreeStyleBuild.Artifact artifact = artifacts.get(0); assertEquals("hack", artifact.relativePath); VirtualFile[] kids = b.getArtifactManager().root().list(); assertEquals(1, kids.length); assertEquals("hack", kids[0].getName()); assertFalse(kids[0].isDirectory()); assertFalse(kids[0].isFile()); assertFalse(kids[0].exists()); j.createWebClient().assertFails(b.getUrl() + "artifact/hack", HttpURLConnection.HTTP_NOT_FOUND); } static class CreateArtifact extends TestBuilder { public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { build.getWorkspace().child("f").write("content", "UTF-8"); return true; } } static class CreateArtifactAndFail extends TestBuilder { public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { build.getWorkspace().child("f").write("content", "UTF-8"); throw new AbortException("failing the build"); } } @Test @Issue("JENKINS-22698") public void testArchivingSkippedWhenOnlyIfSuccessfulChecked() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); ArtifactArchiver aa = new ArtifactArchiver("f"); project.getPublishersList().replaceBy(Collections.singleton(aa)); project.getBuildersList().replaceBy(Collections.singleton(new CreateArtifactAndFail())); assertEquals(Result.FAILURE, build(project)); assertTrue(project.getBuildByNumber(1).getHasArtifacts()); aa.setOnlyIfSuccessful(true); assertEquals(Result.FAILURE, build(project)); assertTrue(project.getBuildByNumber(1).getHasArtifacts()); assertFalse(project.getBuildByNumber(2).getHasArtifacts()); } @Issue("JENKINS-29922") @Test public void configRoundTrip() throws Exception { ArtifactArchiver aa = new ArtifactArchiver("*.txt"); assertNull(Util.fixEmpty(aa.getExcludes())); // null and "" behave the same, we do not care which it is assertEquals("{artifacts=*.txt}", DescribableModel.uninstantiate_(aa).toString()); // but we do care that excludes is considered to be at the default aa = j.configRoundtrip(aa); assertEquals("*.txt", aa.getArtifacts()); assertNull(Util.fixEmpty(aa.getExcludes())); assertEquals("{artifacts=*.txt}", DescribableModel.uninstantiate_(aa).toString()); aa.setExcludes("README.txt"); aa = j.configRoundtrip(aa); assertEquals("*.txt", aa.getArtifacts()); assertEquals("README.txt", aa.getExcludes()); assertEquals("{artifacts=*.txt, excludes=README.txt}", DescribableModel.uninstantiate_(aa).toString()); // TreeMap, so attributes will be sorted } static class CreateDefaultExcludesArtifact extends TestBuilder { public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { FilePath dir = build.getWorkspace().child("dir"); FilePath subSvnDir = dir.child(".svn"); subSvnDir.mkdirs(); subSvnDir.child("file").write("content", "UTF-8"); FilePath svnDir = build.getWorkspace().child(".svn"); svnDir.mkdirs(); svnDir.child("file").write("content", "UTF-8"); dir.child("file").write("content", "UTF-8"); return true; } } @Test @Issue("JENKINS-20086") public void testDefaultExcludesOn() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); Publisher artifactArchiver = new ArtifactArchiver("**", "", false, false, true, true); project.getPublishersList().replaceBy(Collections.singleton(artifactArchiver)); project.getBuildersList().replaceBy(Collections.singleton(new CreateDefaultExcludesArtifact())); assertEquals(Result.SUCCESS, build(project)); // VirtualFile artifacts = project.getBuildByNumber(1).getArtifactManager().root(); assertFalse(artifacts.child(".svn").child("file").exists()); assertFalse(artifacts.child("dir").child(".svn").child("file").exists()); } @Test @Issue("JENKINS-20086") public void testDefaultExcludesOff() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); ArtifactArchiver artifactArchiver = new ArtifactArchiver("**"); artifactArchiver.setDefaultExcludes(false); project.getPublishersList().replaceBy(Collections.singleton(artifactArchiver)); project.getBuildersList().replaceBy(Collections.singleton(new CreateDefaultExcludesArtifact())); assertEquals(Result.SUCCESS, build(project)); // VirtualFile artifacts = project.getBuildByNumber(1).getArtifactManager().root(); assertTrue(artifacts.child(".svn").child("file").exists()); assertTrue(artifacts.child("dir").child(".svn").child("file").exists()); } @LocalData @Test public void latestOnlyMigration() throws Exception { FreeStyleProject p = j.jenkins.getItemByFullName("sample", FreeStyleProject.class); assertNotNull(p); @SuppressWarnings("deprecation") LogRotator lr = p.getLogRotator(); assertNotNull(lr); assertEquals(1, lr.getArtifactNumToKeep()); String xml = p.getConfigFile().asString(); assertFalse(xml, xml.contains("<latestOnly>")); assertTrue(xml, xml.contains("<artifactNumToKeep>1</artifactNumToKeep>")); } @LocalData @Test public void fingerprintMigration() throws Exception { FreeStyleProject p = j.jenkins.getItemByFullName(Functions.isWindows() ? "sample-windows" : "sample", FreeStyleProject.class); assertNotNull(p); String xml = p.getConfigFile().asString(); assertFalse(xml, xml.contains("<recordBuildArtifacts>")); assertTrue(xml, xml.contains("<fingerprint>true</fingerprint>")); assertFalse(xml, xml.contains("<hudson.tasks.Fingerprinter>")); ArtifactArchiver aa = p.getPublishersList().get(ArtifactArchiver.class); assertTrue(aa.isFingerprint()); FreeStyleBuild b1 = j.buildAndAssertSuccess(p); assertEquals(1, b1.getArtifacts().size()); Fingerprinter.FingerprintAction a = b1.getAction(Fingerprinter.FingerprintAction.class); assertNotNull(a); assertEquals("[stuff]", a.getFingerprints().keySet().toString()); } @Test @Issue("JENKINS-21905") public void archiveNotReadable() throws Exception { assumeFalse(Functions.isWindows()); final String FILENAME = "myfile"; DumbSlave slave = j.createOnlineSlave(Label.get("target")); FreeStyleProject p = j.createFreeStyleProject(); p.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { FilePath file = build.getWorkspace().child(FILENAME); file.act(new RemoveReadPermission()); return true; } }); p.getPublishersList().add(new ArtifactArchiver(FILENAME)); p.setAssignedNode(slave); FreeStyleBuild build = p.scheduleBuild2(0).get(); j.assertBuildStatus(Result.FAILURE, build); String expectedPath = build.getWorkspace().child(FILENAME).getRemote(); j.assertLogContains("ERROR: Step ‘Archive the artifacts’ failed: java.nio.file.AccessDeniedException: " + expectedPath, build); assertThat("No stacktrace shown", build.getLog(31), Matchers.iterableWithSize(lessThan(30))); } private static class RemoveReadPermission extends MasterToSlaveFileCallable<Object> { @Override public Object invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { assertTrue(f.createNewFile()); assertTrue(f.setReadable(false)); return null; } } }
package org.pdfsam.ui.io; import static org.pdfsam.support.RequireUtils.requireNotNull; import javafx.scene.control.CheckBox; import javafx.scene.control.Tooltip; import javafx.scene.layout.VBox; import org.pdfsam.i18n.DefaultI18nContext; import org.pdfsam.ui.support.Style; /** * Base panel with minimal output options * * @author Andrea Vacondio * */ class DestinationPane extends VBox { private CheckBox overwrite = new CheckBox(DefaultI18nContext.getInstance().i18n("Overwrite if already exists")); private BrowsableField destination; public DestinationPane(BrowsableField destination) { super(5); requireNotNull(destination, "Destination field cannot be null"); this.destination = destination; overwrite.setSelected(false); overwrite.setTooltip(new Tooltip(DefaultI18nContext.getInstance().i18n( "Tick the box if you want to overwrite the output files if they already exist."))); destination.getStyleClass().addAll(Style.VITEM.css()); getChildren().addAll(destination, overwrite); getStyleClass().addAll(Style.CONTAINER.css()); } protected CheckBox overwrite() { return overwrite; } protected BrowsableField destination() { return destination; } }
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.UNADDRESSED; import io.netty.channel.socket.SocketChannel; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.utils.*; import io.tetrapod.protocol.core.*; import java.io.*; import java.lang.management.ManagementFactory; import java.nio.file.*; import java.util.*; import java.util.concurrent.TimeUnit; import org.slf4j.*; import ch.qos.logback.classic.LoggerContext; public class DefaultService implements Service, Fail.FailHandler, CoreContract.API, SessionFactory, EntityMessage.Handler, ClusterMemberMessage.Handler { private static final Logger logger = LoggerFactory.getLogger(DefaultService.class); protected final Set<Integer> dependencies = new HashSet<>(); protected final Dispatcher dispatcher; protected Client clusterClient; protected Contract contract; protected final ServiceCache services; protected boolean terminated; protected int entityId; protected int parentId; protected String token; protected int status; protected final int buildNumber; protected final LogBuffer logBuffer; protected final ServiceStats stats; private final LinkedList<ServerAddress> clusterMembers = new LinkedList<ServerAddress>(); private final MessageHandlers messageHandlers = new MessageHandlers(); public DefaultService() { logBuffer = (LogBuffer) ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("ROOT").getAppender("BUFFER"); String m = getStartLoggingMessage(); logger.info(m); Session.commsLog.info(m); Fail.handler = this; Metrics.init(getMetricsPrefix()); status |= Core.STATUS_STARTING; dispatcher = new Dispatcher(); clusterClient = new Client(this); stats = new ServiceStats(this); addContracts(new CoreContract()); addPeerContracts(new TetrapodContract()); addMessageHandler(new EntityMessage(), this); addMessageHandler(new ClusterMemberMessage(), this); if (getEntityType() != Core.TYPE_TETRAPOD) { services = new ServiceCache(); addSubscriptionHandler(new TetrapodContract.Services(), services); } else { services = null; } Runtime.getRuntime().addShutdownHook(new Thread("Shutdown Hook") { public void run() { logger.info("Shutdown Hook"); if (!isShuttingDown()) { shutdown(false); } } }); int num = 1; try { String b = Util.readFileAsString(new File("build_number.txt")); num = Integer.parseInt(b.trim()); } catch (IOException e) {} buildNumber = num; checkHealth(); } /** * Returns a prefix for all exported metrics from this service. */ private String getMetricsPrefix() { return Util.getProperty("devMode", "") + "." + Util.getProperty("product.name") + "." + Util.getHostName() + "." + getClass().getSimpleName(); } public byte getEntityType() { return Core.TYPE_SERVICE; } public synchronized int getStatus() { return status; } @Override public void messageEntity(EntityMessage m, MessageContext ctxA) { SessionMessageContext ctx = (SessionMessageContext) ctxA; if (ctx.session.getTheirEntityType() == Core.TYPE_TETRAPOD) { this.entityId = m.entityId; ctx.session.setMyEntityId(m.entityId); } } @Override public void genericMessage(Message message, MessageContext ctx) { assert false; } // Service protocol @Override public void startNetwork(ServerAddress server, String token, Map<String, String> otherOpts) throws Exception { this.token = token; clusterMembers.addFirst(server); connectToCluster(); } /** * Called after registration is complete and this service has a valid entityId and is free to make requests into the cluster. Default * implementation is to do nothing. */ public void onRegistered() {} /** * Called after we've registered and dependencies are all available */ public void onReadyToServe() {} private void onServiceRegistered() { registerServiceInformation(); stats.publishTopic(); sendDirectRequest(new ServicesSubscribeRequest()); onRegistered(); checkDependencies(); } private void checkDependencies() { if (!isShuttingDown()) { if (getEntityType() == Core.TYPE_TETRAPOD || services.checkDependencies(dependencies)) { onReadyToServe(); // ok, we're good to go updateStatus(status & ~Core.STATUS_STARTING); setWebRoot(); } else { dispatcher.dispatch(1, TimeUnit.SECONDS, new Runnable() { public void run() { checkDependencies(); } }); } } } /** * Periodically checks service health, updates metrics */ private void checkHealth() { if (!isShuttingDown()) { if (dispatcher.workQueueSize.getCount() >= Session.DEFAULT_OVERLOAD_THRESHOLD) { updateStatus(status | Core.STATUS_OVERLOADED); } else { updateStatus(status & ~Core.STATUS_OVERLOADED); } dispatcher.dispatch(1, TimeUnit.SECONDS, new Runnable() { public void run() { checkHealth(); } }); } } /** * Called before shutting down. Default implementation is to do nothing. Subclasses are expecting to close any resources they opened (for * example database connections or file handles). * * @param restarting true if we are shutting down in order to restart */ public void onShutdown(boolean restarting) {} public void onPaused() {} public void onUnpaused() {} public void shutdown(boolean restarting) { updateStatus(status | Core.STATUS_STOPPING); onShutdown(restarting); if (restarting) { clusterClient.close(); dispatcher.shutdown(); setTerminated(true); try { Launcher.relaunch(token); } catch (Exception e) { logger.error(e.getMessage(), e); } } else { sendDirectRequest(new UnregisterRequest(getEntityId())).handle(new ResponseHandler() { @Override public void onResponse(Response res) { clusterClient.close(); dispatcher.shutdown(); setTerminated(true); } }); } } /** * Session factory for our session to our parent TetrapodService */ @Override public Session makeSession(SocketChannel ch) { final Session ses = new WireSession(ch, DefaultService.this); ses.setMyEntityType(getEntityType()); ses.setTheirEntityType(Core.TYPE_TETRAPOD); ses.addSessionListener(new Session.Listener() { @Override public void onSessionStop(Session ses) { onDisconnectedFromCluster(); } @Override public void onSessionStart(Session ses) { onConnectedToCluster(); } }); return ses; } public void onConnectedToCluster() { sendDirectRequest(new RegisterRequest(buildNumber, token, getContractId(), getShortName(), status, Util.getHostName())).handle( new ResponseHandler() { @Override public void onResponse(Response res) { if (res.isError()) { Fail.fail("Unable to register: " + res.errorCode()); } else { RegisterResponse r = (RegisterResponse) res; entityId = r.entityId; parentId = r.parentId; token = r.token; logger.info(String.format("%s My entityId is 0x%08X", clusterClient.getSession(), r.entityId)); clusterClient.getSession().setMyEntityId(r.entityId); clusterClient.getSession().setTheirEntityId(r.parentId); clusterClient.getSession().setMyEntityType(getEntityType()); clusterClient.getSession().setTheirEntityType(Core.TYPE_TETRAPOD); onServiceRegistered(); } } }); } public void onDisconnectedFromCluster() { if (!isShuttingDown()) { dispatcher.dispatch(3, TimeUnit.SECONDS, new Runnable() { public void run() { connectToCluster(); } }); } } private void connectToCluster() { if (!isShuttingDown() && !clusterClient.isConnected()) { synchronized (clusterMembers) { final ServerAddress server = clusterMembers.poll(); try { clusterClient.connect(server.host, server.port, dispatcher).sync(); if (clusterClient.isConnected()) { clusterMembers.addFirst(server); return; } } catch (Throwable e) { logger.error(e.getMessage(), e); } clusterMembers.addLast(server); } // schedule a retry dispatcher.dispatch(1, TimeUnit.SECONDS, new Runnable() { public void run() { connectToCluster(); } }); } } // subclass utils protected void setMainContract(Contract c) { addContracts(c); contract = c; } protected void addContracts(Contract... contracts) { for (Contract c : contracts) { c.registerStructs(); } } protected void addPeerContracts(Contract... contracts) { for (Contract c : contracts) { c.registerPeerStructs(); } } protected int getEntityId() { return entityId; } protected int getParentId() { return parentId; } public synchronized boolean isShuttingDown() { return (status & Core.STATUS_STOPPING) != 0; } public synchronized boolean isPaused() { return (status & Core.STATUS_PAUSED) != 0; } public synchronized boolean isNominal() { int nonRunning = Core.STATUS_STARTING | Core.STATUS_FAILED | Core.STATUS_BUSY | Core.STATUS_PAUSED | Core.STATUS_STOPPING; return (status & nonRunning) == 0; } public synchronized boolean isTerminated() { return terminated; } private synchronized void setTerminated(boolean val) { logger.info("TERMINATED"); terminated = val; } protected void updateStatus(int status) { boolean changed = false; synchronized (this) { changed = this.status != status; this.status = status; } if (changed && clusterClient.isConnected()) { sendDirectRequest(new ServiceStatusUpdateRequest(status)); } } @Override public void fail(Throwable error) { logger.error(error.getMessage(), error); updateStatus(status | Core.STATUS_FAILED); } @Override public void fail(String reason) { logger.error("FAIL: {}", reason); updateStatus(status | Core.STATUS_FAILED); } /** * Get a URL for this service's icon to display in the admin apps. Subclasses should override this to customize */ public String getServiceIcon() { return "media/gear.gif"; } /** * Get any custom metadata for the service. Subclasses should override this to customize */ public String getServiceMetadata() { return null; } /** * Get any custom admin commands for the service to show in command menu of admin app. Subclasses should override this to customize */ public ServiceCommand[] getServiceCommands() { return null; } protected String getShortName() { if (contract == null) { return null; } return contract.getName(); } protected String getFullName() { if (contract == null) { return null; } String s = contract.getClass().getCanonicalName(); return s.substring(0, s.length() - "Contract".length()); } public String getHostName() { return Util.getHostName(); } public long getAverageResponseTime() { return (long) dispatcher.requestTimes.getOneMinuteRate(); } /** * Services can override this to provide a service specific counter for display in the admin app */ public long getCounter() { return 0; } public long getNumRequestsHandled() { return dispatcher.requestsHandledCounter.getCount(); } public long getNumMessagesSent() { return dispatcher.messagesSentCounter.getCount(); } public Response sendPendingRequest(Request req, PendingResponseHandler handler) { return clusterClient.getSession().sendPendingRequest(req, Core.UNADDRESSED, (byte) 30, handler); } public Response sendPendingRequest(Request req, int toEntityId, PendingResponseHandler handler) { return clusterClient.getSession().sendPendingRequest(req, toEntityId, (byte) 30, handler); } public Async sendRequest(Request req) { return clusterClient.getSession().sendRequest(req, Core.UNADDRESSED, (byte) 30); } public Async sendDirectRequest(Request req) { return clusterClient.getSession().sendRequest(req, Core.DIRECT, (byte) 30); } public Async sendRequest(Request req, int toEntityId) { return clusterClient.getSession().sendRequest(req, toEntityId, (byte) 30); } public void sendMessage(Message msg, int toEntityId, int topicId) { clusterClient.getSession().sendMessage(msg, toEntityId, topicId); } public void sendBroadcastMessage(Message msg, int topicId) { clusterClient.getSession().sendBroadcastMessage(msg, topicId); } public void subscribe(int topicId, int entityId) { sendMessage(new TopicSubscribedMessage(getEntityId(), topicId, entityId), UNADDRESSED, UNADDRESSED); } public void unsubscribe(int topicId, int entityId) { sendMessage(new TopicUnsubscribedMessage(getEntityId(), topicId, entityId), UNADDRESSED, UNADDRESSED); } public void unpublish(int topicId) { sendMessage(new TopicUnpublishedMessage(getEntityId(), topicId), UNADDRESSED, UNADDRESSED); } // Generic handlers for all request/subscriptions public Response genericRequest(Request r, RequestContext ctx) { logger.error("unhandled request " + r.dump()); return new Error(CoreContract.ERROR_UNKNOWN_REQUEST); } public void setDependencies(int... contractIds) { for (int contractId : contractIds) { dependencies.add(contractId); } } // Session.Help implementation @Override public Dispatcher getDispatcher() { return dispatcher; } @Override public ServiceAPI getServiceHandler(int contractId) { // this method allows us to have delegate objects that directly handle some contracts return this; } @Override public List<SubscriptionAPI> getMessageHandlers(int contractId, int structId) { return messageHandlers.get(contractId, structId); } @Override public int getContractId() { return contract == null ? 0 : contract.getContractId(); } public void addSubscriptionHandler(Contract sub, SubscriptionAPI handler) { messageHandlers.add(sub, handler); } public void addMessageHandler(Message k, SubscriptionAPI handler) { messageHandlers.add(k, handler); } @Override public void messageClusterMember(ClusterMemberMessage m, MessageContext ctx) { clusterMembers.add(new ServerAddress(m.host, m.servicePort)); } // private methods protected void registerServiceInformation() { if (contract != null) { AddServiceInformationRequest asi = new AddServiceInformationRequest(); asi.routes = contract.getWebRoutes(); asi.structs = new ArrayList<>(); for (Structure s : contract.getRequests()) { asi.structs.add(s.makeDescription()); } for (Structure s : contract.getResponses()) { asi.structs.add(s.makeDescription()); } for (Structure s : contract.getMessages()) { asi.structs.add(s.makeDescription()); } for (Structure s : contract.getStructs()) { asi.structs.add(s.makeDescription()); } sendDirectRequest(asi).handle(ResponseHandler.LOGGER); } } // Base service implementation @Override public Response requestPause(PauseRequest r, RequestContext ctx) { updateStatus(status | Core.STATUS_PAUSED); onPaused(); return Response.SUCCESS; } @Override public Response requestUnpause(UnpauseRequest r, RequestContext ctx) { updateStatus(status & ~Core.STATUS_PAUSED); onUnpaused(); return Response.SUCCESS; } @Override public Response requestRestart(RestartRequest r, RequestContext ctx) { dispatcher.dispatch(new Runnable() { public void run() { shutdown(true); } }); return Response.SUCCESS; } @Override public Response requestShutdown(ShutdownRequest r, RequestContext ctx) { dispatcher.dispatch(new Runnable() { public void run() { shutdown(false); } }); return Response.SUCCESS; } @Override public Response requestServiceDetails(ServiceDetailsRequest r, RequestContext ctx) { return new ServiceDetailsResponse(getServiceIcon(), getServiceMetadata(), getServiceCommands()); } @Override public Response requestServiceStatsSubscribe(ServiceStatsSubscribeRequest r, RequestContext ctx) { stats.subscribe(ctx.header.fromId); return Response.SUCCESS; } @Override public Response requestServiceStatsUnsubscribe(ServiceStatsUnsubscribeRequest r, RequestContext ctx) { stats.unsubscribe(ctx.header.fromId); return Response.SUCCESS; } private void setWebRoot() { String name = Launcher.getOpt("webOnly"); if (name == null) { name = getShortName(); } try { recursiveAddWebFiles(name, new File("webContent"), true); if (Util.getProperty("devMode", "local").equals("local")) { for (File f : getDevProtocolWebRoots()) recursiveAddWebFiles(name, f, false); } if (Launcher.getOpt("webOnly") != null) { shutdown(false); } } catch (IOException e) { logger.error("bad web root path", e); } } private static final Set<String> VALID_EXTENSIONS = new HashSet<>(Arrays.asList(new String[] { "html", "htm", "js", "css", "jpg", "png", "gif", "wav" })); private void recursiveAddWebFiles(String webRootName, File dir, boolean first) throws IOException { if (!dir.exists()) return; if (Util.getProperty("devMode", "local").equals("local")) { sendDirectRequest(new AddWebFileRequest(dir.getCanonicalPath(), webRootName, null, first)); return; } ArrayList<File> files = new ArrayList<>(Arrays.asList(dir.listFiles())); while (!files.isEmpty()) { File f = files.remove(0); if (f.isDirectory()) { files.addAll(Arrays.asList(f.listFiles())); continue; } int ix = f.getName().lastIndexOf("."); String ext = ix < 0 ? "" : f.getName().substring(ix + 1).toLowerCase(); if (VALID_EXTENSIONS.contains(ext)) { byte[] contents = Files.readAllBytes(f.toPath()); String path = "/" + dir.toPath().relativize(f.toPath()).toString(); Async a = sendDirectRequest(new AddWebFileRequest(path, webRootName, contents, first)); if (first) { // have to wait for the first one to finish so the first flag is really // the first one that is processed a.waitForResponse(); } first = false; } } } protected File[] getDevProtocolWebRoots() { if (getShortName() == null) { return new File[] {}; } return new File[] { new File("../Protocol-" + getShortName() + "/rsc") }; } @Override public Response requestServiceLogs(ServiceLogsRequest r, RequestContext ctx) { if (logBuffer == null) { return new Error(CoreContract.ERROR_NOT_CONFIGURED); } final List<ServiceLogEntry> list = new ArrayList<ServiceLogEntry>(); long last = logBuffer.getItems(r.logId, logBuffer.convert(r.level), r.maxItems, list); return new ServiceLogsResponse(last, list); } protected String getStartLoggingMessage() { return "*** Start Service ***" + "\n *** Service name: " + Util.getProperty("APPNAME") + "\n *** Options: " + Launcher.getAllOpts() + "\n *** VM Args: " + ManagementFactory.getRuntimeMXBean().getInputArguments().toString(); } }
package chihane.starrysky; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.ColorInt; import android.support.annotation.FloatRange; import android.support.annotation.IntDef; import android.support.annotation.IntRange; import android.util.AttributeSet; import android.view.View; public class Star extends View { static final int MAGNITUDE_MAX = -6; static final int MAGNITUDE_MIN = 6; private static final int ALPHA_MAX = 0xff; private static final int ALPHA_MIN = 0x33; private static final long TWINKLING_DURATION_MIN = 3000; private static final long TWINKLING_DURATION_MAX = 6000; private static final int STYLE_NORMAL = 0; @IntDef(value = {STYLE_NORMAL}) @interface StarStyle {} @IntRange(from = MAGNITUDE_MAX, to = MAGNITUDE_MIN) int magnitude; float latitude; float longitude; @StarStyle int style; @ColorInt int color; @FloatRange(from = 0, to = 20) float size; private Paint paint; private float dimmedPercent = 1; public Star(Context context) { this(context, null); } public Star(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Star(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } void init() { magnitude = MAGNITUDE_MAX; latitude = 0; longitude = 0; style = STYLE_NORMAL; color = Color.WHITE; size = 4; paint = new Paint(); } void twinkle() { ValueAnimator animator = ValueAnimator.ofFloat(1, 0); animator.setDuration(TWINKLING_DURATION_MIN + (int) (Math.random() * (TWINKLING_DURATION_MAX - TWINKLING_DURATION_MIN))); animator.setRepeatMode(ValueAnimator.REVERSE); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setStartDelay((long) (Math.random() * TWINKLING_DURATION_MAX / 2)); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); if (dimmedPercent == value) { return; } dimmedPercent = value; invalidate(); } }); animator.start(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension((int) size, (int) size); } @Override protected void onDraw(Canvas canvas) { initPaint(); canvas.drawCircle(size / 2, size / 2, size / 2, paint); } private void initPaint() { paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); paint.setColor(color); paint.setAlpha((int) (magnitude2Alpha(magnitude) * dimmedPercent)); } private int magnitude2Alpha(int magnitude) { int k = (ALPHA_MAX - ALPHA_MIN) / (MAGNITUDE_MAX - MAGNITUDE_MIN); int b = ALPHA_MAX - k * MAGNITUDE_MAX; return k * magnitude + b; } }
package net.somethingdreadful.MAL.tasks; import android.content.Context; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import net.somethingdreadful.MAL.MALManager; import net.somethingdreadful.MAL.PrefManager; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Anime; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Manga; import net.somethingdreadful.MAL.api.BaseModels.Backup; import net.somethingdreadful.MAL.api.MALApi; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; public class BackupTask extends AsyncTask<String, Void, Object> { private final BackupTaskListener callback; private final Context context; private ArrayList<Anime> animeResult; private ArrayList<Manga> mangaResult; private ArrayList<File> files = new ArrayList<>(); public BackupTask(BackupTaskListener callback, Context context) { this.callback = callback; this.context = context; } @Override protected Object doInBackground(String... params) { try { if (AccountService.getAccount() == null) { callback.onBackupTaskFailed(); return null; } MALManager mManager = new MALManager(context); PrefManager.create(context); mManager.verifyAuthentication(); // creates directory if it doesn't exists File directory = new File(Environment.getExternalStorageDirectory() + "/Atarashii/"); directory.mkdirs(); if (PrefManager.getBackupLength() < directory.listFiles().length) { Crashlytics.log(Log.INFO, "MALX", "BackupTask.saveBackup(): Backup limit reached: " + PrefManager.getBackupLength() + " records: " + directory.length()); Collections.addAll(files, directory.listFiles()); File file = new File(files.get(0).getAbsolutePath()); file.delete(); } // check if the network is available if (MALApi.isNetworkAvailable(context)) { // clean dirty records to pull all the changes mManager.cleanDirtyAnimeRecords(); mManager.cleanDirtyMangaRecords(); animeResult = mManager.downloadAndStoreAnimeList(AccountService.getUsername()); mangaResult = mManager.downloadAndStoreMangaList(AccountService.getUsername()); } // Get results from the database if there weren't any records if (animeResult == null) animeResult = mManager.getAnimeListFromDB(String.valueOf(MALApi.ListType.ANIME)); if (mangaResult == null) mangaResult = mManager.getMangaListFromDB(String.valueOf(MALApi.ListType.ANIME)); // create the backup model and get the string Backup backup = new Backup(); backup.setAccountType(AccountService.accountType); backup.setUsername(AccountService.getUsername()); backup.setAnimeList(animeResult); backup.setMangaList(mangaResult); String jsonResult = (new Gson()).toJson(backup); // creates the file itself File file = new File(directory, "Backup" + System.currentTimeMillis() + "_" + AccountService.getUsername() + ".json"); file.createNewFile(); // writes the details in the files OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file)); outputStreamWriter.write(jsonResult); outputStreamWriter.close(); // notify user Crashlytics.log(Log.INFO, "MALX", "BackupTask.saveBackup(): Backup has been created"); if (callback != null) callback.onBackupTaskFinished(); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "BackupTask.saveBackup(): " + e.getMessage()); Crashlytics.logException(e); if (callback != null) { callback.onBackupTaskFailed(); } } return null; } public interface BackupTaskListener { void onBackupTaskFinished(); void onBackupTaskFailed(); } }
package org.apache.cassandra.hirudinea; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.Iterator; import java.nio.ByteBuffer; import java.util.Date; import java.lang.Math; import org.apache.cassandra.db.*; import org.apache.cassandra.utils.ByteBufferUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import weka.clusterers.SimpleKMeans; public class Hirudinea { public static final String KEYSPACE_NAME = "tp"; public static final String TABLE_NAME = "station"; public static final String NUMBER_COLUMN_NAME = "n"; public static final Long TIME_WINDOW = 1000L*60; public static final Long INTERVAL = 1000L; private static final Logger logger = LoggerFactory.getLogger(Hirudinea.class); public static final ConcurrentHashMap<Long, ArrayList<StationEntry>> stations = new ConcurrentHashMap(); /* * Request analyze */ public static void extract(Keyspace ks, Mutation m) { String keyspace_name = ks.getName(); ByteBuffer key = m.key(); String table_name; String cell_name; ByteBuffer cell_value; Collection<ColumnFamily> values = m.getColumnFamilies(); for (ColumnFamily c: values) { table_name = c.metadata().cfName; for (Cell cell: c) { cell_name = c.getComparator().getString(cell.name()); cell_value = cell.value(); analyze(keyspace_name, table_name, key, cell_name, cell_value); } } } public static void analyze(String keyspace_name, String table_name, ByteBuffer key, String cell_name, ByteBuffer cell_value) { Long station_id; Long new_value; Date date; if (keyspace_name.equals(KEYSPACE_NAME) && table_name.equals(TABLE_NAME) && cell_name.equals(NUMBER_COLUMN_NAME)) { station_id = ByteBufferUtil.toLong(key); new_value = ByteBufferUtil.toLong(cell_value); date = new Date(); logger.info("Station {} modified at {}, new value: {}", station_id, date, new_value); addStationEntry(station_id, new_value, date); } } /* * Stations */ public static void addStationEntry(Long station_id, Long value, Date date) { ArrayList<StationEntry> entries; if (stations.get(station_id) == null) { entries = new ArrayList<StationEntry>(); } else { entries = stations.get(station_id); } entries.add(new StationEntry(value, date)); stations.put(station_id, entries); kmean(3); //displayStations(); } public static void displayStations() { logger.info("-- Display stations --"); for (Map.Entry<Long, ArrayList<StationEntry>> entry : stations.entrySet()) { Long key = entry.getKey(); ArrayList<StationEntry> value = entry.getValue(); logger.info("\t Station {}", key); logger.info("\t\t Time serie: {}", timeSerieToString(getTimeSerie(key, 1000L*60, 1000L))); for (StationEntry se: value) { logger.info("\t\t {}: {}", se.date, se.value); } } } /* * Time series */ public static ArrayList<Long> getTimeSerie(Long station_id, Date start, Date end, Long interval) { ArrayList<StationEntry> list_entries = stations.get(station_id); ArrayList<Long> time_serie = new ArrayList<Long>(); Long total_number = (end.getTime() - start.getTime()) / interval; for (int i = 0; i < total_number; i++) { time_serie.add(0L); } for (StationEntry se: list_entries) { int index = (int) ((se.date.getTime() - start.getTime()) / interval); for (int i = index; i < time_serie.size(); i++) { if (i >= 0) { time_serie.set(i, se.value); } } } return time_serie; } public static String timeSerieToString(ArrayList<Long> ts) { String s = "["; for (Long l: ts) { s += l + ", "; } s += "]"; return s; } public static ArrayList<Long> getTimeSerie(Long station_id, Long duration, Long interval) { Date start = new Date((new Date()).getTime() - duration); Date end = new Date(); return getTimeSerie(station_id, start, end, interval); } public static void kmean(int n) { ArrayList<ArrayList<Long>> timeSeries = new ArrayList<ArrayList<Long>>(); for (Long s_id : stations.keySet()) { timeSeries.add(getTimeSerie(s_id, TIME_WINDOW, INTERVAL)); } for (ArrayList<Long> t1 : timeSeries) { for (ArrayList<Long> t2 : timeSeries) { System.out.println(distance(t1, t2)); } } } public static ArrayList<Long> dba(ArrayList<ArrayList<Long>> timeSeries) { return new ArrayList<Long>(0); } public static Double distance(ArrayList<Long> series1, ArrayList<Long> series2) { int n = series1.size(); int m = series2.size(); ArrayList<ArrayList<Double>> dtw = new ArrayList<ArrayList<Double>>(n); for (int i = 0; i < n; i++) { ArrayList<Double> row = new ArrayList<Double>(m); for (int j = 0; j < m; j++) { if (j == 0 || i == 0) { row.add(Double.POSITIVE_INFINITY); } else{ row.add(0D); } } dtw.add(row); } dtw.get(0).set(0, 0D); for (int i = 1; i < n; i++) { for (int j = 1; j < m ; j++) { Double cost = Math.abs(series1.get(i).doubleValue() - series2.get(j).doubleValue()); dtw.get(i).set(j, cost + (Double)(Math.min(Math.min(dtw.get(i-1).get(j), dtw.get(i).get(j-1)), dtw.get(i-1).get(j-1)))); } } return dtw.get(n-1).get(m-1); } }
package io.tetrapod.core.web; import static io.netty.buffer.Unpooled.copiedBuffer; import static io.netty.buffer.Unpooled.wrappedBuffer; import static io.netty.handler.codec.http.HttpMethod.POST; import static io.tetrapod.protocol.core.Core.UNADDRESSED; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.multipart.*; import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType; import io.netty.util.CharsetUtil; import io.tetrapod.core.Session; import io.tetrapod.core.json.JSONObject; import io.tetrapod.protocol.core.RequestHeader; import io.tetrapod.protocol.core.WebRoute; import java.io.IOException; import java.util.List; import java.util.Map; import org.slf4j.*; public class WebContext { private static final Logger logger = LoggerFactory.getLogger(WebContext.class); public static ByteBuf makeByteBufResult(Object result) { if (result instanceof ByteBuf) return (ByteBuf) result; if (result instanceof byte[]) return wrappedBuffer((byte[]) result); return copiedBuffer(result.toString(), CharsetUtil.UTF_8); } private JSONObject requestParameters; private String requestPath; public WebContext(FullHttpRequest request, String routePath) throws IOException { parseRequestParameters(request, routePath); } public WebContext(JSONObject json) throws IOException { this.requestParameters = json; this.requestPath = json.optString("_uri", "/unknown"); } public RequestHeader makeRequestHeader(Session s, WebRoute route) { return makeRequestHeader(s, route, requestParameters); } public static RequestHeader makeRequestHeader(Session s, WebRoute route, JSONObject params) { RequestHeader header = new RequestHeader(); header.toId = params.optInt("_toId", UNADDRESSED); header.fromId = s.getTheirEntityId(); header.fromType = s.getTheirEntityType(); if (route == null) { // route is null for web socket & poller calls header.requestId = params.optInt("_requestId", -1); header.contractId = params.optInt("_contractId", -1); header.structId = params.optInt("_structId", -1); } else { header.contractId = route.contractId; header.structId = route.structId; } if (header.requestId < 0 || header.contractId < 0 || header.structId < 0) { return null; } header.timeout = (byte) 30; return header; } public JSONObject getRequestParams() { return requestParameters; } public String getRequestPath() { return requestPath; } private void parseRequestParameters(FullHttpRequest request, String routePath) throws IOException { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); if (!queryStringDecoder.path().equals(routePath) && !request.getUri().contains("?")) { // this happens if we're using / to start the params String uri = request.getUri(); uri = routePath + "?" + uri.substring(routePath.length() + 1); queryStringDecoder = new QueryStringDecoder(uri); } this.requestPath = queryStringDecoder.path(); this.requestParameters = new JSONObject(); Map<String, List<String>> reqs; try { reqs = queryStringDecoder.parameters(); } catch (IllegalArgumentException e) { logger.warn("Can't parse request parameters for [{}] {}", request.getUri(), routePath); return; } for (String k : reqs.keySet()) for (String v : reqs.get(k)) requestParameters.accumulate(k, v); // Add POST parameters if (request.getMethod() != POST) return; final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request); try { if (HttpHeaders.getHeader(request, "content-type").equals("application/json")) { if (decoder.hasNext()) { InterfaceHttpData httpData = decoder.next(); JSONObject data = new JSONObject(httpData.toString()); for(String k : JSONObject.getNames(requestParameters)) { data.put(k, requestParameters.get(k)); } requestParameters = data; } } else { while (decoder.hasNext()) { InterfaceHttpData httpData = decoder.next(); if (httpData.getHttpDataType() == HttpDataType.Attribute) { Attribute attribute = (Attribute) httpData; requestParameters.accumulate(attribute.getName(), attribute.getValue()); attribute.release(); } } } } catch (HttpPostRequestDecoder.EndOfDataDecoderException ex) { // Exception when the body is fully decoded, even if there is still data } finally { decoder.destroy(); } } }
package io.spine.server.aggregate; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks a method of an aggregate as one that modifies the state of the aggregate with data * from the passed event. * * <p>As we apply the event to the aggregate state, we call such a method <i>Event Applier</i>. * * <p>An event applier method: * <ul> * <li>is annotated with {@link Apply}; * <li>is {@code void}; * <li>accepts an event derived from {@link com.google.protobuf.Message Message} * as the only parameter. * </ul> * * <p>In order to update the state of the aggregate, the {@link Aggregate#getBuilder()} method * should be used. * * <p>If the annotation comes with the attribute {@link #allowImport() allowImport} set to * {@code true}, the aggregate would be able receive incoming events as if they were produced * by the aggregate. * * @author Alexander YevsyukovA */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Apply { /** * If {@code true} the aggregate supports importing of events with the messages * defined as the first parameter of the annotated method. * * @see ImportBus * @see AggregateRepository#getEventImportRouting() */ boolean allowImport() default false; }
package com.rho.db.file; import j2me.io.FileNotFoundException; import j2me.lang.AssertMe; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import net.rim.device.api.system.PersistentObject; import net.rim.device.api.system.PersistentStore; import net.rim.device.api.util.Persistable; import net.rim.device.api.util.StringUtilities; import com.rho.RhoEmptyLogger; import com.rho.RhoLogger; import com.rho.db.RandomAccessFile; public class PersistRAFileImpl implements RAFileImpl { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("PersistRAFileImpl"); // WARNING!!! Be very carefull when modify this line! There was a case when // entire Hsqldb module has preverification error in case if this line was exactly as: //private static final String kprefix = PersistRAFileImpl.class.getName() + ":"; // It is impossible to explain why it happened but need to be remembered private static final String kprefix = PersistRAFileImpl.class.getName(); private static final String version = "2.2"; //private static final String version = "debug.2.13"; private static final int PAGE_SIZE = 4096; private static final int MAX_CLEAR_PAGES_CACHED = 1; private static Hashtable m_shared = new Hashtable(); private static int m_all_sync_times = 0; private int m_sync_times = 0; // Only for debug purposes private static int id = 0; private final int m_id = ++id; private String m_name; private int m_mode; private long m_nSeekPos; private String getObjName() { return kprefix + "." + version + ":" + m_name + ";pagesize=" + PAGE_SIZE; } private static class ByteArrayWrapper implements Persistable { public byte[] content; public ByteArrayWrapper(byte[] c) { content = c; } }; private static class FileInfoWrapper implements Persistable { public String name; public Long size; public FileInfoWrapper(String n, long s) { name = n; size = new Long(s); } }; private class Page { public byte[] content; public boolean dirty; public Page() { this(null); } public Page(byte[] c) { content = c; dirty = false; } }; private class FileInfo { //private String m_name; private long m_size; private Vector m_pages; private int m_dirty; private int m_use_count; private long getInfoKey() { return StringUtilities.stringHashToLong(getObjName() + ";info"); } private long getPageKey(int n) { return StringUtilities.stringHashToLong(getObjName() + ";page" + Integer.toString(n)); } public FileInfo() { m_dirty = 0; long key = getInfoKey(); PersistentObject persInfo = PersistentStore.getPersistentObject(key); FileInfoWrapper wrapper = (FileInfoWrapper)persInfo.getContents(); m_size = wrapper == null ? 0 : wrapper.size.longValue(); int n = (int)(m_size/PAGE_SIZE) + 1; m_pages = new Vector(n); for (int i = 0; i != n; ++i) m_pages.addElement(new Page()); m_use_count = 0; } public void setPageDirty(int idx) { Page page = (Page)m_pages.elementAt(idx); if (!page.dirty) ++m_dirty; page.dirty = true; } private void unloadClearPages(int needToClear) { for (int i = m_pages.size() - 1; needToClear > 0 && i >= 0; --i) { Page page = (Page)m_pages.elementAt(i); if (page.dirty) continue; page.content = null; --needToClear; } } public byte[] getPage(int n) { Page page = (Page)m_pages.elementAt(n); if (page.content == null) { int clearPages = m_pages.size() - m_dirty; unloadClearPages(clearPages - MAX_CLEAR_PAGES_CACHED + 1); long key = getPageKey(n); PersistentObject persPage = PersistentStore.getPersistentObject(key); ByteArrayWrapper wrapper = (ByteArrayWrapper)persPage.getContents(); page.content = wrapper == null ? new byte[PAGE_SIZE] : wrapper.content; } return page.content; } public long getSize() { return m_size; } public void setSize(long newSize) { int n = (int)(newSize/PAGE_SIZE + 1); if (n != m_pages.size()) { int prevSize = m_pages.size(); m_pages.setSize(n); for (int i = prevSize; i != n; ++i) m_pages.setElementAt(new Page(), i); } m_size = newSize; } public void sync() { if (m_mode != RandomAccessFile.WRITE && m_mode != RandomAccessFile.READ_WRITE) return; if (m_dirty == 0) return; LOG.TRACE("Sync called for " + m_name + ": " + ++m_sync_times + " (" + ++m_all_sync_times + " all), size: " + m_size + ", dirty pages: " + m_dirty); synchronized (PersistentStore.getSynchObject()) { for (int i = m_pages.size() - 1; m_dirty > 0 && i >= 0; --i) { Page page = (Page)m_pages.elementAt(i); if (page.content != null && page.dirty) { //LOG.TRACE("Sync " + m_name + ": page " + i); long key = getPageKey(i); PersistentObject persPage = PersistentStore.getPersistentObject(key); persPage.setContents(new ByteArrayWrapper(page.content)); persPage.commit(); page.dirty = false; --m_dirty; } } int clearPages = m_pages.size() - m_dirty; unloadClearPages(clearPages - MAX_CLEAR_PAGES_CACHED); long key = getInfoKey(); PersistentObject persInfo = PersistentStore.getPersistentObject(key); persInfo.setContents(new FileInfoWrapper(m_name, m_size)); persInfo.commit(); } LOG.TRACE("Sync done for " + m_name); } public void addRef() { ++m_use_count; } public void release() { if (--m_use_count == 0) sync(); } }; private FileInfo m_info = null; public void open(String name, int mode) throws FileNotFoundException { m_name = name; m_mode = mode; synchronized (m_shared) { FileInfo info = (FileInfo)m_shared.get(m_name); if (info == null) { info = new FileInfo(); m_shared.put(m_name, info); } info.addRef(); m_info = info; } m_nSeekPos = 0; LOG.TRACE("Open file: " + m_name); } public void close() throws IOException { LOG.TRACE("Close file: " + m_name); m_info.release(); m_info = null; m_nSeekPos = 0; } public void seek(long pos) throws IOException { m_nSeekPos = pos; } public long seekPos() throws IOException { return m_nSeekPos; } private int getPageNumber(long pos) { int n = (int)(pos/PAGE_SIZE); return n; } public void setSize(long newSize) throws IOException { if (newSize < 0) throw new IllegalArgumentException(); synchronized (m_info) { long size = m_info.getSize(); if (size == newSize) return; m_info.setSize(newSize); } } public long size() throws IOException { synchronized (m_info) { return m_info.getSize(); } } public void sync() throws IOException { if (m_mode != RandomAccessFile.WRITE && m_mode != RandomAccessFile.READ_WRITE) throw new IOException("File is not open in write mode"); synchronized (m_info) { m_info.sync(); } } public int read() throws IOException { synchronized (m_info) { if (m_nSeekPos >= m_info.getSize()) return -1; int n = (int)(m_nSeekPos/PAGE_SIZE); byte[] content = m_info.getPage(n); int pos = (int)(m_nSeekPos % PAGE_SIZE); ++m_nSeekPos; return content[pos]; } } public int read(byte[] b, int off, int len) throws IOException { if (b == null) throw new NullPointerException(); if (off < 0 || len < 0 || off + len > b.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; synchronized (m_info) { long size = m_info.getSize(); if (m_nSeekPos >= size) return -1; if (m_nSeekPos + len > size) len = (int)(size - m_nSeekPos); int startPage = getPageNumber(m_nSeekPos); int endPage = getPageNumber(m_nSeekPos + len); int n = startPage == endPage ? len : PAGE_SIZE - (int)m_nSeekPos%PAGE_SIZE; byte[] content = m_info.getPage(startPage); System.arraycopy(content, (int)(m_nSeekPos%PAGE_SIZE), b, off, n); for (int i = startPage + 1; i <= endPage; ++i) { content = m_info.getPage(i); int howmuch = i == endPage ? (int)((m_nSeekPos + len)%PAGE_SIZE) : PAGE_SIZE; System.arraycopy(content, 0, b, n, howmuch); n += howmuch; } m_nSeekPos += n; return n; } } public void write(int b) throws IOException { synchronized (m_info) { if (m_nSeekPos >= m_info.getSize()) m_info.setSize(m_nSeekPos + 1); int n = getPageNumber(m_nSeekPos); byte[] content = m_info.getPage(n); content[(int)(m_nSeekPos%PAGE_SIZE)] = (byte)b; ++m_nSeekPos; m_info.setPageDirty(n); } } public void write(byte[] b, int off, int len) throws IOException { if (b == null) throw new NullPointerException(); if (off < 0 || len < 0 || off + len > b.length) throw new IndexOutOfBoundsException(); if (len == 0) return; synchronized (m_info) { if (m_nSeekPos + len >= m_info.getSize()) m_info.setSize(m_nSeekPos + len); int startPage = getPageNumber(m_nSeekPos); int endPage = getPageNumber(m_nSeekPos + len); int n = startPage == endPage ? len : PAGE_SIZE - (int)m_nSeekPos%PAGE_SIZE; byte[] content = m_info.getPage(startPage); System.arraycopy(b, off, content, (int)(m_nSeekPos%PAGE_SIZE), n); m_info.setPageDirty(startPage); for (int i = startPage + 1; i <= endPage; ++i) { int howmuch = i == endPage ? (int)((m_nSeekPos + len)%PAGE_SIZE) : PAGE_SIZE; content = m_info.getPage(i); System.arraycopy(b, off + n, content, 0, howmuch); m_info.setPageDirty(i); n += howmuch; } m_nSeekPos += n; } } }
package de.avgl.dmp.controller; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Properties; import javax.ws.rs.core.UriBuilder; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; /** * Main class. */ public class Main { private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Main.class); // Base URI the Grizzly HTTP server will listen on public final String BASE_URI; public Main(Properties properties) { final String host = properties.getProperty("backend_http_server_host"); final int port = Integer.valueOf(properties.getProperty("backend_http_server_port")); final URI baseUri = UriBuilder.fromUri("http://" + host).port(port).path("dmp/").build(); BASE_URI = baseUri.toString(); } public String getBaseUri() { return BASE_URI; } private static Properties loadProperties(String propertiesPath) { final InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesPath); final Properties properties = new Properties(); try { properties.load(inStream); } catch (IOException e) { log.debug("could not load properties"); } return properties; } private static Properties loadProperties() { return loadProperties("dmp.properties"); } /** * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application. * * @return Grizzly HTTP server. */ public HttpServer startServer() { // create a resource config that scans for JAX-RS resources and // providers // in de.avgl.dmp.controller.resources package final ResourceConfig rc = new ResourceConfig() // .register(JacksonJaxbJsonProvider.class) .packages("de.avgl.dmp.controller.resources"); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); } public static Main create(int port) { final Properties properties = loadProperties(); properties.setProperty("backend_http_server_port", Integer.valueOf(port).toString()); return new Main(properties); } public static Main create() { final Properties properties = loadProperties(); return new Main(properties); } /** * Main method. * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { final Main main = Main.create(); final HttpServer server = main.startServer(); System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\nHit enter to stop it...", main.getBaseUri())); System.in.read(); server.stop(); } }
package org.cinchapi.concourse; import java.net.ConnectException; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import javax.annotation.Nullable; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.cinchapi.common.configuration.Configurations; import org.cinchapi.common.time.Time; import org.cinchapi.common.tools.Transformers; import org.cinchapi.concourse.thrift.AccessToken; import org.cinchapi.concourse.thrift.ConcourseService; import org.cinchapi.concourse.thrift.Operator; import org.cinchapi.concourse.thrift.TObject; import org.cinchapi.concourse.thrift.TransactionToken; import org.cinchapi.concourse.util.Convert; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Lists; /** * <p> * Concourse is a schemaless distributed version control database with * serializable transactions and full-text search. Concourse provides a more * intuitive approach to data management that is easy to deploy, access and * scale with minimal tuning while also maintaining the referential integrity, * atomicity, consistency, isolability and durability found in traditional * database systems. * </p> * <h2>Data Model</h2> * <p> * The Concourse data model is lightweight and flexible which enables it to * support any kind of data at very large scales. Concourse trades unnecessary * structural notions of predefined schemas, tables and indexes for a more * natural modeling of data based solely on the following concepts: * </p> * <p> * <ul> * <li><strong>Record</strong> &mdash; A logical grouping of information about a * single person, place, thing (i.e. object). Each record is a collection of * key/value mappings. * <li><strong>Primary Key</strong> &mdash; An immutable marker that is used to * identify a single Record. Each Record has a unique Primary Key. * <li><strong>Key</strong> &mdash; A label that maps to one or more distinct * Values. A Record can have many different Keys. And since Records are * independent, the Keys in one Record do not affect the Keys in another Record. * <li><strong>Value</strong> &mdash; A typed quantity that is mapped from a Key * in a Record. * </ul> * </p> * <h4>Data Types</h4> * <p> * Concourse natively stores most of the Java primitives: boolean, double, * float, integer, long, and string (utf-8 encoded). Otherwise, the value of the * {@link #toString()} method for other, non-primitive Objects is used to so * those Objects should return a string representation from which the Object can * be reconstructed (i.e. JSON, base64 encoded binary, etc). * </p> * <h4>Links</h4> * <p> * Concourse supports links between Records and enforces referential integrity * with the ability to map a key in one Record to the PrimaryKey of another * Record using the {@link #link(String, long, long)} and * {@link #link(String, long, String, long)} methods. * * <h2>Transactions</h2> * <p> * By default, Concourse conducts every operation in {@code autocommit} mode * where every change is immediately written. Concourse supports the ability to * group and stage operations in transactions that are atomic, consistent, * isolated, and durable (ACID) using the {@link #stage()}, {@link #commit()} * and {@link #abort()} methods. * * </p> * * @author jnelson */ public interface Concourse { /** * Discard any changes that are currently staged for commit. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be immediately written to the * database. * </p> */ public void abort(); /** * Add {@code key} as {@code value} in {@code record} if no such mapping * currently exist. No other mappings are affected because {@code key} in * {@code record} may map to multiple distinct values. * * @param key * @param value * @param record * @return {@code true} if the mapping is added */ public boolean add(String key, Object value, long record); /** * Audit {@code record} and return a log of revisions. * * @param record * @return a mapping of timestamps to revision descriptions */ public Map<DateTime, String> audit(long record); /** * Audit {@code key} in {@code record} and return a log of revisions. * * @param key * @param record * @return a mapping of timestamps to revision descriptions */ public Map<DateTime, String> audit(String key, long record); /** * Clear {@code key} in {@code record} and remove all the currently * contained mappings. * * @param record */ public void clear(String key, long record); /** * Attempt to permanently commit all the changes that are currently staged. * This function returns {@code true} if and only if all the changes can be * successfully applied to the database.Otherwise, this function returns * {@code false} and all the changes are aborted. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be immediately written to the * database. * </p> */ public boolean commit(); /** * Create a new Record and return its Primary Key. * * @return the Primary Key of the new Record */ public long create(); /** * Describe {@code record} and return its keys that currently map to at * least one value. If there are no such keys, an empty Set is returned. * * @param record * @return the populated keys */ public Set<String> describe(long record); /** * Describe {@code record} at {@code timestamp} and return its keys that * mapped to at least one value. If there were no such keys, an empty Set is * returned. * * @param record * @param timestamp * @return the keys for populated keys */ public Set<String> describe(long record, DateTime timestamp); /** * Disconnect from the remote Concourse server. */ public void exit(); /** * Fetch {@code key} from {@code record} and return the currently mapped * values. If there are none, an empty Set is returned. * * @param key * @param record * @return the contained values */ public Set<Object> fetch(String key, long record); /** * Fetch {@code key} from {@code record} at {@code timestamp} and return the * values that were mapped. If there were none, an empty Set is returned. * * @param key * @param record * @param timestamp * @return the contained values */ public Set<Object> fetch(String key, long record, DateTime timestamp); /** * Find {@code key} {@code operator} {@code values} at {@code timestamp} and * return the records that satisfied the criteria. This is analogous to a * SELECT query in a RDBMS. If there were no records that matched the * criteria, an empty Set is returned. * * @param timestamp * @param key * @param operator * @param values * @return the records that match the criteria */ public Set<Long> find(DateTime timestamp, String key, Operator operator, Object... values); /** * Find {@code key} {@code operator} {@code values} and return the records * that satisfy the criteria. This is analogous to a SELECT query in a * RDBMS. If there are now records that match the criteria, an empty Set is * returned. * * @param key * @param operator * @param values * @return the records that match the criteria */ public Set<Long> find(String key, Operator operator, Object... values); /** * Get {@code key} from {@code record} and return the first mapped value or * {@code null} if there are none. Compared to {@link #fetch(String, long)}, * this method is suited for cases when the caller is certain that * {@code key} in {@code record} maps to a single value of type {@code T}. * * @param key * @param record * @return the first mapped value */ public <T> T get(String key, long record); /** * Get {@code key} from {@code record} at {@code timestamp} and return the * first mapped value or {@code null} if there were none. Compared to * {@link #fetch(String, long, long)}, this method is suited for cases when * the caller is certain that {@code key} in {@code record} mapped to a * single value of type {@code T} at {@code timestamp}. * * @param key * @param record * @param timestamp * @return the first mapped value */ public <T> T get(String key, long record, DateTime timestamp); /** * Link {@code key} in {@code source} to {@code destination}. In other * words, a {@link Link} to {@code destination} is mapped from {@code key} * in {@code source}. * * @param key * @param source * @param destination * @return {@code true} if the one way link is added */ public boolean link(String key, long source, long destination); /** * Link {@code sourceKey} in {@code source} to {@code destinationKey} in * {@code destination}. In other words, a {@link Link} to * {@code destination} is mapped from {@code sourceKey} in {@code source} * and a {@link Link} to {@code source} is mapped from * {@code destinationKey} in {@code destination}. * * @param sourceKey * @param source * @param destinationKey * @param destination * @return {@code true} if a two way link exists between {@code source} and * {@code destination} */ public boolean link(String sourceKey, long source, String destinationKey, long destination); /** * Ping {@code record} and return {@code true} if there is * <em>currently</em> at least one populated key. * * @param record * @return {@code true} if {@code record} currently contains data */ public boolean ping(long record); /** * Remove {@code key} as {@code value} from {@code record} if the mapping * currently exists. No other mappings are affected. * * @param key * @param value * @param record * @return {@code true} if the mapping is removed */ public boolean remove(String key, Object value, long record); /** * Revert {@code key} in {@code record} to {@code timestamp}. This method * restores the key to its state at {@code timestamp} by reversing all * revisions that have occurred since. * <p> * Please note that this method <strong>does not</strong> {@code rollback} * any revisions, but creates <em>new</em> revisions that are the inverse of * all revisions since {@code timestamp} in reverse order. * </p> * * @param key * @param record * @param timestamp */ public void revert(String key, long record, DateTime timestamp); /** * Search {@code key} for {@code query} and return the records that match * the fulltext query. If there are no such records, an empty Set is * returned. * * @param key * @param query * @return the records that match the query */ public Set<Long> search(String key, String query); /** * Set {@code key} as {@code value} in {@code record}. This is a convenience * method that clears the values currently mapped from {@code key} and adds * a new mapping for {@code value}. * * @param key * @param value * @param record * @return {@code true} if the old mappings are removed and the new one is * added */ public boolean set(String key, Object value, long record); /** * Turn on {@code staging} mode so that all subsequent changes are * collected in a staging area before possibly being committed to the * database. Staged operations are guaranteed to be reliable, all or nothing * units of work that allow correct recovery from failures and provide * isolation between clients so the database is always in a consistent state * (i.e. a transaction). * <p> * After this method returns, all subsequent operations will be done in * {@code staging} mode until either {@link #abort()} or {@link #commit()} * is invoked. * </p> */ public void stage(); /** * Verify {@code key} equals {@code value} in {@code record} and return * {@code true} if {@code value} is currently mapped. * * @param key * @param value * @param record * @return {@code true} if the mapping exists */ public boolean verify(String key, Object value, long record); /** * Verify {@code key} equaled {@code value} in {@code record} at * {@code timestamp} and return {@code true} if {@code value} was mapped. * * @param key * @param value * @param record * @param timestamp * @return {@code true} if the mapping existed */ public boolean verify(String key, Object value, long record, DateTime timestamp); /** * The implementation of the {@link Concourse} interface that establishes a * connection with the remote server and handles communication. This class * is a more user friendly wrapper around a Thrift * {@link ConcourseService.Client}. * * @author jnelson */ public final static class Client implements Concourse { private static final Logger log = LoggerFactory .getLogger(Concourse.class); /** * All configuration information is contained in this prefs file. */ private static final String configFileName = "concourse.prefs"; /** * Handler for configuration preferences. */ private static final PropertiesConfiguration config = Configurations .loadPropertiesConfiguration(configFileName); /** * Represents a request to respond to a query using the current state as * opposed to the history. */ private static DateTime now = new DateTime(0); private final String username; private final String password; /** * The Thrift client that actually handles all RPC communication. */ private final ConcourseService.Client client; /** * The client keeps a copy of its {@link AccessToken} and passes it to * the * server for each remote procedure call. The client will * re-authenticate * when necessary using the username/password read from the prefs file. */ private AccessToken creds = null; /** * Whenever the client starts a Transaction, it keeps a * {@link TransactionToken} so that the server can stage the changes in * the * appropriate place. */ private TransactionToken transaction = null; /** * Create a new Client connection to the Concourse server specified in * {@code concourse.prefs} and return a handler to facilitate database * interaction. */ public Client() { this(config.getString("CONCOURSE_SERVER_HOST", "localhost"), config .getInt("CONCOURSE_SERVER_PORT", 1717), config.getString( "USERNAME", "admin"), config.getString("PASSWORD", "admin")); } /** * Create a new Client connection to a Concourse server and return a * handler to facilitate database interaction. * * @param host * @param port * @param username * @param password */ private Client(String host, int port, String username, String password) { this.username = username; this.password = password; TTransport transport = new TSocket(host, port); try { transport.open(); TProtocol protocol = new TBinaryProtocol(transport); client = new ConcourseService.Client(protocol); authenticate(); log.info("Connected to Concourse server at {}:{}.", host, port); Runtime.getRuntime().addShutdownHook(new Thread("shutdown") { @Override public void run() { if(transaction != null) { abort(); log.warn("Prior to shutdown, the client was in the middle " + "of an uncommitted transaction. That transaction " + "has been aborted and all of its uncommited changes " + "have been lost."); } } }); } catch (TTransportException e) { if(e.getCause() instanceof ConnectException) { log.error("Unable to establish a connection with the " + "Concourse server at {}:{}. Please check " + "that the remote service is actually running " + "and accepting connections.", host, port); } throw Throwables.propagate(e); } } @Override public void abort() { execute(new Callable<Void>() { @Override public Void call() throws Exception { if(transaction != null) { client.abort(creds, transaction); transaction = null; } else { log.warn("There is no transaction to abort."); } return null; } }); } @Override public boolean add(final String key, final Object value, final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.add(key, Convert.javaToThrift(value), record, creds, transaction); } }); } @Override public Map<DateTime, String> audit(final long record) { return execute(new Callable<Map<DateTime, String>>() { @Override public Map<DateTime, String> call() throws Exception { Map<Long, String> audit = client.audit(record, null, creds, transaction); return Transformers.transformMap(audit, new Function<Long, DateTime>() { @Override public DateTime apply(Long input) { return Convert.unixToJoda(input); } }); } }); } @Override public Map<DateTime, String> audit(final String key, final long record) { return execute(new Callable<Map<DateTime, String>>() { @Override public Map<DateTime, String> call() throws Exception { Map<Long, String> audit = client.audit(record, key, creds, transaction); return Transformers.transformMap(audit, new Function<Long, DateTime>() { @Override public DateTime apply(Long input) { return Convert.unixToJoda(input); } }); } }); } @Override public void clear(String key, long record) { Set<Object> values = fetch(key, record); for (Object value : values) { remove(key, value, record); } } @Override public boolean commit() { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean result = client.commit(creds, transaction); transaction = null; return result; } }); } @Override public long create() { return Time.now(); // TODO get a primary key using a plugin } @Override public Set<String> describe(long record) { return describe(record, now); } @Override public Set<String> describe(final long record, final DateTime timestamp) { return execute(new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { return client.describe(record, Convert.jodaToUnix(timestamp), creds, transaction); } }); } @Override public void exit() { client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); log.info("The client has disconnected"); } @Override public Set<Object> fetch(String key, long record) { return fetch(key, record, now); } @Override public Set<Object> fetch(final String key, final long record, final DateTime timestamp) { return execute(new Callable<Set<Object>>() { @Override public Set<Object> call() throws Exception { Set<TObject> values = client.fetch(key, record, Convert.jodaToUnix(timestamp), creds, transaction); return Transformers.transformSet(values, new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert.thriftToJava(input); } }); } }); } @Override public Set<Long> find(final DateTime timestamp, final String key, final Operator operator, final Object... values) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find(key, operator, Lists.transform( Lists.newArrayList(values), new Function<Object, TObject>() { @Override public TObject apply(Object input) { return Convert.javaToThrift(input); } }), Convert.jodaToUnix(timestamp), creds, transaction); } }); } @Override public Set<Long> find(String key, Operator operator, Object... values) { return find(now, key, operator, values); } @Override @Nullable public <T> T get(String key, long record) { return get(key, record, now); } @SuppressWarnings("unchecked") @Override @Nullable public <T> T get(String key, long record, DateTime timestamp) { Set<Object> values = fetch(key, record, timestamp); if(!values.isEmpty()) { return (T) values.iterator().next(); } return null; } @Override public boolean link(String key, long source, long destination) { return add(key, Link.to(destination), source); } @Override public boolean link(String sourceKey, long source, String destinationKey, long destination) { return link(sourceKey, source, destination) ^ link(destinationKey, destination, source); } @Override public boolean ping(final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.ping(record, creds, transaction); } }); } @Override public boolean remove(final String key, final Object value, final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.remove(key, Convert.javaToThrift(value), record, creds, transaction); } }); } @Override public void revert(final String key, final long record, final DateTime timestamp) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.revert(key, record, Convert.jodaToUnix(timestamp), creds, transaction); return null; } }); } @Override public Set<Long> search(final String key, final String query) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.search(key, query, creds, transaction); } }); } @Override public boolean set(String key, Object value, long record) { Set<Object> values = fetch(key, record); for (Object v : values) { remove(key, v, record); } return add(key, value, record); } @Override public void stage() { execute(new Callable<Void>() { @Override public Void call() throws Exception { transaction = client.stage(creds); return null; } }); } @Override public boolean verify(String key, Object value, long record) { return verify(key, value, record, now); } @Override public boolean verify(final String key, final Object value, final long record, final DateTime timestamp) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.verify(key, Convert.javaToThrift(value), record, Convert.jodaToUnix(timestamp), creds, transaction); } }); } /** * Authenticate the {@link #username} and {@link #password} and populate * {@link #creds} with the appropriate AccessToken. */ private void authenticate() { try { creds = client.login(username, password); } catch (TException e) { throw Throwables.propagate(e); } } /** * Execute the task defined in {@code callable}. This method contains * retry logic to handle cases when {@code creds} expires and must be * updated. * * @param callable * @return the task result */ private <T> T execute(Callable<T> callable) { try { return callable.call(); } catch (SecurityException e) { authenticate(); return execute(callable); } catch (Exception e) { throw Throwables.propagate(e); } } } }
package net.ashishb.android_time_tracker; import android.Manifest.permission; import android.app.ActivityManager; import android.app.ListActivity; import android.content.Intent; import android.content.Context; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ImageView; import android.widget.TextView; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.Vector; public class Main extends ListActivity { public static final String TAG = "AndroidTimeTracker"; private ArrayAdapter<String> listAdapter; private ListView listView; // TODO: add a UI Settings element for this setting. private boolean excludeLauncherPackage = true; private PackageManager pm = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); Context context = getApplicationContext(); context.startService(new Intent(context, TimeTrackingService.class)); pm = getPackageManager(); } @Override public void onResume() { super.onResume(); String launcherPackageName = this.getLauncherPackageName(); String packageName = this.getApplicationContext().getPackageName(); listView = getListView(); listView.setTextFilterEnabled(true); Set< Entry<String, Integer> > values = TimeTrackingService.getPackageUseCount().entrySet(); if (values.size() == 0) { // This is really crude. I need to improve on this. finish(); // SystemClock.sleep(1000); // values = TimeTrackingService.getPackageUseCount().entrySet(); } TreeSet< Entry<String, Integer>> sortedSet = new TreeSet( new Comparator<Entry<String, Integer>>() { @Override public int compare( Entry<String, Integer> e1, Entry<String, Integer> e2) { return (-1) * (e1.getValue() - e2.getValue()); } }); sortedSet.addAll(values); // Vector<String> entries = new Vector<String>(); Vector<PackageInfoEntry> entries = new Vector<PackageInfoEntry>(); long sum = 0; Iterator<Entry<String, Integer>> iterator = sortedSet.iterator(); while (iterator.hasNext()) { Entry<String, Integer> entry = iterator.next(); if (!entry.getKey().equals(launcherPackageName) && !entry.getKey().equals(packageName)) { sum += entry.getValue(); } } Iterator<Entry<String, Integer>> iterator2 = sortedSet.iterator(); while (iterator2.hasNext()) { Entry<String, Integer> entry = iterator2.next(); // Ignore Launcher app. // Ignore the time tracker app. if (!entry.getKey().equals(launcherPackageName) && !entry.getKey().equals(packageName)) { double value = (double)entry.getValue()/sum; if (value > 0.01) { try { PackageInfoEntry tmp = new PackageInfoEntry(); tmp.packageLabel = pm.getApplicationInfo( entry.getKey(), PackageManager.GET_META_DATA).loadLabel(pm).toString(); tmp.packageName = entry.getKey(); tmp.packageIcon = pm.getApplicationIcon(entry.getKey()); tmp.usage = value; entries.add(tmp); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Trying to read label of non existant package " + entry.getKey()); } } } } listAdapter = new PackageInfoArrayAdapter(this, entries); listView.setAdapter(listAdapter); } public String getLauncherPackageName() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); ResolveInfo resolveInfo = getPackageManager().resolveActivity( intent, PackageManager.MATCH_DEFAULT_ONLY); return resolveInfo.activityInfo.packageName; } } class PackageInfoEntry { public String packageName; // Fully qualified name of the package. public String packageLabel; // Human readable label of the package. public Drawable packageIcon; // Icon of the package; public double usage; // Expressed as a fraction of total usage. }; class PackageInfoArrayAdapter extends ArrayAdapter<String> { private final Context context; private final Vector<PackageInfoEntry> values; public PackageInfoArrayAdapter(Context context, Vector<PackageInfoEntry> values) { super(context, R.layout.main, new String[values.size()]); this.context = context; this.values = values; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.main, parent, false); TextView textView = (TextView) rowView.findViewById(R.id.label); ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); // Set the package label (and not fully qualified name) as text. textView.setText(values.get(position).packageLabel + "\t" + (int)(values.get(position).usage * 100) + "%"); String s = values.get(position).packageName; imageView.setImageDrawable(values.get(position).packageIcon); Log.d(Main.TAG, "Icon is " + values.get(position).packageIcon); return rowView; } }
package de.uka.ipd.sdq.beagle.core; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.ArrayList; import java.util.List; public class SeffBranch implements MeasurableSeffElement { /** * Serialisation version UID, see {@link java.io.Serializable}. */ private static final long serialVersionUID = -1525692970296450080L; /** * All branches for this SeffBranch. */ private final List<CodeSection> branches; public SeffBranch(final List<CodeSection> branches) { if (branches.size() <= 1) { throw new IllegalArgumentException( "The code section set for the SeffBranch had less than two code sections"); } Validate.noNullElements(branches); this.branches = new ArrayList<>(branches); } @Override public boolean equals(final Object object) { if (object == null) { return false; } if (object == this) { return true; } if (object.getClass() != this.getClass()) { return false; } final SeffBranch other = (SeffBranch) object; return new EqualsBuilder().append(this.branches, other.branches).isEquals(); } /** * Gives a set of valid code sections representing a branch of this SeffBranch. * * @return A set of valid code sections representing a branch of this SeffBranch. They * fulfil the following property: Two points of execution exist, the so called * beginning and ending of this branch, with the following properties: When * you would insert an (empty) code line at the beginning and an (empty) code * line at the ending, those would form a valid code section with the * beginning line as first line and the line at the ending as last line. And * each time the beginning point was reached, exactly one code section of this * branch gets executed immediately after that. Immediately after that, the * ending point is reached. The set contains at least {@code 2} code sections. * The set is never {@code null}. This set never contains {@code null} * entries. */ public List<CodeSection> getBranches() { return this.branches; } @Override public int hashCode() { // you pick a hard-coded, randomly chosen, non-zero, odd number // ideally different for each class return new HashCodeBuilder(21, 49).append(this.branches).toHashCode(); } @Override public String toString() { return new ToStringBuilder(this).append("branches", this.branches).toString(); } }
// This file is part of the "OPeNDAP Web Coverage Service Project." // Authors: // Haibo Liu <haibo@iri.columbia.edu> // Nathan David Potter <ndp@opendap.org> // Benno Blumenthal <benno@iri.columbia.edu> // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // 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 // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. package opendap.semantics.IRISail; import opendap.xml.Transformer; import org.jdom.output.XMLOutputter; import org.openrdf.model.*; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.*; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.slf4j.Logger; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; public class RdfImporter { private Logger log; private HashSet<String> urlsToBeIgnored; private Vector<String> imports; private String localResourceDir; public RdfImporter(String resourceDir) { log = org.slf4j.LoggerFactory.getLogger(this.getClass()); urlsToBeIgnored = new HashSet<String>(); imports = new Vector<String>(); this.localResourceDir = resourceDir; } public void reset() { urlsToBeIgnored.clear(); imports.clear(); } public String getLocalResourceDirUrl(){ if(localResourceDir.startsWith("file:")) return localResourceDir; return "file:"+ localResourceDir; } public boolean importReferencedRdfDocs(Repository repository, Vector<String> doNotImportUrls) { boolean repositoryChanged = false; Vector<String> rdfDocList = new Vector<String>(); if (doNotImportUrls != null) urlsToBeIgnored.addAll(doNotImportUrls); findNeededRDFDocuments(repository, rdfDocList); while (!rdfDocList.isEmpty()) { if(addNeededRDFDocuments(repository, rdfDocList)){ repositoryChanged = true; } rdfDocList.clear(); findNeededRDFDocuments(repository, rdfDocList); } return repositoryChanged; } /** * Find all rdfcache:RDFDocuments that are referenced by existing documents in the repository. * * @param repository * @param rdfDocs */ private void findNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) { TupleQueryResult result = null; List<String> bindingNames; RepositoryConnection con = null; try { con = repository.getConnection(); String queryString = "(SELECT doc " + "FROM {doc} rdf:type {rdfcache:"+Terms.startingPointType +"} " + "union " + "SELECT doc " + "FROM {tp} rdf:type {rdfcache:"+Terms.startingPointType +"}; rdfcache:"+Terms.dependsOnContext+" {doc}) " + "MINUS " + "SELECT doc " + "FROM CONTEXT "+"rdfcache:"+Terms.cacheContext+" {doc} rdfcache:"+Terms.lastModifiedContext+" {lastmod} " + "USING NAMESPACE " + "rdfcache = <" + Terms.rdfCacheNamespace + ">"; log.debug("Query for NeededRDFDocuments: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("doc"); String doc = firstValue.stringValue(); if (!rdfDocs.contains(doc) && !imports.contains(doc) && !urlsToBeIgnored.contains(doc) && doc.startsWith("http: rdfDocs.add(doc); log.debug("Adding to rdfDocs: " + doc); } } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } finally { if (result != null) { try { result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } try { con.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException! in findNeededRDFDocuments() Msg: " + e.getMessage()); } } log.info("Number of needed files identified: " + rdfDocs.size()); } /** * Add the each of the RDF documents whose URL's are in the passed Vector to the Repository. * * @param repository * @param rdfDocs * @return * */ private boolean addNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) { URI uriaddress; long inferStartTime, inferEndTime; inferStartTime = new Date().getTime(); String documentURL = null; RepositoryConnection con = null; int skipCount = 0; String contentType = ""; HttpURLConnection httpConnection = null; InputStream importIS = null; boolean addedDocument = false; try { con = repository.getConnection(); log.debug("addNeededRDFDocuments(): rdfDocs.size=" + rdfDocs.size()); skipCount = 0; while (!rdfDocs.isEmpty()) { documentURL = rdfDocs.remove(0); try { log.debug("addNeededRDFDocuments(): Checking import URL: " + documentURL); if (urlsToBeIgnored.contains(documentURL)) { log.error("addNeededRDFDocuments(): Previous server error, Skipping " + documentURL); } else { URL myurl = new URL(documentURL); int rsCode; httpConnection = (HttpURLConnection) myurl.openConnection(); log.debug("addNeededRDFDocuments(): Connected to import URL: " + documentURL); rsCode = httpConnection.getResponseCode(); contentType = httpConnection.getContentType(); log.debug("addNeededRDFDocuments(): Got HTTP status code: " + rsCode); log.debug("addNeededRDFDocuments(): Got Content Type: " + contentType); if (rsCode == -1) { log.error("addNeededRDFDocuments(): Unable to get an HTTP status code for resource " + documentURL + " WILL NOT IMPORT!"); urlsToBeIgnored.add(documentURL); } else if (rsCode != 200) { log.error("addNeededRDFDocuments(): Error! HTTP status code " + rsCode + " Skipping documentURL " + documentURL); urlsToBeIgnored.add(documentURL); } else { log.debug("addNeededRDFDocuments(): Import URL appears valid ( " + documentURL + " )"); //@todo make this a more robust String transformToRdfUrl = RepositoryOps.getUrlForTransformToRdf(repository, documentURL); log.debug("addNeededRDFDocuments(): Transformation = " + transformToRdfUrl); if (transformToRdfUrl != null){ InputStream inStream; log.info("addNeededRDFDocuments(): Transforming " + documentURL +" with "+ transformToRdfUrl); Transformer t = new Transformer(transformToRdfUrl); inStream = t.transform(documentURL); log.info("addNeededRDFDocuments(): Finished transforming RDFa " + documentURL); importUrl(con, documentURL, contentType, inStream); addedDocument = true; }else if(documentURL.endsWith(".owl") || documentURL.endsWith(".rdf")) { importIS = httpConnection.getInputStream(); importUrl(con, documentURL, contentType, importIS); addedDocument = true; } else if (documentURL.endsWith(".xsd")) { // XML Schema Document transformToRdfUrl = getLocalResourceDirUrl() + "xsl/xsd2owl.xsl"; log.info("addNeededRDFDocuments(): Transforming Schema Document'" + documentURL +"' with '"+ transformToRdfUrl); InputStream inStream; Transformer t = new Transformer(new StreamSource(transformToRdfUrl)); inStream = t.transform(new StreamSource(documentURL)); //inStream = transform(new StreamSource(documentURL),localResourceDir+transformToRdfUrl); log.info("addNeededRDFDocuments(): Finished transforming Xml Schema Document: '" + documentURL+"'"); importUrl(con, documentURL, contentType, inStream); addedDocument = true; } else { if ((contentType != null) && (contentType.equalsIgnoreCase("text/plain") || contentType.equalsIgnoreCase("text/xml") || contentType.equalsIgnoreCase("application/xml") || contentType.equalsIgnoreCase("application/rdf+xml")) ) { importUrl(con, documentURL, contentType, importIS); log.info("addNeededRDFDocuments(): Imported non owl/xsd from " + documentURL); addedDocument = true; } else { log.warn("addNeededRDFDocuments(): SKIPPING Import URL '" + documentURL + "' It does not appear to reference a " + "document that I know how to process."); urlsToBeIgnored.add(documentURL); //skip this file skipCount++; } log.info("addNeededRDFDocuments(): Total non owl/xsd files skipped: " + skipCount); } } } // while (!rdfDocs.isEmpty() } catch (Exception e) { log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage()); if (documentURL != null){ log.warn("addNeededRDFDocuments(): SKIPPING Import URL '"+ documentURL +"' Because bad things happened when we tried to get it."); urlsToBeIgnored.add(documentURL); //skip this file } } finally { if (importIS != null) try { importIS.close(); } catch (IOException e) { log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage()); } if (httpConnection != null) httpConnection.disconnect(); } } } catch (RepositoryException e) { log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error("addNeededRDFDocuments(): Caught an RepositoryException! in addNeededRDFDocuments() Msg: " + e.getMessage()); } } inferEndTime = new Date().getTime(); double inferTime = (inferEndTime - inferStartTime) / 1000.0; log.debug("addNeededRDFDocuments(): Import takes " + inferTime + " seconds"); } return addedDocument; } private void importUrl(RepositoryConnection con, String importURL, String contentType, InputStream importIS) throws IOException, RDFParseException, RepositoryException { if (!this.imports.contains(importURL)) { // not in the repository yet log.info("Importing URL " + importURL); ValueFactory valueFactory = con.getValueFactory(); URI importUri = new URIImpl(importURL); con.add(importIS, importURL, RDFFormat.RDFXML, (Resource) importUri); RepositoryOps.setLTMODContext(importURL, con, valueFactory); // set last modified time of the context RepositoryOps.setContentTypeContext(importURL, contentType, con, valueFactory); log.info("Finished importing URL " + importURL); imports.add(importURL); } else { log.error("Import URL '"+importURL+"' already has been imported! SKIPPING!"); } } public static void main(String[] args) throws Exception { StreamSource httpSource = new StreamSource("http://schemas.opengis.net/wcs/1.1/wcsAll.xsd"); StreamSource fileSource = new StreamSource("file:/Users/ndp/OPeNDAP/Projects/Hyrax/swdev/trunk/olfs/resources/WCS/xsl/xsd2owl.xsl"); StreamSource transform = fileSource; StreamSource document = httpSource; XMLOutputter xmlo = new XMLOutputter(); xmlo.output(Transformer.getTransformedDocument(document,transform),System.out); } }
package org.amoeba.examples.entity; import java.util.ArrayList; import java.util.List; import org.amoeba.activity.GameActivity; import org.amoeba.entity.sprite.TextSprite; import org.amoeba.graphics.texture.TextOptions; import android.graphics.Color; import android.graphics.Paint.Align; import android.graphics.Typeface; import android.os.Bundle; public class TextExample extends GameActivity { private List<TextSprite> textSprites; private final static int[] textSizes = {12, 14, 16, 18, 22, 24, 26, 28, 32, 48, 64, 128}; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); textSprites = new ArrayList<TextSprite>(); for (int textSize : textSizes) { TextOptions options = new TextOptions(textSize, Color.BLUE, Align.CENTER, Typeface.DEFAULT, true); textSprites.add(getGraphicsService().getTextFactory().createTextSprite("Text size: " + textSize, options)); } } @Override public void onSurfaceChanged(final int width, final int height) { float yPosition = 0.0f; for (TextSprite text : textSprites) { text.setPosition(width / 2, yPosition); yPosition += text.getHeight(); } } }
package com.ibm.sk.ff.gui.client; import static com.ibm.sk.ff.gui.common.GUIOperations.CLOSE; import static com.ibm.sk.ff.gui.common.GUIOperations.CREATE_GAME; import static com.ibm.sk.ff.gui.common.GUIOperations.EVENT_POLL; import static com.ibm.sk.ff.gui.common.GUIOperations.REMOVE; import static com.ibm.sk.ff.gui.common.GUIOperations.SCORE; import static com.ibm.sk.ff.gui.common.GUIOperations.SET; import static com.ibm.sk.ff.gui.common.GUIOperations.SHOW_INIT_MENU; import static com.ibm.sk.ff.gui.common.GUIOperations.SHOW_RESULT; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ibm.sk.ff.gui.common.events.GuiEvent; import com.ibm.sk.ff.gui.common.events.GuiEventListener; import com.ibm.sk.ff.gui.common.mapper.Mapper; import com.ibm.sk.ff.gui.common.objects.gui.GAntFoodObject; import com.ibm.sk.ff.gui.common.objects.gui.GAntObject; import com.ibm.sk.ff.gui.common.objects.gui.GFoodObject; import com.ibm.sk.ff.gui.common.objects.gui.GUIObject; import com.ibm.sk.ff.gui.common.objects.gui.GUIObjectCrate; import com.ibm.sk.ff.gui.common.objects.gui.GUIObjectTypes; import com.ibm.sk.ff.gui.common.objects.operations.CloseData; import com.ibm.sk.ff.gui.common.objects.operations.CreateGameData; import com.ibm.sk.ff.gui.common.objects.operations.InitMenuData; import com.ibm.sk.ff.gui.common.objects.operations.ResultData; import com.ibm.sk.ff.gui.common.objects.operations.ScoreData; import com.ibm.sk.ff.gui.common.objects.operations.Step; public class GUIFacade { private final Client CLIENT; private final List<GuiEventListener> guiEventListeners = new ArrayList<>(); private final List<GAntFoodObject> antFoodObjects = new ArrayList<>(); private final Map<GAntObject, GAntFoodObject> notRenderedYet = new HashMap<>(); private List<Step> steps; public GUIFacade() { this.CLIENT = new Client(); new Thread(new Runnable() { @Override public void run() { final int sleepTime = Integer.parseInt(Config.SERVER_POLL_INTERVAL.toString()); while (true) { try { Thread.sleep(sleepTime); checkEvents(); } catch (final Exception e) { e.printStackTrace(); } } } }).start(); } public void set(final GUIObject object) { set(new GUIObject[] {object}); } public void set(final GUIObject[] o) { if (o != null && o.length > 0) { final GUIObject [] objects = map(o); final GUIObjectCrate crate = new GUIObjectCrate(); crate.sortOut(objects); this.CLIENT.postMessage(SET.toString(), Mapper.INSTANCE.pojoToJson(crate)); // steps.add(new Step(SET, crate)); } sendNotYetRenderedData(o); } private void sendNotYetRenderedData(final GUIObject[] o) { if (this.notRenderedYet.size() > 0) { final List<GAntObject> antsToRemove = new ArrayList<>(); final List<GFoodObject> foodsToRemove = new ArrayList<>(); this.notRenderedYet.values().stream().forEach(af -> { antsToRemove.add(af.getAnt()); foodsToRemove.add(af.getFood()); } ); remove(antsToRemove.stream().toArray(GAntObject[]::new)); remove(foodsToRemove.stream().toArray(GFoodObject[]::new)); this.CLIENT.postMessage( SET.toString() + "/" + GUIObjectTypes.ANT_FOOD.toString(), Mapper.INSTANCE.pojoToJson(mapNotYetRendered(o)) ); } } private GAntFoodObject[] mapNotYetRendered(final GUIObject[] o) { final List<GAntFoodObject> ret = new ArrayList<>(); for (final GUIObject it : o) { if (it.getType() == GUIObjectTypes.ANT) { final GAntObject swp = (GAntObject)it; if (this.notRenderedYet.containsKey(swp)) { final GAntFoodObject toAdd = this.notRenderedYet.remove(swp); toAdd.setLocation(swp.getLocation()); ret.add(toAdd); } } } return ret.stream().toArray(GAntFoodObject[]::new); } private GUIObject[] map(final GUIObject[] orig) { final List<GUIObject> ret = new ArrayList<>(orig.length); for (final GUIObject it : orig) { if (it.getType() == GUIObjectTypes.ANT) { final GAntFoodObject mapped = getMapped((GAntObject)it); if (mapped != null && !this.notRenderedYet.containsValue(mapped)) { mapped.setLocation(it.getLocation()); ret.add(mapped); } else { ret.add(it); } } else { ret.add(it); } } return ret.stream().toArray(GUIObject[]::new); } private GAntFoodObject getMapped(final GAntObject ant) { return this.antFoodObjects.stream().filter(af -> af.getAnt().equals(ant)).findFirst().orElse(null); } public GAntFoodObject join(final GAntObject ant, final GFoodObject food) { GAntFoodObject gafo = getMapped(ant); if (!this.antFoodObjects.contains(gafo)) { gafo = new GAntFoodObject(); gafo.setAnt(ant); gafo.setFood(food); this.antFoodObjects.add(gafo); this.notRenderedYet.put(ant, gafo); } return gafo; } public GUIObject[] separate(final GAntObject ant) { final List<GUIObject> retList = new ArrayList<>(); final GAntFoodObject gafo = getMapped(ant); if (this.antFoodObjects.contains(gafo)) { this.antFoodObjects.stream() .filter(afo -> afo.getAnt().equals(ant)) .forEach(afo -> retList.add(afo.getFood())); this.antFoodObjects.remove(gafo); remove(gafo); set(ant); } return retList.stream().toArray(GUIObject[]::new); } public void separate(final GFoodObject food) { //TODO } public void separate(final GAntObject ant, final GFoodObject food) { //TODO } public void remove(final GUIObject data) { remove(new GUIObject [] {data}); } public void remove(final GUIObject[] objects) { final GUIObjectCrate crate = new GUIObjectCrate(); final GUIObject[] mapped = map(objects); crate.sortOut(mapped); this.CLIENT.postMessage(REMOVE.toString() + "/", Mapper.INSTANCE.pojoToJson(crate)); steps.add(new Step(REMOVE, crate)); } public void showScore(final ScoreData data) { this.CLIENT.postMessage(SCORE.toString(), Mapper.INSTANCE.pojoToJson(data)); } // Operations public void showInitMenu(final InitMenuData data) { this.CLIENT.postMessage(SHOW_INIT_MENU.toString(), Mapper.INSTANCE.pojoToJson(data)); } public void createGame(final CreateGameData data) { this.CLIENT.postMessage(CREATE_GAME.toString(), Mapper.INSTANCE.pojoToJson(data)); } public void showResult(final ResultData data) { this.CLIENT.postMessage(SHOW_RESULT.toString(), Mapper.INSTANCE.pojoToJson(data)); } public void close(final CloseData data) { this.CLIENT.postMessage(CLOSE.toString(), Mapper.INSTANCE.pojoToJson(data)); } // Poll for events private void checkEvents() { final String events = this.CLIENT.getMessage(EVENT_POLL.toString()); if (events != null && events.length() > 0) { final GuiEvent[] swp = Mapper.INSTANCE.jsonToPojo(events, GuiEvent[].class); castEvent(swp); } } // EVENTS public void addGuiEventListener(final GuiEventListener listener) { this.guiEventListeners.add(listener); } public void removeGuiEventListener(final GuiEventListener listener) { this.guiEventListeners.remove(listener); } private void castEvent(final GuiEvent[] event) { for (final GuiEvent it : event) { this.guiEventListeners.stream().forEach(l -> l.actionPerformed(it)); } } }
package org.helioviewer.jhv.camera; import java.awt.Point; import org.helioviewer.base.logging.Log; import org.helioviewer.base.math.GL3DMat4d; import org.helioviewer.base.math.GL3DQuatd; import org.helioviewer.base.math.GL3DVec2d; import org.helioviewer.base.math.GL3DVec3d; import org.helioviewer.base.physics.Constants; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.gui.ImageViewerGui; import com.jogamp.opengl.GL2; public abstract class GL3DCamera { public static final double MAX_DISTANCE = -Constants.SunMeanDistanceToEarth * 1.8; public static final double MIN_DISTANCE = -Constants.SunRadius * 1.2; public static final double INITFOV = (48. / 60.) * Math.PI / 180.; public static final double MIN_FOV = INITFOV * 0.02; public static final double MAX_FOV = INITFOV * 10; private final double clipNear = Constants.SunRadius * 3; private final double clipFar = Constants.SunRadius * 10000.; private double fov = INITFOV; private double aspect = 0.0; private double previousAspect = -1.0; private GL3DMat4d cameraTransformation; protected GL3DQuatd rotation; protected GL3DVec3d translation; protected GL3DQuatd currentDragRotation; protected GL3DQuatd localRotation; private long timeDelay; protected long time; private boolean trackingMode; public GL3DMat4d orthoMatrixInverse = GL3DMat4d.identity(); private double cameraWidth = 1.; private double previousCameraWidth = -1; private double cameraWidthTimesAspect; private double FOVangleToDraw; protected static final double DEFAULT_CAMERA_DISTANCE = Constants.SunMeanDistanceToEarth / Constants.SunRadiusInMeter; private final GL3DTrackballRotationInteraction rotationInteraction; private final GL3DPanInteraction panInteraction; private final GL3DZoomBoxInteraction zoomBoxInteraction; protected GL3DInteraction currentInteraction; public GL3DCamera() { this.cameraTransformation = GL3DMat4d.identity(); this.rotation = new GL3DQuatd(); this.currentDragRotation = new GL3DQuatd(); this.localRotation = new GL3DQuatd(); this.translation = new GL3DVec3d(); this.resetFOV(); this.rotationInteraction = new GL3DTrackballRotationInteraction(this); this.panInteraction = new GL3DPanInteraction(this); this.zoomBoxInteraction = new GL3DZoomBoxInteraction(this); this.currentInteraction = this.rotationInteraction; } public void reset() { this.resetFOV(); this.translation = new GL3DVec3d(0, 0, this.translation.z); this.currentDragRotation.clear(); this.currentInteraction.reset(this); } private void resetFOV() { this.fov = INITFOV; } /** * This method is called when the camera changes and should copy the * required settings of the preceding camera objects. * * @param precedingCamera */ public void activate(GL3DCamera precedingCamera) { if (precedingCamera != null) { this.rotation = precedingCamera.getRotation().copy(); this.translation = precedingCamera.translation.copy(); this.FOVangleToDraw = precedingCamera.getFOVAngleToDraw(); this.updateCameraTransformation(); if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getRotateInteraction())) { this.setCurrentInteraction(this.getRotateInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getPanInteraction())) { this.setCurrentInteraction(this.getPanInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getZoomInteraction())) { this.setCurrentInteraction(this.getZoomInteraction()); } } else { Log.debug("GL3DCamera: No Preceding Camera, resetting Camera"); this.reset(); } } public double getFOVAngleToDraw() { return this.FOVangleToDraw; } protected void setZTranslation(double z) { double truncatedz = Math.min(MIN_DISTANCE, Math.max(MAX_DISTANCE, z)); this.translation.z = truncatedz; } public void setPanning(double x, double y) { this.translation.x = x; this.translation.y = y; } public GL3DVec3d getTranslation() { return this.translation; } public GL3DMat4d getCameraTransformation() { return this.cameraTransformation; } public double getZTranslation() { return this.translation.z; } public GL3DQuatd getLocalRotation() { return this.localRotation; } public GL3DQuatd getRotation() { return this.rotation; } public void resetCurrentDragRotation() { this.currentDragRotation.clear(); } public void setLocalRotation(GL3DQuatd localRotation) { this.localRotation = localRotation; this.rotation.clear(); this.updateCameraTransformation(); } public void setCurrentDragRotation(GL3DQuatd currentDragRotation) { this.currentDragRotation = currentDragRotation; this.rotation.clear(); this.updateCameraTransformation(); } public void rotateCurrentDragRotation(GL3DQuatd currentDragRotation) { this.currentDragRotation.rotate(currentDragRotation); this.rotation.clear(); this.updateCameraTransformation(); } public void applyPerspective(GL2 gl) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); this.aspect = Displayer.getViewportWidth() / (double) Displayer.getViewportHeight(); cameraWidth = -translation.z * Math.tan(fov / 2.); if (cameraWidth == 0.) cameraWidth = 1.; cameraWidthTimesAspect = cameraWidth * aspect; gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); if (cameraWidth == previousCameraWidth && aspect == previousAspect) { return; } ImageViewerGui.getZoomStatusPanel().updateZoomLevel(cameraWidth); previousCameraWidth = cameraWidth; previousAspect = aspect; //orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); orthoMatrixInverse = GL3DMat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); } public void resumePerspective(GL2 gl) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glMatrixMode(GL2.GL_MODELVIEW); } public GL3DVec3d getVectorFromSphereOrPlane(GL3DVec2d normalizedScreenpos, GL3DQuatd cameraDifferenceRotation) { double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x; double up1y = normalizedScreenpos.y * cameraWidth - translation.y; GL3DVec3d hitPoint; GL3DVec3d rotatedHitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= 1) { hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2)); rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint); if (rotatedHitPoint.z > 0.) { return rotatedHitPoint; } } GL3DVec3d altnormal = cameraDifferenceRotation.rotateVector(GL3DVec3d.ZAxis); double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z; hitPoint = new GL3DVec3d(up1x, up1y, zvalue); rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint); return rotatedHitPoint; } public GL3DVec3d getVectorFromSphere(Point viewportCoordinates) { GL3DVec2d normalizedScreenpos = new GL3DVec2d(2. * (viewportCoordinates.getX() / Displayer.getViewportWidth() - 0.5), -2. * (viewportCoordinates.getY() / Displayer.getViewportHeight() - 0.5)); double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x; double up1y = normalizedScreenpos.y * cameraWidth - translation.y; GL3DVec3d hitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= 1.) { hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2)); hitPoint = this.localRotation.rotateInverseVector(this.currentDragRotation.rotateInverseVector(hitPoint)); return hitPoint; } return null; } public GL3DVec3d getVectorFromSphereAlt(Point viewportCoordinates) { GL3DVec2d normalizedScreenpos = new GL3DVec2d(2. * (viewportCoordinates.getX() / Displayer.getViewportWidth() - 0.5), -2. * (viewportCoordinates.getY() / Displayer.getViewportHeight() - 0.5)); double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x; double up1y = normalizedScreenpos.y * cameraWidth - translation.y; GL3DVec3d hitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= 1.) { hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2)); hitPoint = this.currentDragRotation.rotateInverseVector(hitPoint); return hitPoint; } return null; } public GL3DVec3d getVectorFromSphereTrackball(Point viewportCoordinates) { GL3DVec2d normalizedScreenpos = new GL3DVec2d(2. * (viewportCoordinates.getX() / Displayer.getViewportWidth() - 0.5), -2. * (viewportCoordinates.getY() / Displayer.getViewportHeight() - 0.5)); double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x; double up1y = normalizedScreenpos.y * cameraWidth - translation.y; GL3DVec3d hitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= Constants.SunRadius2 / 2.) { hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(Constants.SunRadius2 - radius2)); } else { hitPoint = new GL3DVec3d(up1x, up1y, Constants.SunRadius2 / (2. * Math.sqrt(radius2))); } GL3DMat4d roti = this.getCurrentDragRotation().toMatrix().inverse(); hitPoint = roti.multiply(hitPoint); return hitPoint; } /** * Updates the camera transformation by applying the rotation and * translation information. */ public void updateCameraTransformation() { this.rotation = this.currentDragRotation.copy(); this.rotation.rotate(this.localRotation); cameraTransformation = this.rotation.toMatrix().translate(this.translation); } public GL3DMat4d getRotationMatrix() { return this.getRotation().toMatrix(); } public void applyCamera(GL2 gl) { gl.glMultMatrixd(cameraTransformation.m, 0); } public void drawCamera(GL2 gl) { getCurrentInteraction().drawInteractionFeedback(gl, this); } public double getCameraFOV() { return this.fov; } public double setCameraFOV(double fov) { if (fov < MIN_FOV) { this.fov = MIN_FOV; } else if (fov > MAX_FOV) { this.fov = MAX_FOV; } else { this.fov = fov; } return this.fov; } public final double getClipNear() { return clipNear; } public final double getClipFar() { return clipFar; } public double getAspect() { return aspect; } @Override public String toString() { return getName(); } public void setTimeDelay(long timeDelay) { this.timeDelay = timeDelay; } public long getTimeDelay() { return this.timeDelay; } public GL3DQuatd getCurrentDragRotation() { return this.currentDragRotation; } public void setTrackingMode(boolean trackingMode) { this.trackingMode = trackingMode; } public boolean getTrackingMode() { return this.trackingMode; } public void deactivate() { } public void setDefaultFOV() { this.fov = INITFOV; } public double getCameraWidth() { return cameraWidth; } public void zoom(int wr) { this.setCameraFOV(this.fov + 0.0005 * wr); Displayer.render(); } public void setFOVangleDegrees(double fovAngle) { this.FOVangleToDraw = fovAngle * Math.PI / 180.0; } public GL3DInteraction getPanInteraction() { return this.panInteraction; } public GL3DInteraction getRotateInteraction() { return this.rotationInteraction; } public GL3DInteraction getCurrentInteraction() { return this.currentInteraction; } public void setCurrentInteraction(GL3DInteraction currentInteraction) { this.currentInteraction = currentInteraction; } public GL3DInteraction getZoomInteraction() { return this.zoomBoxInteraction; } public String getName() { return "Solar Rotation Tracking Camera"; } public abstract GL3DCameraOptionPanel getOptionPanel(); }
package org.helioviewer.jhv.camera; import java.awt.Point; import java.util.Date; import org.helioviewer.jhv.base.astronomy.Sun; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.base.math.Mat4d; import org.helioviewer.jhv.base.math.Quatd; import org.helioviewer.jhv.base.math.Vec2d; import org.helioviewer.jhv.base.math.Vec3d; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.gui.ImageViewerGui; import org.helioviewer.jhv.layers.Layers; import org.helioviewer.jhv.viewmodel.metadata.MetaData; import com.jogamp.opengl.GL2; public abstract class GL3DCamera { public static final double INITFOV = (48. / 60.) * Math.PI / 180.; public static final double MIN_FOV = INITFOV * 0.02; public static final double MAX_FOV = INITFOV * 30; private static final double clipNear = Sun.Radius * 3; private static final double clipFar = Sun.Radius * 10000; private double fov = INITFOV; private double previousAspect = -1.0; private Mat4d cameraTransformation; private Quatd rotation; private Vec3d translation; private final Quatd currentDragRotation; protected Quatd localRotation; private boolean trackingMode; private Mat4d orthoMatrixInverse = Mat4d.identity(); private double cameraWidth = 1.; private double previousCameraWidth = -1; private double cameraWidthTimesAspect; private double FOVangleToDraw; private final GL3DTrackballRotationInteraction rotationInteraction; private final GL3DPanInteraction panInteraction; private final GL3DAnnotateInteraction annotateInteraction; private GL3DInteraction currentInteraction; public GL3DCamera() { this.cameraTransformation = Mat4d.identity(); this.rotation = new Quatd(); this.currentDragRotation = new Quatd(); this.localRotation = new Quatd(); this.translation = new Vec3d(); this.fov = INITFOV; this.rotationInteraction = new GL3DTrackballRotationInteraction(this); this.panInteraction = new GL3DPanInteraction(this); this.annotateInteraction = new GL3DAnnotateInteraction(this); this.currentInteraction = this.rotationInteraction; } public void reset() { this.translation = new Vec3d(0, 0, this.translation.z); this.currentDragRotation.clear(); this.currentInteraction.reset(); zoomToFit(); } /** * This method is called when the camera changes and should copy the * required settings of the preceding camera objects. * * @param precedingCamera */ public void activate(GL3DCamera precedingCamera) { if (precedingCamera != null) { this.rotation = precedingCamera.rotation.copy(); this.translation = precedingCamera.translation.copy(); this.FOVangleToDraw = precedingCamera.getFOVAngleToDraw(); this.updateRotation(Layers.getLastUpdatedTimestamp(), null); this.updateCameraWidthAspect(precedingCamera.previousAspect); GL3DInteraction precedingInteraction = precedingCamera.getCurrentInteraction(); if (precedingInteraction.equals(precedingCamera.getRotateInteraction())) { this.setCurrentInteraction(this.getRotateInteraction()); } else if (precedingInteraction.equals(precedingCamera.getPanInteraction())) { this.setCurrentInteraction(this.getPanInteraction()); } else if (precedingInteraction.equals(precedingCamera.getAnnotateInteraction())) { this.setCurrentInteraction(this.getAnnotateInteraction()); } } else { Log.debug("GL3DCamera: No Preceding Camera, resetting Camera"); this.reset(); } } private Quatd saveRotation; private Quatd saveLocalRotation; private Vec3d saveTranslation; private Mat4d saveTransformation; public void push(Date date, MetaData m) { if (!trackingMode) { saveRotation = rotation.copy(); saveLocalRotation = localRotation.copy(); saveTranslation = translation.copy(); saveTransformation = cameraTransformation.copy(); updateRotation(date, m); } } public void pop() { if (!trackingMode) { rotation = saveRotation; localRotation = saveLocalRotation; translation = saveTranslation; cameraTransformation = saveTransformation; } } public double getFOVAngleToDraw() { return this.FOVangleToDraw; } public void setPanning(double x, double y) { translation.x = x; translation.y = y; } protected void setZTranslation(double z) { translation.z = z; updateCameraWidthAspect(previousAspect); } public double getZTranslation() { return this.translation.z; } public Vec3d getTranslation() { return this.translation; } public Quatd getLocalRotation() { return this.localRotation; } public void resetCurrentDragRotation() { this.currentDragRotation.clear(); } public void setLocalRotation(Quatd localRotation) { this.localRotation = localRotation; this.rotation.clear(); this.updateCameraTransformation(); } public void rotateCurrentDragRotation(Quatd currentDragRotation) { this.currentDragRotation.rotate(currentDragRotation); this.rotation.clear(); this.updateCameraTransformation(); } // quantization bits per half width camera private static final int quantFactor = 1 << 12; public void updateCameraWidthAspect(double aspect) { cameraWidth = -translation.z * Math.tan(fov / 2.); if (cameraWidth == 0.) cameraWidth = 1.; cameraWidth = (long) (cameraWidth * quantFactor) / (double) quantFactor; if (cameraWidth == previousCameraWidth && aspect == previousAspect) { return; } previousCameraWidth = cameraWidth; previousAspect = aspect; cameraWidthTimesAspect = cameraWidth * aspect; //orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); orthoMatrixInverse = Mat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); if (this == Displayer.getViewport().getCamera()) { // Displayer.render(); ImageViewerGui.getZoomStatusPanel().updateZoomLevel(cameraWidth); } } public Mat4d getOrthoMatrixInverse() { return orthoMatrixInverse.copy(); } public void applyPerspective(GL2 gl) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); // applyCamera gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadMatrixd(cameraTransformation.m, 0); } public Vec3d getVectorFromSphereOrPlane(Vec2d normalizedScreenpos, Quatd cameraDifferenceRotation) { double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x; double up1y = normalizedScreenpos.y * cameraWidth - translation.y; Vec3d hitPoint; Vec3d rotatedHitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= 1) { hitPoint = new Vec3d(up1x, up1y, Math.sqrt(1. - radius2)); rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint); if (rotatedHitPoint.z > 0.) { return rotatedHitPoint; } } Vec3d altnormal = cameraDifferenceRotation.rotateVector(Vec3d.ZAxis); double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z; hitPoint = new Vec3d(up1x, up1y, zvalue); return cameraDifferenceRotation.rotateInverseVector(hitPoint); } private static double computeNormalizedX(Point viewportCoordinates) { return +2. * ((viewportCoordinates.getX() - Displayer.getViewport().getOffsetX()) / Displayer.getViewport().getWidth() - 0.5); } private static double computeNormalizedY(Point viewportCoordinates) { return -2. * ((viewportCoordinates.getY() - Displayer.getViewport().getOffsetY()) / Displayer.getViewport().getHeight() - 0.5); } private double computeUpX(Point viewportCoordinates) { return computeNormalizedX(viewportCoordinates) * cameraWidthTimesAspect - translation.x; } private double computeUpY(Point viewportCoordinates) { return computeNormalizedY(viewportCoordinates) * cameraWidth - translation.y; } public Vec3d getVectorFromSphere(Point viewportCoordinates) { Vec3d hitPoint = getVectorFromSphereAlt(viewportCoordinates); if (hitPoint != null) { return localRotation.rotateInverseVector(hitPoint); } return null; } public Vec3d getVectorFromPlane(Point viewportCoordinates) { double up1x = computeUpX(viewportCoordinates); double up1y = computeUpY(viewportCoordinates); Vec3d altnormal = currentDragRotation.rotateVector(Vec3d.ZAxis); if (altnormal.z == 0) { return null; } double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z; Vec3d hitPoint = new Vec3d(up1x, up1y, zvalue); return currentDragRotation.rotateInverseVector(hitPoint); } public Vec3d getVectorFromSphereAlt(Point viewportCoordinates) { double up1x = computeUpX(viewportCoordinates); double up1y = computeUpY(viewportCoordinates); Vec3d hitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= 1.) { hitPoint = new Vec3d(up1x, up1y, Math.sqrt(1. - radius2)); return currentDragRotation.rotateInverseVector(hitPoint); } return null; } public double getRadiusFromSphereAlt(Point viewportCoordinates) { double up1x = computeUpX(viewportCoordinates); double up1y = computeUpY(viewportCoordinates); return Math.sqrt(up1x * up1x + up1y * up1y); } public Vec3d getVectorFromSphereTrackball(Point viewportCoordinates) { double up1x = computeUpX(viewportCoordinates); double up1y = computeUpY(viewportCoordinates); Vec3d hitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= Sun.Radius2 / 2.) { hitPoint = new Vec3d(up1x, up1y, Math.sqrt(Sun.Radius2 - radius2)); } else { hitPoint = new Vec3d(up1x, up1y, Sun.Radius2 / (2. * Math.sqrt(radius2))); } return currentDragRotation.rotateInverseVector(hitPoint); } public Quatd getCameraDifferenceRotationQuatd(Quatd rot) { Quatd cameraDifferenceRotation = rotation.copy(); cameraDifferenceRotation.rotateWithConjugate(rot); return cameraDifferenceRotation; } /** * Updates the camera transformation by applying the rotation and * translation information. */ public void updateCameraTransformation() { this.rotation = this.currentDragRotation.copy(); this.rotation.rotate(this.localRotation); cameraTransformation = this.rotation.toMatrix().translate(this.translation); } public double getCameraFOV() { return fov; } public void setCameraFOV(double fov) { if (fov < MIN_FOV) { this.fov = MIN_FOV; } else if (fov > MAX_FOV) { this.fov = MAX_FOV; } else { this.fov = fov; } updateCameraWidthAspect(previousAspect); } @Override public String toString() { return getName(); } public void setTrackingMode(boolean trackingMode) { this.trackingMode = trackingMode; } public boolean getTrackingMode() { return trackingMode; } public void deactivate() { } public double getCameraWidth() { return cameraWidth; } public void zoom(int wr) { setCameraFOV(fov + 0.0005 * wr); } public void setFOVangleDegrees(double fovAngle) { this.FOVangleToDraw = fovAngle * Math.PI / 180.0; } public void setCurrentInteraction(GL3DInteraction currentInteraction) { this.currentInteraction = currentInteraction; } public GL3DInteraction getCurrentInteraction() { return this.currentInteraction; } public GL3DInteraction getPanInteraction() { return this.panInteraction; } public GL3DInteraction getRotateInteraction() { return this.rotationInteraction; } public GL3DInteraction getAnnotateInteraction() { return this.annotateInteraction; } public abstract String getName(); public abstract GL3DCameraOptionPanel getOptionPanel(); public abstract void timeChanged(Date date); public abstract void updateRotation(Date date, MetaData m); public void zoomToFit() { double size = Layers.getLargestPhysicalSize(); if (size == 0) setCameraFOV(INITFOV); else setCameraFOV(2. * Math.atan(-size / 2. / this.getZTranslation())); } public Mat4d getRotation() { return this.rotation.toMatrix(); } }
package org.helioviewer.jhv.layers; import java.awt.Component; import java.awt.geom.Rectangle2D; import java.nio.FloatBuffer; import java.nio.IntBuffer; import org.helioviewer.jhv.JHVGlobals; import org.helioviewer.jhv.base.math.IcoSphere; import org.helioviewer.jhv.base.math.Mat4; import org.helioviewer.jhv.base.math.Quat; import org.helioviewer.jhv.base.math.Vec3; import org.helioviewer.jhv.base.scale.GridScale; import org.helioviewer.jhv.base.time.JHVDate; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.camera.CameraHelper; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.gui.ImageViewerGui; import org.helioviewer.jhv.io.APIRequest; import org.helioviewer.jhv.io.LoadRemoteTask; import org.helioviewer.jhv.opengl.GLImage; import org.helioviewer.jhv.opengl.GLImage.DifferenceMode; import org.helioviewer.jhv.opengl.GLSLShader; import org.helioviewer.jhv.opengl.GLSLSolarShader; import org.helioviewer.jhv.opengl.GLText; import org.helioviewer.jhv.renderable.gui.AbstractRenderable; import org.helioviewer.jhv.viewmodel.imagedata.ImageData; import org.helioviewer.jhv.viewmodel.imagedata.ImageDataHandler; import org.helioviewer.jhv.viewmodel.metadata.MetaData; import org.helioviewer.jhv.viewmodel.view.View; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.GL2; import com.jogamp.opengl.util.awt.TextRenderer; public class ImageLayer extends AbstractRenderable implements ImageDataHandler { private int positionBufferID; private int indexBufferID; private int indexBufferSize; private final GLImage glImage = new GLImage(); private final ImageLayerOptions optionsPanel; private LoadRemoteTask worker; private View view; private static final String loading = "Loading..."; public static ImageLayer createImageLayer() { ImageLayer imageLayer = new ImageLayer(); ImageViewerGui.getRenderableContainer().addBeforeRenderable(imageLayer); return imageLayer; } public void load(APIRequest req) { if (!req.equals(getAPIRequest())) { if (worker != null) worker.cancel(true); worker = new LoadRemoteTask(this, req, 0); JHVGlobals.getExecutorService().execute(worker); } } public void unload() { if (view == null) // not changing view ImageViewerGui.getRenderableContainer().removeRenderable(this); else { worker = null; Displayer.display(); } } private ImageLayer() { optionsPanel = new ImageLayerOptions(this); } @Override public void init(GL2 gl) { glImage.init(gl); FloatBuffer positionBuffer = IcoSphere.IcoSphere.a; IntBuffer indexBuffer = IcoSphere.IcoSphere.b; positionBufferID = generate(gl); gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID); gl.glBufferData(GL2.GL_ARRAY_BUFFER, positionBuffer.capacity() * Buffers.SIZEOF_FLOAT, positionBuffer, GL2.GL_STATIC_DRAW); gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, 0); indexBufferID = generate(gl); indexBufferSize = indexBuffer.capacity(); gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBufferID); gl.glBufferData(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBufferSize * Buffers.SIZEOF_INT, indexBuffer, GL2.GL_STATIC_DRAW); gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, 0); } @Override public void setVisible(boolean visible) { super.setVisible(visible); if (Displayer.multiview) { Layers.arrangeMultiView(true); } } private float opacity = -1; public void setView(View _view) { if (view != null) unsetView(); view = _view; worker = null; // drop reference setVisible(true); // enable optionsPanel ImageViewerGui.getRenderableContainerPanel().setOptionsPanel(this); view.setImageLayer(this); view.setDataHandler(this); Layers.addLayer(view); ImageViewerGui.getRenderableContainer().refreshTable(); if (Displayer.multiview) { Layers.arrangeMultiView(true); } else if (opacity == -1) { // first time if (Layers.isCor(view.getName())) opacity = 1; else { int count = 0; for (int i = 0; i < Layers.getNumLayers(); i++) { if (!Layers.isCor(Layers.getLayer(i).getName())) count++; } opacity = (float) (1. / (count == 0 ? 1 : count /* satisfy coverity */)); } optionsPanel.setOpacity(opacity); } optionsPanel.setLUT(view.getDefaultLUT()); } private void unsetView() { if (view != null) { Layers.removeLayer(view); view.setDataHandler(null); view.setImageLayer(null); view.abolish(); view = null; ImageViewerGui.getRenderableContainer().refreshTable(); } imageData = prevImageData = baseImageData = null; } @Override public void remove(GL2 gl) { if (worker != null) { worker.cancel(true); worker = null; } unsetView(); if (Displayer.multiview) { Layers.arrangeMultiView(true); } dispose(gl); } @Override public void prerender(GL2 gl) { if (imageData == null) { return; } glImage.streamImage(gl, imageData, prevImageData, baseImageData); } private static final double[] depth = new double[] { 1., 1., 0., 1. }; private static final double[] depthMini = new double[] { 0., 0., 0., 0. }; private static final double[] depthScale = new double[] { 1., 1., 1., 1. }; @Override public void render(Camera camera, Viewport vp, GL2 gl) { _render(camera, vp, gl, depth); } @Override public void renderMiniview(Camera camera, Viewport vp, GL2 gl) { _render(camera, vp, gl, depthMini); } @Override public void renderScale(Camera camera, Viewport vp, GL2 gl) { _render(camera, vp, gl, depthScale); } private void _render(Camera camera, Viewport vp, GL2 gl, double[] depthrange) { if (imageData == null) { return; } if (!isVisible[vp.idx]) return; GLSLSolarShader shader = Displayer.mode.shader; GridScale scale = Displayer.mode.scale; shader.bind(gl); { glImage.applyFilters(gl, imageData, prevImageData, baseImageData, shader); shader.setViewport(vp.x, vp.yGL, vp.width, vp.height); shader.filter(gl); camera.push(imageData.getViewpoint()); Mat4 vpmi = CameraHelper.getOrthoMatrixInverse(camera, vp); if (Displayer.mode == Displayer.DisplayMode.Orthographic) vpmi.translate(new Vec3(-camera.getCurrentTranslation().x, -camera.getCurrentTranslation().y, 0.)); else vpmi.translate(new Vec3(-camera.getCurrentTranslation().x / vp.aspect, -camera.getCurrentTranslation().y, 0.)); Quat q = camera.getRotation(); shader.bindMatrix(gl, vpmi.getFloatArray()); shader.bindCameraDifferenceRotationQuat(gl, Quat.rotateWithConjugate(q, imageData.getMetaData().getCenterRotation())); DifferenceMode diffMode = glImage.getDifferenceMode(); if (diffMode == DifferenceMode.BaseRotation) { shader.bindDiffCameraDifferenceRotationQuat(gl, Quat.rotateWithConjugate(q, baseImageData.getMetaData().getCenterRotation())); } else if (diffMode == DifferenceMode.RunningRotation) { shader.bindDiffCameraDifferenceRotationQuat(gl, Quat.rotateWithConjugate(q, prevImageData.getMetaData().getCenterRotation())); } shader.bindAngles(gl, imageData.getMetaData().getViewpointL()); shader.setPolarRadii(gl, scale.getYstart(), scale.getYstop()); camera.pop(); enablePositionVBO(gl); enableIndexVBO(gl); { gl.glVertexPointer(3, GL2.GL_FLOAT, 3 * Buffers.SIZEOF_FLOAT, 0); if (shader == GLSLSolarShader.ortho) { shader.bindIsDisc(gl, 1); gl.glDepthRange(depthrange[2], depthrange[3]); gl.glDrawElements(GL2.GL_TRIANGLES, indexBufferSize - 6, GL2.GL_UNSIGNED_INT, 0); shader.bindIsDisc(gl, 0); } gl.glDepthRange(depthrange[0], depthrange[1]); gl.glDrawElements(GL2.GL_TRIANGLES, 6, GL2.GL_UNSIGNED_INT, (indexBufferSize - 6) * Buffers.SIZEOF_INT); gl.glDepthRange(0, 1); } disableIndexVBO(gl); disablePositionVBO(gl); } GLSLShader.unbind(gl); } @Override public void renderFullFloat(Camera camera, Viewport vp, GL2 gl) { if (imageData == null || worker != null) { // loading something int delta = (int) (vp.height * 0.01); TextRenderer renderer = GLText.getRenderer(GLText.TEXT_SIZE_LARGE); Rectangle2D rect = renderer.getBounds(loading); renderer.beginRendering(vp.width, vp.height, true); renderer.draw(loading, (int) (vp.width - rect.getWidth() - delta), (int) (vp.height - rect.getHeight() - delta)); renderer.endRendering(); } } private static int generate(GL2 gl) { int[] tmpId = new int[1]; gl.glGenBuffers(1, tmpId, 0); return tmpId[0]; } private void enableIndexVBO(GL2 gl) { gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBufferID); } private static void disableIndexVBO(GL2 gl) { gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, 0); } private void enablePositionVBO(GL2 gl) { gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID); } private static void disablePositionVBO(GL2 gl) { gl.glDisableClientState(GL2.GL_VERTEX_ARRAY); gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, 0); } private void deletePositionVBO(GL2 gl) { gl.glDeleteBuffers(1, new int[] { positionBufferID }, 0); } private void deleteIndexVBO(GL2 gl) { gl.glDeleteBuffers(1, new int[] { indexBufferID }, 0); } @Override public Component getOptionsPanel() { return optionsPanel; } @Override public String getName() { return view == null || worker != null ? loading : view.getName(); } @Override public String getTimeString() { if (imageData == null) { return "N/A"; } return imageData.getMetaData().getViewpoint().time.toString(); } @Override public boolean isDeletable() { return true; } @Override public void dispose(GL2 gl) { disablePositionVBO(gl); disableIndexVBO(gl); deletePositionVBO(gl); deleteIndexVBO(gl); glImage.dispose(gl); } public boolean isActiveImageLayer() { return Layers.getActiveView() == view; } public void setActiveImageLayer() { if (view != null) Layers.setActiveView(view); } private ImageData imageData; private ImageData prevImageData; private ImageData baseImageData; private void setImageData(ImageData newImageData) { int frame = newImageData.getMetaData().getFrameNumber(); if (frame == 0) { baseImageData = newImageData; } if (imageData == null || (prevImageData != null && prevImageData.getMetaData().getFrameNumber() - frame > 2)) { prevImageData = newImageData; } else if (frame != imageData.getMetaData().getFrameNumber()) { prevImageData = imageData; } imageData = newImageData; } public ImageData getImageData() { return imageData; } public MetaData getMetaData() { return imageData == null ? view.getMetaData(new JHVDate(0)) : imageData.getMetaData(); } @Override public void handleData(ImageData newImageData) { setImageData(newImageData); ImageViewerGui.getRenderableContainer().fireTimeUpdated(this); Displayer.display(); } @Override public boolean isDownloading() { return view != null && view.isDownloading(); } void setOpacity(float opacity) { optionsPanel.setOpacity(opacity); } GLImage getGLImage() { return glImage; } View getView() { return view; } public APIRequest getAPIRequest() { return view == null ? null : view.getAPIRequest(); } double getAutoBrightness() { return imageData.getAutoBrightness(); } }
package org.simplity.tp; import org.simplity.kernel.Tracer; import org.simplity.kernel.data.DataSheet; import org.simplity.kernel.value.Value; import org.simplity.kernel.value.ValueType; import org.simplity.service.ServiceContext; /** * add a row to a data sheet using fields from the context. * * @author org.simplity * */ public class AddRow extends Action { /** * sheet to which row is to be added */ String sheetName; @Override protected Value doAct(ServiceContext ctx) { DataSheet sheet = ctx.getDataSheet(this.sheetName); if (sheet == null) { return Value.VALUE_FALSE; } String[] names = sheet.getColumnNames(); Value[] row = new Value[names.length]; ValueType[] types = sheet.getValueTypes(); int i = 0; for (String name : names) { Value value = ctx.getValue(name); ValueType vt = types[i]; if (value == null) { value = Value.newUnknownValue(vt); } else if (value.getValueType() != vt) { /* * should we reject this value? Let us be tolerant to possible * compatible types */ Tracer.trace("Found a value of type " + value.getValueType() + " for column " + name + " while we were expecting " + vt + ". We will try to convert."); value = Value.parseValue(value.toString(), vt); } row[i] = value; i++; } sheet.addRow(row); return Value.VALUE_TRUE; } }
package org.dvb.event; import java.awt.BDJHelper; import java.util.Iterator; import java.util.LinkedList; import javax.tv.xlet.XletContext; import org.davic.resources.ResourceClient; import org.davic.resources.ResourceServer; import org.davic.resources.ResourceStatusEvent; import org.davic.resources.ResourceStatusListener; import org.havi.ui.HScene; import org.videolan.BDJAction; import org.videolan.BDJXletContext; import org.videolan.GUIManager; import org.videolan.Logger; public class EventManager implements ResourceServer { public static EventManager getInstance() { synchronized (EventManager.class) { if (instance == null) instance = new EventManager(); } return instance; } public boolean addUserEventListener(UserEventListener listener, ResourceClient client, UserEventRepository userEvents) throws IllegalArgumentException { if (client == null) throw new IllegalArgumentException(); BDJXletContext context = BDJXletContext.getCurrentContext(); synchronized (this) { if (!cleanupReservedEvents(userEvents)) return false; exclusiveUserEventListener.add(new UserEventItem(context, listener, client, userEvents)); sendResourceStatusEvent(new UserEventUnavailableEvent(userEvents)); return true; } } public void addUserEventListener(UserEventListener listener, UserEventRepository userEvents) { if (listener == null || userEvents == null) throw new NullPointerException(); BDJXletContext context = BDJXletContext.getCurrentContext(); synchronized (this) { sharedUserEventListener.add(new UserEventItem(context, listener, null, userEvents)); } } public void removeUserEventListener(UserEventListener listener) { BDJXletContext context = BDJXletContext.getCurrentContext(); synchronized (this) { for (Iterator it = sharedUserEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if ((item.context == context) && (item.listener == listener)) it.remove(); } for (Iterator it = exclusiveUserEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if ((item.context == context) && (item.listener == listener)) { sendResourceStatusEvent(new UserEventAvailableEvent(item.userEvents)); it.remove(); } } } } public boolean addExclusiveAccessToAWTEvent(ResourceClient client, UserEventRepository userEvents) throws IllegalArgumentException { if (client == null) throw new IllegalArgumentException(); BDJXletContext context = BDJXletContext.getCurrentContext(); synchronized (this) { if (!cleanupReservedEvents(userEvents)) return false; exclusiveAWTEventListener.add(new UserEventItem(context, null, client, userEvents)); sendResourceStatusEvent(new UserEventUnavailableEvent(userEvents)); return true; } } public void removeExclusiveAccessToAWTEvent(ResourceClient client) { BDJXletContext context = BDJXletContext.getCurrentContext(); synchronized (this) { for (Iterator it = exclusiveAWTEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if ((item.context == context) && (item.client == client)) { sendResourceStatusEvent(new UserEventAvailableEvent(item.userEvents)); it.remove(); } } } } public void addResourceStatusEventListener(ResourceStatusListener listener) { synchronized (this) { resourceStatusEventListeners.add(listener); } } public void removeResourceStatusEventListener(ResourceStatusListener listener) { synchronized (this) { resourceStatusEventListeners.remove(listener); } } private void sendResourceStatusEvent(ResourceStatusEvent event) { for (Iterator it = resourceStatusEventListeners.iterator(); it.hasNext(); ) ((ResourceStatusListener)it.next()).statusChanged(event); } public void receiveKeyEvent(int type, int modifiers, int keyCode) { receiveKeyEventN(type, modifiers, keyCode); } public boolean receiveKeyEventN(int type, int modifiers, int keyCode) { UserEvent ue = new UserEvent(this, 1, type, keyCode, modifiers, System.currentTimeMillis()); HScene focusHScene = GUIManager.getInstance().getFocusHScene(); boolean result = false; if (focusHScene != null) { BDJXletContext context = focusHScene.getXletContext(); for (Iterator it = exclusiveAWTEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if (item.context == null || item.context.isReleased()) { logger.error("Removing exclusive AWT event listener for " + item.context); it.remove(); continue; } if (item.context == context) { if (item.userEvents.contains(ue)) { result = BDJHelper.postKeyEvent(type, modifiers, keyCode); return true; } } } } for (Iterator it = exclusiveUserEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if (item.context == null || item.context.isReleased()) { logger.error("Removing exclusive UserEvent listener for " + item.context); it.remove(); continue; } if (item.userEvents.contains(ue)) { item.context.putCallback(new UserEventAction(item, ue)); return true; } } result = BDJHelper.postKeyEvent(type, modifiers, keyCode); for (Iterator it = sharedUserEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if (item.context == null || item.context.isReleased()) { logger.error("Removing UserEvent listener for " + item.context); it.remove(); continue; } if (item.userEvents.contains(ue)) { item.context.putCallback(new UserEventAction(item, ue)); result = true; } } return result; } private boolean cleanupReservedEvents(UserEventRepository userEvents) { BDJXletContext context = BDJXletContext.getCurrentContext(); for (Iterator it = exclusiveUserEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if (item.context == context) continue; if (hasOverlap(userEvents, item.userEvents)) { try { if (!item.client.requestRelease(item.userEvents, null)) return false; } catch (Exception e) { logger.error("requestRelease() failed: " + e.getClass()); logger.info("" + e.getStackTrace()); return false; } sendResourceStatusEvent(new UserEventAvailableEvent(item.userEvents)); it.remove(); } } for (Iterator it = exclusiveAWTEventListener.iterator(); it.hasNext(); ) { UserEventItem item = (UserEventItem)it.next(); if (item.context == context) continue; if (hasOverlap(userEvents, item.userEvents)) { try { if (!item.client.requestRelease(item.userEvents, null)) return false; } catch (Exception e) { logger.error("requestRelease() failed: " + e.getClass()); logger.info("" + e.getStackTrace()); return false; } sendResourceStatusEvent(new UserEventAvailableEvent(item.userEvents)); it.remove(); } } return true; } private boolean hasOverlap(UserEventRepository userEvents1, UserEventRepository userEvents2) { UserEvent[] evts1 = userEvents1.getUserEvent(); UserEvent[] evts2 = userEvents2.getUserEvent(); for (int i = 0; i < evts1.length; i++) { UserEvent evt1 = evts1[i]; for (int j = 0; j < evts2.length; j++) { UserEvent evt2 = evts2[j]; if ((evt1.getFamily() == evt2.getFamily()) && (evt1.getCode() != evt2.getCode())) return true; } } return false; } private class UserEventItem { public UserEventItem(BDJXletContext context, UserEventListener listener, ResourceClient client, UserEventRepository userEvents) { this.context = context; this.listener = listener; this.client = client; this.userEvents = userEvents.getNewInstance(); if (context == null) { logger.error("Missing xlet context: " + Logger.dumpStack()); } } public BDJXletContext context; public UserEventListener listener; public ResourceClient client; public UserEventRepository userEvents; } private class UserEventAction extends BDJAction { public UserEventAction(UserEventItem item, UserEvent event) { this.listener = item.listener; this.event = event; } protected void doAction() { listener.userEventReceived(event); } private UserEventListener listener; private UserEvent event; } private LinkedList exclusiveUserEventListener = new LinkedList(); private LinkedList sharedUserEventListener = new LinkedList(); private LinkedList exclusiveAWTEventListener = new LinkedList(); private LinkedList resourceStatusEventListeners = new LinkedList(); private static EventManager instance = null; private static final Logger logger = Logger.getLogger(EventManager.class.getName()); }
package i5.las2peer.tools; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import i5.las2peer.api.execution.ServiceInvocationException; import i5.las2peer.api.execution.ServiceNotFoundException; import i5.las2peer.api.p2p.ServiceNameVersion; import i5.las2peer.api.persistency.EnvelopeException; import i5.las2peer.api.persistency.EnvelopeNotFoundException; import i5.las2peer.api.security.AgentAccessDeniedException; import i5.las2peer.api.security.AgentException; import i5.las2peer.api.security.AgentLockedException; import i5.las2peer.api.security.AgentNotFoundException; import i5.las2peer.api.security.AgentOperationFailedException; import i5.las2peer.api.security.ServiceAgent; import i5.las2peer.classLoaders.ClassManager; import i5.las2peer.classLoaders.libraries.FileSystemRepository; import i5.las2peer.classLoaders.policies.ClassLoaderPolicy; import i5.las2peer.classLoaders.policies.DefaultPolicy; import i5.las2peer.classLoaders.policies.RestrictivePolicy; import i5.las2peer.communication.ListMethodsContent; import i5.las2peer.communication.Message; import i5.las2peer.connectors.Connector; import i5.las2peer.connectors.ConnectorException; import i5.las2peer.logging.L2pLogger; import i5.las2peer.p2p.AgentAlreadyRegisteredException; import i5.las2peer.p2p.AgentNotRegisteredException; import i5.las2peer.p2p.NodeException; import i5.las2peer.p2p.NodeInformation; import i5.las2peer.p2p.PastryNodeImpl; import i5.las2peer.p2p.TimeoutException; import i5.las2peer.persistency.EncodingFailedException; import i5.las2peer.persistency.SharedStorage; import i5.las2peer.persistency.SharedStorage.STORAGE_MODE; import i5.las2peer.sandbox.L2pSecurityManager; import i5.las2peer.security.AgentImpl; import i5.las2peer.security.GroupAgentImpl; import i5.las2peer.security.InternalSecurityException; import i5.las2peer.security.PassphraseAgentImpl; import i5.las2peer.security.ServiceAgentImpl; import i5.las2peer.security.UserAgentImpl; import i5.las2peer.serialization.MalformedXMLException; import i5.las2peer.serialization.SerializationException; import i5.las2peer.tools.helper.L2pNodeLauncherConfiguration; import rice.pastry.socket.SocketNodeHandle; /** * las2peer node launcher * * It is the main tool for service developers / node maintainers to start their services, upload agents to the network * and to test their service methods directly in the p2p network. The launcher both supports the start of a new network * as well as starting a node that connects to an already existing network via a bootstrap. * * All methods to be executed can be stated via additional command line parameters to the {@link #main} method. */ public class L2pNodeLauncher { // this is the main class and therefore the logger needs to be static private static final L2pLogger logger = L2pLogger.getInstance(L2pNodeLauncher.class.getName()); private static final String DEFAULT_SERVICE_DIRECTORY = "./service/"; private static final String DEFAULT_STARTUP_DIRECTORY = "etc/startup/"; private static final String DEFAULT_SERVICE_AGENT_DIRECTORY = "etc/startup/"; private CommandPrompt commandPrompt; private static List<Connector> connectors = new ArrayList<>(); private boolean bFinished = false; public boolean isFinished() { return bFinished; } private PastryNodeImpl node; public PastryNodeImpl getNode() { return node; } private UserAgentImpl currentUser; /** * Get the envelope with the given id * * @param id * @return the XML-representation of an envelope as a String * @throws EnvelopeException * @throws EnvelopeNotFoundException * @throws NumberFormatException * @throws SerializationException */ public String getEnvelope(String id) throws NumberFormatException, EnvelopeNotFoundException, EnvelopeException, SerializationException { return node.fetchEnvelope(id).toXmlString(); } /** * Searches for the given agent in the las2peer network. * * @param agentId * @return node handles * @throws AgentNotRegisteredException */ public Object[] findAgent(String agentId) throws AgentNotRegisteredException { return node.findRegisteredAgent(agentId); } /** * Looks for the given service in the las2peer network. * * Needs an active user * * @see #registerUserAgent * * @param serviceNameVersion Exact name and version, same syantax as in {@link #startService(String)} * @return node handles * @throws AgentException */ public Object[] findService(String serviceNameVersion) throws AgentException { if (currentUser == null) { throw new IllegalStateException("Please register a valid user with registerUserAgent before invoking!"); } AgentImpl agent = node.getServiceAgent(ServiceNameVersion.fromString(serviceNameVersion), currentUser); return node.findRegisteredAgent(agent); } /** * Closes the current node. */ public void shutdown() { node.shutDown(); this.bFinished = true; } /** * load passphrases from a simple text file where each line consists of the filename of the agent's xml file and a * passphrase separated by a ; * * @param filename * @return hashtable containing agent file &gt;&gt; passphrase */ private Hashtable<String, String> loadPassphrases(String filename) { Hashtable<String, String> result = new Hashtable<>(); File file = new File(filename); if (file.isFile()) { String[] content; try { content = FileContentReader.read(file).split("\n"); for (String line : content) { line = line.trim(); if (line.isEmpty()) { continue; } String[] split = line.split(";", 2); if (split.length != 2) { printWarning("Ignoring invalid passphrase line (" + line + ") in '" + filename + "'"); continue; } result.put(split[0], split[1]); } } catch (IOException e) { printErrorWithStacktrace("Error reading contents of " + filename, e); logger.printStackTrace(e); bFinished = true; } } return result; } /** * Uploads the contents of the given directory to the global storage of the las2peer network. * * Each contained .xml-file is used as an artifact or - in case the name of the file starts with <i>agent-</i> - as * an agent to upload. * * If agents are to be uploaded, make sure, that the startup directory contains a <i>passphrases.txt</i> file giving * the passphrases for the agents. * * @param directory */ public void uploadStartupDirectory(String directory) { File dir = new File(directory); if (!dir.isDirectory()) { throw new IllegalArgumentException(directory + " is not a directory!"); } Hashtable<String, String> htPassphrases = loadPassphrases(directory + "/passphrases.txt"); Map<String, String> agentIdToXml = new HashMap<>(); List<GroupAgentImpl> groupAgents = new LinkedList<>(); for (File xmlFile : dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".xml"); } })) { try { // maybe an agent? AgentImpl agent = AgentImpl.createFromXml(xmlFile); agentIdToXml.put(agent.getIdentifier(), xmlFile.getName()); if (agent instanceof PassphraseAgentImpl) { String passphrase = htPassphrases.get(xmlFile.getName()); if (passphrase != null) { ((PassphraseAgentImpl) agent).unlock(passphrase); } else { printWarning("\t- got no passphrase for agent from " + xmlFile.getName()); } node.storeAgent(agent); printMessage("\t- stored agent from " + xmlFile); } else if (agent instanceof GroupAgentImpl) { GroupAgentImpl ga = (GroupAgentImpl) agent; groupAgents.add(ga); } else { throw new IllegalArgumentException("Unknown agent type: " + agent.getClass()); } } catch (MalformedXMLException e) { printErrorWithStacktrace("unable to deserialize contents of " + xmlFile.toString() + "!", e); } catch (AgentLockedException e) { printErrorWithStacktrace("error storing agent from " + xmlFile.toString(), e); } catch (AgentAlreadyRegisteredException e) { printErrorWithStacktrace("agent from " + xmlFile.toString() + " already known at this node!", e); } catch (AgentException e) { printErrorWithStacktrace("unable to generate agent " + xmlFile.toString() + "!", e); } } // wait till all user agents are added from startup directory to unlock group agents for (GroupAgentImpl currentGroupAgent : groupAgents) { for (String memberId : currentGroupAgent.getMemberList()) { AgentImpl memberAgent = null; try { memberAgent = node.getAgent(memberId); } catch (AgentException e) { printErrorWithStacktrace("Can't get agent for group member " + memberId, e); continue; } if ((memberAgent instanceof PassphraseAgentImpl) == false) { printError("Unknown agent type to unlock, type: " + memberAgent.getClass().getName()); continue; } PassphraseAgentImpl memberPassAgent = (PassphraseAgentImpl) memberAgent; String xmlName = agentIdToXml.get(memberPassAgent.getIdentifier()); if (xmlName == null) { printError("No known xml file for agent " + memberPassAgent.getIdentifier()); continue; } String passphrase = htPassphrases.get(xmlName); if (passphrase == null) { printError("No known password for agent " + memberPassAgent.getIdentifier()); continue; } try { memberPassAgent.unlock(passphrase); currentGroupAgent.unlock(memberPassAgent); node.storeAgent(currentGroupAgent); printMessage("\t- stored group agent from " + xmlName); break; } catch (Exception e) { printErrorWithStacktrace("Can't unlock group agent " + currentGroupAgent.getIdentifier() + " with member " + memberPassAgent.getIdentifier(), e); continue; } } if (currentGroupAgent.isLocked()) { throw new IllegalArgumentException("group agent still locked!"); } } } /** * Upload the contents of the <i>startup</i> sub directory to the global storage of the las2peer network. * * Each contained .xml-file is used as an artifact or - in case the name of the file starts with <i>agent-</i> - as * an agent to upload. * * If agents are to be uploaded, make sure, that the startup directory contains a <i>passphrases.txt</i> file giving * the passphrases for the agents. */ public void uploadStartupDirectory() { uploadStartupDirectory(DEFAULT_STARTUP_DIRECTORY); } /** * Uploads the service jar file and its dependencies into the shared storage to be used for network class loading. * * @param serviceJarFile The service jar file that should be uploaded. * @param developerAgentXMLFile The XML file of the developers agent. * @param developerPassword The password for the developer agent. * @throws ServicePackageException */ public void uploadServicePackage(String serviceJarFile, String developerAgentXMLFile, String developerPassword) throws ServicePackageException { PackageUploader.uploadServicePackage(node, serviceJarFile, developerAgentXMLFile, developerPassword); } /** * Starts the WebConnector */ public void startWebConnector() { // adding the actual class here, would add an undesired dependency from WebConnector to the core startConnector("i5.las2peer.connectors.webConnector.WebConnector"); } /** * Stops the WebConnector */ public void stopWebConnector() { // adding the actual class here, would add an undesired dependency from WebConnector to the core stopConnector("i5.las2peer.connectors.webConnector.WebConnector"); } /** * @deprecated Use {@link #startWebConnector()} instead. */ @Deprecated public void startNodeAdminConnector() { System.err.println("NodeAdminConnector is now merged into WebConnector. Use startWebConnector instead!"); startWebConnector(); } /** * @deprecated Use {@link #stopWebConnector()} instead. */ @Deprecated public void stopNodeAdminConnector() { System.err.println("NodeAdminConnector is now merged into WebConnector. Use stopWebConnetor instead!"); stopWebConnector(); } /** * Starts a connector given by its classname. * * @param connectorClass */ public void startConnector(String connectorClass) { try { printMessage("Starting connector with class name: " + connectorClass + "!"); Connector connector = loadConnector(connectorClass); connector.start(node); connectors.add(connector); } catch (Exception e) { printErrorWithStacktrace(" --> Problems starting the connector", e); } } /** * Stops a connector given by its classname. * * @param connectorClass */ public void stopConnector(String connectorClass) { Iterator<Connector> iterator = connectors.iterator(); while (iterator.hasNext()) { try { Connector connector = iterator.next(); if (connector.getClass().getName().equals(connectorClass)) { connector.stop(); iterator.remove(); return; } } catch (ConnectorException e) { logger.printStackTrace(e); } } printWarning("No connector with the given classname was started!"); } private Connector loadConnector(String classname) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class<?> connectorClass = L2pNodeLauncher.class.getClassLoader().loadClass(classname); Connector connector = (Connector) connectorClass.newInstance(); return connector; } /** * Try to register the user of the given id at the node and for later usage in this launcher, i.e. for service * method calls via {@link #invoke}. * * @param idOrLogin id or login of the agent to load * @param passphrase passphrase to unlock the private key of the agent * @return the registered agent */ public boolean registerUserAgent(String idOrLogin, String passphrase) { try { // we can't actually determine whether it's an ID based on the format, because technically something // matching [a-f][a-z0-9]{127} could be either // so we try both try { currentUser = (UserAgentImpl) node.getAgent(idOrLogin); } catch (AgentNotFoundException e) { currentUser = (UserAgentImpl) node.getAgent(node.getUserManager().getAgentIdByLogin(idOrLogin)); } currentUser.unlock(passphrase); node.registerReceiver(currentUser); return true; } catch (Exception e) { logger.printStackTrace(e); currentUser = null; return false; } } /** * Register the given agent at the las2peer node and for later usage with {@link #invoke}. * * Make sure, that the private key of the agent is unlocked before registering * * @param agent * @throws InternalSecurityException * @throws AgentAlreadyRegisteredException * @throws AgentException * @throws AgentAccessDeniedException */ public void registerUserAgent(UserAgentImpl agent) throws InternalSecurityException, AgentAlreadyRegisteredException, AgentException, AgentAccessDeniedException { registerUserAgent(agent, null); } /** * Register the given agent at the las2peer node and for later usage with {@link #invoke}. * * If the private key of the agent is not unlocked and a pass phrase has been given, an attempt to unlock the key is * started before registering. * * @param agent * @param passphrase * @throws InternalSecurityException * @throws AgentAlreadyRegisteredException * @throws AgentException * @throws AgentAccessDeniedException */ public void registerUserAgent(UserAgentImpl agent, String passphrase) throws InternalSecurityException, AgentException, AgentAccessDeniedException { if (passphrase != null && agent.isLocked()) { agent.unlock(passphrase); } if (agent.isLocked()) { throw new IllegalStateException("You have to unlock the agent first or give a correct passphrase!"); } try { node.registerReceiver(agent); } catch (AgentAlreadyRegisteredException e) { } currentUser = agent; } /** * Unregister the current user from the las2peer node and from this launcher. * * @see #registerUserAgent */ public void unregisterCurrentAgent() { if (currentUser == null) { return; } try { node.unregisterReceiver(currentUser); } catch (AgentNotRegisteredException | NodeException e) { } currentUser = null; } /** * Invokes a service method as the current agent, choosing an approptiate service version. * * The arguments must be passed via ONE String separated by "-". * * @see #registerUserAgent * @param serviceIdentifier * @param serviceMethod * @param parameters pass an empty string if you want to call a method without parameters * @return Returns the invocation result * @throws ServiceInvocationException * @throws AgentLockedException */ public Serializable invoke(String serviceIdentifier, String serviceMethod, String parameters) throws AgentLockedException, ServiceInvocationException { if (parameters.isEmpty()) { return invoke(serviceIdentifier, serviceMethod, new Serializable[0]); } String[] split = parameters.trim().split("-"); return invoke(serviceIdentifier, serviceMethod, (Serializable[]) split); } /** * Invokes a service method as the current agent, choosing an approptiate service version. * * @see #registerUserAgent * @param serviceIdentifier * @param serviceMethod * @param parameters * @return Returns the invocation result * @throws ServiceInvocationException * @throws AgentLockedException */ private Serializable invoke(String serviceIdentifier, String serviceMethod, Serializable... parameters) throws ServiceInvocationException, AgentLockedException { if (currentUser == null) { throw new IllegalStateException("Please register a valid user with registerUserAgent before invoking!"); } return node.invoke(currentUser, serviceIdentifier, serviceMethod, parameters); } /** * Returns a list of available methods for the given service class name. * * @param serviceNameVersion Exact service name and version, same syntax as in {@link #startService(String)} * @return list of methods encapsulated in a ListMethodsContent * @throws InternalSecurityException * @throws AgentException * @throws InterruptedException * @throws SerializationException * @throws EncodingFailedException * @throws TimeoutException */ public ListMethodsContent getServiceMethods(String serviceNameVersion) throws InternalSecurityException, AgentException, InterruptedException, EncodingFailedException, SerializationException, TimeoutException { if (currentUser == null) { throw new IllegalStateException("please log in a valid user with registerUserAgent before!"); } AgentImpl receiver = node.getServiceAgent(ServiceNameVersion.fromString(serviceNameVersion), currentUser); Message request = new Message(currentUser, receiver, new ListMethodsContent()); request.setSendingNodeId(node.getNodeId()); Message response = node.sendMessageAndWaitForAnswer(request); response.open(currentUser, node); return (ListMethodsContent) response.getContent(); } /** * Starts a service with a known agent or generate a new agent for the service (using a random passphrase) * * Will create an xml file for the generated agent and store the passphrase lcoally * * @param serviceNameVersion Specify the service name and version to run: package.serviceClass@Version. Exact match * required. * @throws Exception on error */ public void startService(String serviceNameVersion) throws Exception { String passPhrase = SimpleTools.createRandomString(20); startService(serviceNameVersion, passPhrase); } /** * start a service with a known agent or generate a new agent for the service * * will create an xml file for the generated agent and store the passphrase lcoally * * @param serviceNameVersion the exact name and version of the service to be started * @param defaultPass this pass will be used to generate the agent if no agent exists * @throws Exception on error */ public void startService(String serviceNameVersion, String defaultPass) throws Exception { ServiceNameVersion service = ServiceNameVersion.fromString(serviceNameVersion); if (service.getVersion() == null && service.getVersion().toString().equals("*")) { printError("You must specify an exact version of the service you want to start."); return; } File file = new File(DEFAULT_SERVICE_AGENT_DIRECTORY + serviceNameVersion + ".xml"); if (!file.exists()) { // create agent ServiceAgentImpl a = ServiceAgentImpl.createServiceAgent(service, defaultPass); file.getParentFile().mkdirs(); file.createNewFile(); // save agent Files.write(file.toPath(), a.toXmlString().getBytes()); // save passphrase Path passphrasesPath = Paths.get(DEFAULT_SERVICE_AGENT_DIRECTORY + "passphrases.txt"); String passphraseLine = serviceNameVersion + ".xml;" + defaultPass; try { Files.write(passphrasesPath, ("\n" + passphraseLine).getBytes(), StandardOpenOption.APPEND); } catch (NoSuchFileException e) { Files.write(passphrasesPath, passphraseLine.getBytes(), StandardOpenOption.CREATE); } } // get passphrase from file Hashtable<String, String> htPassphrases = loadPassphrases(DEFAULT_SERVICE_AGENT_DIRECTORY + "passphrases.txt"); if (htPassphrases.containsKey(serviceNameVersion.toString() + ".xml")) { defaultPass = htPassphrases.get(serviceNameVersion.toString() + ".xml"); } // start startServiceXml(file.toPath().toString(), defaultPass); } /** * start a service defined by an XML file of the corresponding agent * * @param file path to the file containing the service * @param passphrase passphrase to unlock the service agent * @return the service agent * @throws Exception on error */ public ServiceAgentImpl startServiceXml(String file, String passphrase) throws Exception { try { ServiceAgentImpl xmlAgent = ServiceAgentImpl.createFromXml(FileContentReader.read(file)); ServiceAgentImpl serviceAgent; try { // check if the agent is already known to the network serviceAgent = (ServiceAgentImpl) node.getAgent(xmlAgent.getIdentifier()); serviceAgent.unlock(passphrase); } catch (AgentNotFoundException e) { xmlAgent.unlock(passphrase); node.storeAgent(xmlAgent); logger.info("ServiceAgent was not known in network. Published it"); serviceAgent = xmlAgent; } startService(serviceAgent); return serviceAgent; } catch (Exception e) { logger.log(Level.SEVERE, "Starting service failed", e); throw e; } } /** * start the service defined by the given (Service-)Agent * * @param serviceAgent * @throws AgentAlreadyRegisteredException * @throws InternalSecurityException * @throws AgentException */ public void startService(AgentImpl serviceAgent) throws AgentAlreadyRegisteredException, InternalSecurityException, AgentException { if (!(serviceAgent instanceof ServiceAgentImpl)) { throw new IllegalArgumentException("given Agent is not a service agent!"); } if (serviceAgent.isLocked()) { throw new IllegalStateException("You have to unlock the agent before starting the corresponding service!"); } node.registerReceiver(serviceAgent); } /** * stop the given service * * needs name and version * * @param serviceNameVersion * @throws AgentNotRegisteredException * @throws NodeException * @throws ServiceNotFoundException */ public void stopService(String serviceNameVersion) throws AgentNotRegisteredException, NodeException, ServiceNotFoundException { node.stopService(ServiceNameVersion.fromString(serviceNameVersion)); } /** * load an agent from an XML file and return it for later usage * * @param filename name of the file to load * @return the loaded agent * @throws AgentException */ public AgentImpl loadAgentFromXml(String filename) throws AgentException { try { String contents = FileContentReader.read(filename); AgentImpl result = AgentImpl.createFromXml(contents); return result; } catch (Exception e) { throw new AgentException("problems loading an agent from the given file", e); } } /** * try to unlock the private key of the given agent with the given pass phrase * * @param agent * @param passphrase * @throws AgentAccessDeniedException * @throws AgentOperationFailedException If the agent's private key can not be deserialized. */ public void unlockAgent(PassphraseAgentImpl agent, String passphrase) throws AgentAccessDeniedException, AgentOperationFailedException { agent.unlock(passphrase); } /** * start interactive console mode based on a {@link i5.las2peer.tools.CommandPrompt} */ public void interactive() { System.out.println("Entering interactive mode\n" + " + "Enter 'help' for further information of the console.\n" + "Use all public methods of the L2pNodeLauncher class for interaction with the P2P network.\n\n"); commandPrompt.startPrompt(); System.out.println("Exiting interactive mode"); } /** * get the information stored about the local Node * * @return a node information * @throws CryptoException */ public NodeInformation getLocalNodeInfo() throws CryptoException { return node.getNodeInformation(); } /** * get information about other nodes (probably neighbors in the ring etc) * * @return string with node information */ public String getNetInfo() { return SimpleTools.join(node.getOtherKnownNodes(), "\n\t"); } /** * Gets a list of local running services on this node * * @return Returns a list of local running services */ public List<ServiceNameVersion> getLocalServices() { List<ServiceNameVersion> result = new LinkedList<>(); if (node == null) { return result; } ServiceAgent[] localServices = node.getRegisteredServices(); for (ServiceAgent localService : localServices) { result.add(localService.getServiceNameVersion()); } return result; } /** * Creates a new node launcher instance. * * @param bindAddress * * @param port local port number to open * @param bootstrap list of bootstrap hosts to connect to or {@code null} for a new network * @param storageMode A {@link STORAGE_MODE} used by the local node instance for persistence. * @param storageDir * @param monitoringObserver determines, if the monitoring-observer will be started at this node * @param cl the class loader to be used with this node * @param nodeIdSeed the seed to generate node IDs from */ private L2pNodeLauncher(InetAddress bindAddress, Integer port, List<String> bootstrap, STORAGE_MODE storageMode, String storageDir, Boolean monitoringObserver, ClassManager cl, Long nodeIdSeed) { if (monitoringObserver == null) { monitoringObserver = false; } node = new PastryNodeImpl(cl, monitoringObserver, bindAddress, port, bootstrap, storageMode, storageDir, nodeIdSeed); commandPrompt = new CommandPrompt(this); } /** * actually start the node * * @throws NodeException */ private void start() throws NodeException { node.launch(); } /** * Prints a message to the console. * * @param message */ private static void printMessage(String message) { logger.info(message); } /** * Prints a (Yellow) warning message to the console. * * @param message */ private static void printWarning(String message) { message = ColoredOutput.colorize(message, ColoredOutput.ForegroundColor.Yellow); logger.warning(message); } /** * Prints a (Red) error message to the console. * * @param message */ private static void printError(String message) { message = ColoredOutput.colorize(message, ColoredOutput.ForegroundColor.Red); logger.severe(message); } /** * Prints a (Red) error message to the console including a stack trace. * * @param message * @param throwable */ private static void printErrorWithStacktrace(String message, Throwable throwable) { message = ColoredOutput.colorize(message, ColoredOutput.ForegroundColor.Red); logger.log(Level.SEVERE, message, throwable); } @Deprecated public static L2pNodeLauncher launchSingle(Iterable<String> args) throws CryptoException, NodeException { return launchConfiguration(L2pNodeLauncherConfiguration.createFromIterableArgs(args)); } @Deprecated public static L2pNodeLauncher launchSingle(int port, String bootstrap, STORAGE_MODE storageMode, boolean observer, String sLogDir, Iterable<String> serviceDirectories, Long nodeIdSeed, Iterable<String> commands) throws CryptoException, NodeException { L2pNodeLauncherConfiguration configuration = new L2pNodeLauncherConfiguration(); configuration.setPort(port); configuration.setBootstrap(bootstrap); configuration.setStorageMode(storageMode); configuration.setUseMonitoringObserver(observer); configuration.setLogDir(sLogDir); serviceDirectories.forEach(configuration.getServiceDirectories()::add); configuration.setNodeIdSeed(nodeIdSeed); commands.forEach(configuration.getCommands()::add); return launchConfiguration(configuration); } public static L2pNodeLauncher launchConfiguration(L2pNodeLauncherConfiguration launcherConfiguration) throws CryptoException, NodeException, IllegalArgumentException { if (launcherConfiguration.isSandbox()) { L2pSecurityManager.enableSandbox(); // ENABLE SANDBOXING!!! } // check configuration String logDir = launcherConfiguration.getLogDir(); if (logDir != null) { try { L2pLogger.setGlobalLogDirectory(logDir); } catch (Exception ex) { throw new IllegalArgumentException("Couldn't use '" + logDir + "' as log directory.", ex); } } InetAddress bindAddress = launcherConfiguration.getBindAddress(); if (launcherConfiguration.isDebugMode()) { // in debug only listen to loopback interface bindAddress = InetAddress.getLoopbackAddress(); } else if (launcherConfiguration.getPort() == null) { // in non debug mode replace null port launcherConfiguration.setPort(PastryNodeImpl.DEFAULT_BOOTSTRAP_PORT); } STORAGE_MODE storageMode = launcherConfiguration.getStorageMode(); if (storageMode == null) { if (System.getenv().containsKey("MEM_STORAGE") || launcherConfiguration.isDebugMode()) { storageMode = STORAGE_MODE.MEMORY; } else { storageMode = STORAGE_MODE.FILESYSTEM; } } Set<String> serviceDirectories = launcherConfiguration.getServiceDirectories(); if (serviceDirectories == null) { HashSet<String> directories = new HashSet<>(); directories.add(DEFAULT_SERVICE_DIRECTORY); serviceDirectories = directories; } // set up class loader policy ClassLoaderPolicy clp = new DefaultPolicy(); if (launcherConfiguration.isSandbox()) { clp = new RestrictivePolicy(); } // instantiate launcher ClassManager cl = new ClassManager(new FileSystemRepository(serviceDirectories, true), L2pNodeLauncher.class.getClassLoader(), clp); L2pNodeLauncher launcher = new L2pNodeLauncher(bindAddress, launcherConfiguration.getPort(), launcherConfiguration.getBootstrap(), storageMode, launcherConfiguration.getStorageDirectory(), launcherConfiguration.useMonitoringObserver(), cl, launcherConfiguration.getNodeIdSeed()); // check special commands if (launcherConfiguration.isPrintHelp()) { launcher.bFinished = true; printHelp(); return launcher; } else if (launcherConfiguration.isPrintVersion()) { launcher.bFinished = true; printVersion(); return launcher; } // handle commands if (launcherConfiguration.isDebugMode()) { System.err.println("WARNING! Launching node in DEBUG mode! THIS NODE IS NON PERSISTENT!"); } try { launcher.start(); // execute other node commands for (String command : launcherConfiguration.getCommands()) { System.out.println("Handling: '" + command + "'"); launcher.commandPrompt.handleLine(command); } if (!launcherConfiguration.isDebugMode()) { // auto-update bootstrap parameter in configuration file ArrayList<String> bootstrapList = new ArrayList<>(); Iterator<Object> itOther = Arrays.asList(launcher.node.getOtherKnownNodes()).iterator(); while (itOther.hasNext()) { SocketNodeHandle handle = (SocketNodeHandle) itOther.next(); InetSocketAddress addr = handle.getInetSocketAddress(); bootstrapList.add(addr.getHostString() + ":" + addr.getPort()); } launcherConfiguration.setBootstrap(bootstrapList); launcherConfiguration.writeToFile(); } if (launcher.isFinished()) { printMessage("All commands have been handled and shutdown has been called -> end!"); } else { printMessage("All commands have been handled, but not finished yet -> keeping node open!"); } return launcher; } catch (NodeException e) { launcher.bFinished = true; logger.printStackTrace(e); throw e; } } /** * Prints a help message for command line usage. * */ public static void printHelp() { System.out.println("las2peer Node Launcher"); System.out.println(" System.out.println("Usage:"); /** * Gets the las2peer version as String. * * @return Returns the las2peer version as "major.minor.build" or "DEBUG" if not set. */ public static String getVersion() { Package p = L2pNodeLauncher.class.getPackage(); String version = p.getImplementationVersion(); if (version != null) { return version; } else { return "DEBUG"; } } /** * Prints the las2peer version. */ public static void printVersion() { System.out.println("las2peer version \"" + getVersion() + "\""); } /** * Main method for command line processing. * * The method will start a node and try to invoke all command line parameters as parameterless methods of this * class. * * @param argv */ public static void main(String[] argv) { try { // self test system encryption try { CryptoTools.encryptSymmetric("las2peer rulez!".getBytes(), CryptoTools.generateSymmetricKey()); } catch (CryptoException e) { throw new CryptoException( "Fatal Error! Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files are not installed!", e); } // Launches the node L2pNodeLauncherConfiguration conf = new L2pNodeLauncherConfiguration(); try { conf.setFromFile(); } catch (IOException e) { System.err.println("Could not load node configuration"); e.printStackTrace(); System.exit(2); } List<String> comFromFile = new ArrayList<>(conf.getCommands()); conf.getCommands().clear(); // avoid command duplication conf.setFromMainArgs(argv); if (conf.getCommands().isEmpty()) { // no commands specified in main args // readd commands from file conf.getCommands().addAll(comFromFile); } L2pNodeLauncher launcher = launchConfiguration(conf); if (launcher.isFinished()) { System.out.println("node has handled all commands and shut down!"); try { Iterator<Connector> iterator = connectors.iterator(); while (iterator.hasNext()) { iterator.next().stop(); } } catch (ConnectorException e) { logger.printStackTrace(e); } } else { System.out.println("node has handled all commands -- keeping node open\n"); System.out.println("press Strg-C to exit\n"); try { while (true) { Thread.sleep(5000); } } catch (InterruptedException e) { try { Iterator<Connector> iterator = connectors.iterator(); while (iterator.hasNext()) { iterator.next().stop(); } } catch (ConnectorException ce) { logger.printStackTrace(ce); } } } } catch (CryptoException e) { e.printStackTrace(); } catch (NodeException e) { // exception already logged System.exit(2); } } }
// Administrator of the National Aeronautics and Space Administration // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file NOSA-1.3-JPF at the top of the distribution // directory tree for the complete NOSA document. // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. package gov.nasa.jpf.jvm; import gov.nasa.jpf.Config; import gov.nasa.jpf.jvm.bytecode.ArrayInstruction; import gov.nasa.jpf.jvm.bytecode.Instruction; import gov.nasa.jpf.jvm.choice.*; /** * the general policy is that we only create Thread CGs here (based on their * status), but we don't change any thread or lock status. This has to happen * in the instruction before calling the factory */ public class DefaultSchedulerFactory implements SchedulerFactory { protected JVM vm; protected SystemState ss; boolean breakAll; boolean breakArrayAccess; public DefaultSchedulerFactory (Config config, JVM vm, SystemState ss) { this.vm = vm; this.ss = ss; breakAll = config.getBoolean("cg.threads.break_all", false); breakArrayAccess = config.getBoolean("cg.threads.break_arrays", false); } /** * post process a list of choices. This is our primary interface towards * subclasses (together with overriding the relevant ainsn APIs */ protected ThreadInfo[] filter ( ThreadInfo[] list) { // we have nothing to do, but subclasses can use it to // shuffle the order (e.g. to avoid the IdleFilter probblem), // or to filter out the top priorities return list; } protected ChoiceGenerator<ThreadInfo> getRunnableCG () { ThreadInfo[] choices = getRunnablesIfChoices(); if (choices != null) { return new ThreadChoiceFromSet( choices, true); } else { return null; } } protected ChoiceGenerator<ThreadInfo> getSyncCG (ElementInfo ei, ThreadInfo ti) { return getRunnableCG(); } /**************************************** our choice acquisition methods ***/ /** * get list of all runnable threads */ protected ThreadInfo[] getRunnables() { ThreadList tl = vm.getThreadList(); return filter(tl.getRunnableThreads()); } /** * return a list of runnable choices, or null if there is only one */ protected ThreadInfo[] getRunnablesIfChoices() { ThreadList tl = vm.getThreadList(); if (tl.getRunnableThreadCount() > 1) { return filter(tl.getRunnableThreads()); } else { return null; } } protected ThreadInfo[] getRunnablesWith (ThreadInfo ti) { ThreadList tl = vm.getThreadList(); return filter( tl.getRunnableThreadsWith(ti)); } protected ThreadInfo[] getRunnablesWithout (ThreadInfo ti) { ThreadList tl = vm.getThreadList(); return filter( tl.getRunnableThreadsWithout(ti)); } /************************************ the public interface towards the insns ***/ public ChoiceGenerator<ThreadInfo> createSyncMethodEnterCG (ElementInfo ei, ThreadInfo ti) { return createMonitorEnterCG(ei, ti); } public ChoiceGenerator<ThreadInfo> createSyncMethodExitCG (ElementInfo ei, ThreadInfo ti) { return null; // nothing, left mover } public ChoiceGenerator<ThreadInfo> createMonitorEnterCG (ElementInfo ei, ThreadInfo ti) { if (ti.isBlocked()) { // we have to return something if (ss.isAtomic()) { ss.setBlockedInAtomicSection(); } return new ThreadChoiceFromSet(getRunnables(), true); } else { if (ss.isAtomic()) { return null; } return getSyncCG(ei, ti); } } public ChoiceGenerator<ThreadInfo> createMonitorExitCG (ElementInfo ei, ThreadInfo ti) { return null; // nothing, left mover } public ChoiceGenerator<ThreadInfo> createWaitCG (ElementInfo ei, ThreadInfo ti, long timeOut) { if (ss.isAtomic()) { ss.setBlockedInAtomicSection(); } return new ThreadChoiceFromSet(getRunnables(), true); } public ChoiceGenerator<ThreadInfo> createNotifyCG (ElementInfo ei, ThreadInfo ti) { if (ss.isAtomic()) { return null; } ThreadInfo[] waiters = ei.getWaitingThreads(); if (waiters.length < 2) { // if there are less than 2 threads waiting, there is no nondeterminism return null; } else { return new ThreadChoiceFromSet(waiters, false); } } public ChoiceGenerator<ThreadInfo> createNotifyAllCG (ElementInfo ei, ThreadInfo ti) { return null; // no nondeterminism here, left mover } public ChoiceGenerator<ThreadInfo> createSharedFieldAccessCG (ElementInfo ei, ThreadInfo ti) { if (ss.isAtomic()) { return null; } return getSyncCG(ei, ti); } public ChoiceGenerator<ThreadInfo> createSharedArrayAccessCG (ElementInfo ei, ThreadInfo ti) { // the array object (ei) is shared, otherwise we won't get here if (breakArrayAccess) { if (ss.isAtomic()) { return null; } /** // <2do> CG sequence based POR should be optional ArrayInstruction ainsn = (ArrayInstruction)ti.getPC(); boolean isRead = ainsn.isRead(); int aref = ei.getIndex(); for (ChoiceGenerator<?> cg = ss.getChoiceGenerator(); cg != null; cg = cg.getPreviousChoiceGenerator()){ if (cg.getThreadInfo() != ti || cg.getChoiceType() != ThreadInfo.class){ break; // different thread or different choice type -> we need a CG } Instruction cgInsn = cg.getInsn(); if (!(cgInsn instanceof ArrayInstruction)){ break; // not an aload/astore -> we need a CG } ArrayInstruction cgAinsn = (ArrayInstruction)cgInsn; // this is only an approximation since the array ref stored in the insn // might have changed. Note this only works if the insn arrayRef is // stored AFTER this gets executed if (cgAinsn.getArrayRef(ti) != aref){ break; } if (cgAinsn.isRead() == isRead){ return null; // same op on same array in same thread -> no new CG required } // if we get here, this is a complement op on the same array in the same thread // -> skip over all prev. CG insns of the same type } **/ ChoiceGenerator<ThreadInfo> cg = getSyncCG(ei, ti); return cg; } else { return null; } } public ChoiceGenerator<ThreadInfo> createThreadStartCG (ThreadInfo newThread) { // NOTE if newThread is sync and blocked, it already will be blocked // before this gets called // we've been going forth & back a number of times with this. The idea was // that it would be more intuitive to see a transition break every time we // start a new thread, but this causes significant state bloat in case of // pure starter threads, i.e. something that simply does // t.start(); // return // because we get a state branch at the "t.start()" and the "return". // It should be safe to go on, since the important thing is to set the new thread // runnable. if (breakAll) { if (ss.isAtomic()) { return null; } return getRunnableCG(); } else { return null; } } public ChoiceGenerator<ThreadInfo> createThreadYieldCG (ThreadInfo yieldThread) { if (breakAll) { if (ss.isAtomic()) { return null; } return getRunnableCG(); } else { return null; } } public ChoiceGenerator<ThreadInfo> createInterruptCG (ThreadInfo interruptedThread) { if (ss.isAtomic()) { return null; } return getRunnableCG(); } public ChoiceGenerator<ThreadInfo> createThreadSleepCG (ThreadInfo sleepThread, long millis, int nanos) { if (breakAll) { if (ss.isAtomic()) { return null; } // we treat this as a simple reschedule return createThreadYieldCG(sleepThread); } else { return null; } } public ChoiceGenerator<ThreadInfo> createThreadTerminateCG (ThreadInfo terminateThread) { // terminateThread is already TERMINATED at this point ThreadList tl = vm.getThreadList(); // NOTE returning null does not directly define an end state - that's up to // a subsequent call to vm.isEndState() // <2do> FIXME this is redundant and error prone if (tl.hasAnyAliveThread()) { return new ThreadChoiceFromSet(getRunnablesWithout(terminateThread), true); } else { return null; } } public ChoiceGenerator<ThreadInfo> createThreadSuspendCG () { return getRunnableCG(); } public ChoiceGenerator<ThreadInfo> createThreadResumeCG () { return getRunnableCG(); } }
package org.bitcoinj.evolution; import org.bitcoinj.core.*; import org.json.JSONObject; import java.io.IOException; import java.io.OutputStream; public class CoinbaseTx extends SpecialTxPayload { public static final int CURRENT_VERSION = 2; long height; Sha256Hash merkleRootMasternodeList; Sha256Hash merkleRootQuorums; public CoinbaseTx(NetworkParameters params, Transaction tx) { super(params, tx); } @Override protected void parse() throws ProtocolException { super.parse(); height = readUint32(); merkleRootMasternodeList = readHash(); if(version >= 2) merkleRootQuorums = readHash(); length = cursor - offset; } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { super.bitcoinSerializeToStream(stream); Utils.uint32ToByteStreamLE(height, stream); stream.write(merkleRootMasternodeList.getReversedBytes()); if(version >= 2) stream.write(merkleRootQuorums.getReversedBytes()); } public int getCurrentVersion() { return CURRENT_VERSION; } public String toString() { return String.format("CoinbaseTx(height=%d, merkleRootMNList=%s, merkleRootQuorums=%s)", height, merkleRootMasternodeList.toString(), merkleRootQuorums); } @Override public Transaction.Type getType() { return Transaction.Type.TRANSACTION_COINBASE; } @Override public String getName() { return "coinbaseTx"; } @Override public JSONObject toJson() { JSONObject result = new JSONObject(); result.append("height", height); result.append("merkleRootMNList", merkleRootMasternodeList); result.append("merkleRootQuorums", merkleRootQuorums); return result; } public long getHeight() { return height; } public Sha256Hash getMerkleRootMasternodeList() { return merkleRootMasternodeList; } public Sha256Hash getMerkleRootQuorums() { return merkleRootQuorums; } }
package BlueTurtle.warnings; import lombok.Getter; import lombok.Setter; /** * This class is used to represent a FindBugs warning. * * @author BlueTurtle. * */ public class FindBugsWarning extends Warning { @Getter @Setter private int lineNumber; @Getter @Setter private String message; @Getter @Setter private String category; @Getter @Setter private String priority; /** * Constructor. * * @param filePath * the path to the file where the warning is located. * @param filename * the name of the file where the warning is located. * @param line * the line number where the warning is located. * @param message * the message of the warning. * @param category * the category of the warning. * @param priority * the priority of the warning. * @param ruleName * the rule name of the warning. * @param classification * of the violated rule of the warning. */ public FindBugsWarning(String filePath, String filename, int line, String message, String category, String priority, String ruleName, String classification) { super(filePath, filename, "FindBugs", ruleName, classification); setLineNumber(line); setMessage(message); setCategory(category); setPriority(priority); } /** * Check whether two FindBugs warnings are the same. * * @param other * the other warning. * @return a boolean */ @Override public boolean equals(Object other) { if (!(other instanceof FindBugsWarning)) { return false; } FindBugsWarning that = (FindBugsWarning) other; return (filePath.equals(that.filePath) && fileName.equals(that.fileName) && lineNumber == that.lineNumber && message.equals(that.message) && category.equals(that.category) && classification.equals(that.classification) && priority.equals(that.priority) && type.equals(that.type) && ruleName.equals(that.ruleName)); } /** * HashCode for the FindBugsWarning. */ @Override public int hashCode() { return java.util.Objects.hash(filePath, fileName, type, lineNumber, message, category, priority, ruleName, classification); } /** * toString method for FindBugsWarning. */ @Override public String toString() { return "FindBugsWarning [lineNumber=" + lineNumber + ", message=" + message + ", category=" + category + ", priority=" + priority + ", classification=" + classification + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath + ", ruleName=" + ruleName + "]"; } }
package StevenDimDoors.mod_pocketDim; import java.util.ArrayList; import java.util.Random; import net.minecraft.enchantment.Enchantment; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.WeightedRandom; import net.minecraft.util.WeightedRandomChestContent; import net.minecraftforge.common.ChestGenHooks; import StevenDimDoors.mod_pocketDim.util.WeightedContainer; /* * Registers a category of loot chests for Dimensional Doors in Forge. */ public class DDLoot { private static final double MIN_ITEM_DAMAGE = 0.3; private static final double MAX_ITEM_DAMAGE = 0.9; private static final int ITEM_ENCHANTMENT_CHANCE = 50; private static final int MAX_ITEM_ENCHANTMENT_CHANCE = 100; public static final String DIMENSIONAL_DUNGEON_CHEST = "dimensionalDungeonChest"; public static ChestGenHooks DungeonChestInfo = null; private static final int CHEST_SIZE = 5; private DDLoot() { } public static void registerInfo(DDProperties properties) { // Register the dimensional dungeon chest with ChestGenHooks. This isn't necessary, but allows // other mods to add their own loot to our chests if they know our loot category, without having // to interface with our code. DungeonChestInfo = ChestGenHooks.getInfo(DIMENSIONAL_DUNGEON_CHEST); DungeonChestInfo.setMin(CHEST_SIZE); DungeonChestInfo.setMax(CHEST_SIZE); ArrayList<WeightedRandomChestContent> items = new ArrayList<WeightedRandomChestContent>(); addContent(true, items, Item.ingotIron.itemID, 160, 1, 3); addContent(true, items, Item.coal.itemID, 120, 1, 3); addContent(true, items, Item.netherQuartz.itemID, 120, 1, 3); addContent(true, items, Item.enchantedBook.itemID, 100); addContent(true, items, Item.ingotGold.itemID, 80, 1, 3); addContent(true, items, Item.diamond.itemID, 40, 1, 2); addContent(true, items, Item.emerald.itemID, 20, 1, 2); addContent(true, items, Item.appleGold.itemID, 10); addContent(properties.FabricOfRealityLootEnabled, items, mod_pocketDim.blockDimWall.blockID, 80, 4, 16); addContent(properties.WorldThreadLootEnabled, items, mod_pocketDim.itemWorldThread.itemID, 80); // Add all the items to our dungeon chest addItemsToContainer(DungeonChestInfo, items); } private static void addContent(boolean include, ArrayList<WeightedRandomChestContent> items, int itemID, int weight) { if (include) items.add(new WeightedRandomChestContent(itemID, 0, 1, 1, weight)); } private static void addContent(boolean include, ArrayList<WeightedRandomChestContent> items, int itemID, int weight, int minAmount, int maxAmount) { if (include) items.add(new WeightedRandomChestContent(itemID, 0, minAmount, maxAmount, weight)); } private static void addItemsToContainer(ChestGenHooks container, ArrayList<WeightedRandomChestContent> items) { for (WeightedRandomChestContent item : items) { container.addItem(item); } } private static void fillChest(ArrayList<ItemStack> stacks, IInventory inventory, Random random) { // This custom chest-filling function avoids overwriting item stacks // The prime number below is used for choosing chest slots in a seemingly-random pattern. Its value // was selected specifically to achieve a spread-out distribution for chests with up to 104 slots. // Choosing a prime number ensures that our increments are relatively-prime to the chest size, which // means we'll cover all the slots before repeating any. This is mathematically guaranteed. final int primeOffset = 239333; int size = inventory.getSizeInventory(); for (ItemStack item : stacks) { int limit = size; int index = random.nextInt(size); while (limit > 0 && inventory.getStackInSlot(index) != null) { limit index = (index + primeOffset) % size; } inventory.setInventorySlotContents(index, item); } } public static void generateChestContents(ChestGenHooks chestInfo, IInventory inventory, Random random) { // This is a custom version of net.minecraft.util.WeightedRandomChestContent.generateChestContents() // It's designed to avoid the following bugs in MC 1.5: // 1. If multiple enchanted books appear, then they will have the same enchantment // 2. The randomized filling algorithm will sometimes overwrite item stacks with other stacks int count = chestInfo.getCount(random); WeightedRandomChestContent[] content = chestInfo.getItems(random); ArrayList<ItemStack> allStacks = new ArrayList<ItemStack>(); for (int k = 0; k < count; k++) { WeightedRandomChestContent selection = (WeightedRandomChestContent)WeightedRandom.getRandomItem(random, content); // Call getChestGenBase() to make sure we generate a different enchantment for books. // Don't just use a condition to check if the item is an instance of ItemEnchantedBook because // we don't know if other mods might add items that also need to be regenerated. selection = selection.theItemId.getItem().getChestGenBase(chestInfo, random, selection); ItemStack[] stacks = ChestGenHooks.generateStacks(random, selection.theItemId, selection.theMinimumChanceToGenerateItem, selection.theMaximumChanceToGenerateItem); for (int h = 0; h < stacks.length; h++) { allStacks.add(stacks[h]); } } fillChest(allStacks, inventory, random); } public static void fillGraveChest(IInventory inventory, Random random, DDProperties properties) { // This function fills "grave chests", which are chests for dungeons that // look like a player died in the area and his remains were gathered in // a chest. Doing this properly requires fine control of loot generation, // so we use our own function rather than Minecraft's functions. int k; int count; ArrayList<ItemStack> stacks = new ArrayList<ItemStack>(); ArrayList<WeightedContainer<Item>> selection = new ArrayList<WeightedContainer<Item>>(); // Insert bones and rotten flesh // Make stacks of single items to spread them out count = MathHelper.getRandomIntegerInRange(random, 2, 5); for (k = 0; k < count; k++) { stacks.add( new ItemStack(Item.bone, 1) ); } count = MathHelper.getRandomIntegerInRange(random, 2, 4); for (k = 0; k < count; k++) { stacks.add( new ItemStack(Item.rottenFlesh, 1) ); } // Insert tools // 30% chance of adding a pickaxe if (random.nextInt(100) < 30) { addModifiedTool(Item.pickaxeIron, stacks, random); } // 30% chance of adding a bow and some arrows if (random.nextInt(100) < 30) { addModifiedBow(stacks, random); stacks.add( new ItemStack(Item.arrow, MathHelper.getRandomIntegerInRange(random, 8, 32)) ); } // 10% chance of adding a Rift Blade (no enchants) if (properties.RiftBladeLootEnabled && random.nextInt(100) < 10) { stacks.add( new ItemStack(mod_pocketDim.itemRiftBlade, 1) ); } else { // 20% of adding an iron sword, 10% of adding a stone sword addModifiedSword( getRandomItem(Item.swordIron, Item.swordStone, null, 20, 10, random) , stacks, random); } // Insert equipment // For each piece, 25% of an iron piece, 10% of a chainmail piece addModifiedEquipment( getRandomItem(Item.helmetIron, Item.helmetChain, null, 25, 10, random) , stacks, random); addModifiedEquipment( getRandomItem(Item.plateIron, Item.plateChain, null, 25, 10, random) , stacks, random); addModifiedEquipment( getRandomItem(Item.legsIron, Item.legsChain, null, 25, 10, random) , stacks, random); addModifiedEquipment( getRandomItem(Item.bootsIron, Item.bootsChain, null, 25, 10, random) , stacks, random); // Insert other random stuff // 40% chance for a name tag, 35% chance for a glass bottle // 30% chance for an ender pearl, 5% chance for record 11 addItemWithChance(stacks, random, 40, Item.nameTag, 1); addItemWithChance(stacks, random, 35, Item.glassBottle, 1); addItemWithChance(stacks, random, 30, Item.enderPearl, 1); addItemWithChance(stacks, random, 5, Item.record11, 1); fillChest(stacks, inventory, random); } private static void addModifiedEquipment(Item item, ArrayList<ItemStack> stacks, Random random) { if (item == null) return; stacks.add( getModifiedItem(item, random, new Enchantment[] { Enchantment.blastProtection, Enchantment.fireProtection, Enchantment.protection, Enchantment.projectileProtection }) ); } private static void addModifiedSword(Item item, ArrayList<ItemStack> stacks, Random random) { if (item == null) return; stacks.add( getModifiedItem(item, random, new Enchantment[] { Enchantment.fireAspect, Enchantment.knockback, Enchantment.sharpness }) ); } private static void addModifiedTool(Item tool, ArrayList<ItemStack> stacks, Random random) { if (tool == null) return; stacks.add( getModifiedItem(tool, random, new Enchantment[] { Enchantment.efficiency, Enchantment.unbreaking }) ); } private static void addModifiedBow(ArrayList<ItemStack> stacks, Random random) { stacks.add( getModifiedItem(Item.bow, random, new Enchantment[] { Enchantment.flame, Enchantment.power, Enchantment.punch }) ); } private static ItemStack getModifiedItem(Item item, Random random, Enchantment[] enchantments) { ItemStack result = applyRandomDamage(item, random); if (enchantments.length > 0 && random.nextInt(MAX_ITEM_ENCHANTMENT_CHANCE) < ITEM_ENCHANTMENT_CHANCE) { result.addEnchantment(enchantments[ random.nextInt(enchantments.length) ], 1); } return result; } private static Item getRandomItem(Item a, Item b, Item c, int weightA, int weightB, Random random) { int roll = random.nextInt(100); if (roll < weightA) return a; if (roll < weightA + weightB) return b; return c; } private static void addItemWithChance(ArrayList<ItemStack> stacks, Random random, int chance, Item item, int count) { if (random.nextInt(100) < chance) { stacks.add(new ItemStack(item, count)); } } private static ItemStack applyRandomDamage(Item item, Random random) { int damage = (int) (item.getMaxDamage() * MathHelper.getRandomDoubleInRange(random, MIN_ITEM_DAMAGE, MAX_ITEM_DAMAGE)); return new ItemStack(item, 1, damage); } }
package org.jivesoftware.gui; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.UnrecoverableKeyException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.net.ssl.SSLContext; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JPopupMenu; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.text.JTextComponent; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.jivesoftware.AccountCreationWizard; import org.jivesoftware.MainWindow; import org.jivesoftware.Spark; import org.jivesoftware.resource.Default; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.AbstractXMPPConnection; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ReconnectionManager; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.parsing.ExceptionLoggingCallback; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.sasl.javax.SASLExternalMechanism; import org.jivesoftware.smack.sasl.javax.SASLGSSAPIMechanism; import org.jivesoftware.smack.tcp.XMPPTCPConnection; import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration; import org.jivesoftware.smack.util.DNSUtil; import org.jivesoftware.smack.util.TLSUtils; import org.jivesoftware.smackx.carbons.CarbonManager; import org.jivesoftware.smackx.chatstates.ChatStateManager; import org.jivesoftware.spark.PluginManager; import org.jivesoftware.spark.SessionManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.Workspace; import org.jivesoftware.spark.component.MessageDialog; import org.jivesoftware.spark.component.RolloverButton; import org.jivesoftware.spark.sasl.SASLGSSAPIv3CompatMechanism; import org.jivesoftware.spark.ui.login.GSSAPIConfiguration; import org.jivesoftware.spark.ui.login.LoginSettingDialog; import org.jivesoftware.spark.util.BrowserLauncher; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.ResourceUtils; import static org.jivesoftware.spark.util.StringUtils.modifyWildcards; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.certificates.CertificateModel; import org.jivesoftware.sparkimpl.certificates.SparkSSLContextCreator; import org.jivesoftware.sparkimpl.certificates.SparkSSLSocketFactory; import org.jivesoftware.sparkimpl.certificates.SparkTrustManager; import org.jivesoftware.sparkimpl.certificates.UnrecognizedServerCertificatePanel; import org.jivesoftware.sparkimpl.plugin.layout.LayoutSettings; import org.jivesoftware.sparkimpl.plugin.layout.LayoutSettingsManager; import org.jivesoftware.sparkimpl.plugin.manager.Enterprise; import org.jivesoftware.sparkimpl.settings.JiveInfo; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import org.jxmpp.jid.DomainBareJid; import org.jxmpp.jid.impl.JidCreate; import org.jxmpp.jid.parts.Resourcepart; import org.jxmpp.stringprep.XmppStringprepException; import org.jxmpp.util.XmppStringUtils; import org.minidns.dnsname.DnsName; /** * * @author KeepToo */ public class LoginUIPanel extends javax.swing.JPanel implements KeyListener, ActionListener, FocusListener, CallbackHandler { private JFrame loginDialog; private static final String BUTTON_PANEL = "buttonpanel"; // NOTRANS private static final String PROGRESS_BAR = "progressbar"; // NOTRANS private LocalPreferences localPref; private ArrayList<String> _usernames = new ArrayList<>(); private String loginUsername; private String loginPassword; private String loginServer; private static final long serialVersionUID = 2445523786538863459L; // Panel used to hold buttons private final CardLayout cardLayout = new CardLayout(0, 5); final JPanel cardPanel = new JPanel(cardLayout); final JPanel buttonPanel = new JPanel(new GridBagLayout()); private AbstractXMPPConnection connection = null; private RolloverButton otherUsers = new RolloverButton(SparkRes.getImageIcon(SparkRes.PANE_UP_ARROW_IMAGE)); /** * Creates new form LoginWindow */ public LoginUIPanel() { initComponents(); localPref = SettingsManager.getLocalPreferences(); init(); // Check if upgraded needed. try { checkForOldSettings(); } catch (Exception e) { Log.error(e); } } private void init() { ResourceUtils.resButton(cbSavePassword, Res.getString("checkbox.save.password")); ResourceUtils.resButton(cbAutoLogin, Res.getString("checkbox.auto.login")); ResourceUtils.resButton(btnCreateAccount, Res.getString("label.accounts")); ResourceUtils.resButton(cbLoginInvisible, Res.getString("checkbox.login.as.invisible")); ResourceUtils.resButton(cbAnonymous, Res.getString("checkbox.login.anonymously")); ResourceUtils.resButton(btnReset, Res.getString("label.passwordreset")); configureVisibility(); lblProgress.setVisible(false); cbSavePassword.setOpaque(false); cbAutoLogin.setOpaque(false); cbLoginInvisible.setOpaque(false); cbAnonymous.setOpaque(false); // btnReset.setVisible(false); // Add button but disable the login button initially cbSavePassword.addActionListener(this); cbAutoLogin.addActionListener(this); cbLoginInvisible.addActionListener(this); cbAnonymous.addActionListener(this); // Add KeyListener tfUsername.addKeyListener(this); tfPassword.addKeyListener(this); tfDomain.addKeyListener(this); tfPassword.addFocusListener(this); tfUsername.addFocusListener(this); tfDomain.addFocusListener(this); // Add ActionListener btnLogin.addActionListener(this); btnAdvanced.addActionListener(this); otherUsers.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { getPopup().show(otherUsers, e.getX(), e.getY()); } }); // Make same size GraphicUtils.makeSameSize(tfUsername, tfPassword); // Set progress bar description lblProgress.setText(Res.getString("message.authenticating")); lblProgress.setVerticalTextPosition(JLabel.BOTTOM); lblProgress.setHorizontalTextPosition(JLabel.CENTER); lblProgress.setHorizontalAlignment(JLabel.CENTER); // Set Resources // ResourceUtils.resLabel(usernameLabel, tfUsername, Res.getString("label.username")); //ResourceUtils.resLabel(passwordLabel, passwordField, Res.getString("label.password")); ResourceUtils.resButton(btnLogin, Res.getString("button.login")); ResourceUtils.resButton(btnAdvanced, Res.getString("button.advanced")); // Load previous instances String userProp = localPref.getLastUsername(); String serverProp = localPref.getServer(); File file = new File(Spark.getSparkUserHome(), "/user/"); File[] userprofiles = file.listFiles(); for (File f : userprofiles) { if (f.getName().contains("@")) { _usernames.add(f.getName()); } else { Log.error("Profile contains wrong format: \"" + f.getName() + "\" located at: " + f.getAbsolutePath()); } } if (userProp != null) { tfUsername.setText(XmppStringUtils.unescapeLocalpart(userProp)); } if (serverProp != null) { tfDomain.setText(serverProp); } // Check Settings if (localPref.isSavePassword()) { String encryptedPassword = localPref.getPasswordForUser(getBareJid()); if (encryptedPassword != null) { tfPassword.setText(encryptedPassword); } cbSavePassword.setSelected(true); btnLogin.setEnabled(true); } cbAutoLogin.setSelected(localPref.isAutoLogin()); cbLoginInvisible.setSelected(localPref.isLoginAsInvisible()); cbAnonymous.setSelected(localPref.isLoginAnonymously()); tfUsername.setEnabled(!cbAnonymous.isSelected()); tfPassword.setEnabled(!cbAnonymous.isSelected()); useSSO(localPref.isSSOEnabled()); if (cbAutoLogin.isSelected()) { validateLogin(); return; } // Handle arguments String username = Spark.getArgumentValue("username"); String password = Spark.getArgumentValue("password"); String server = Spark.getArgumentValue("server"); if (username != null) { tfUsername.setText(username); } if (password != null) { tfPassword.setText(password); } if (server != null) { tfDomain.setText(server); } if (username != null && server != null && password != null) { validateLogin(); } btnCreateAccount.addActionListener(this); final String lockedDownURL = Default.getString(Default.HOST_NAME); if (ModelUtil.hasLength(lockedDownURL)) { tfDomain.setText(lockedDownURL); } //reset ui //btnAdvanced.setUI(new BasicButtonUI()); //btnCreateAccount.setUI(new BasicButtonUI()); tfDomain.putClientProperty("JTextField.placeholderText", "Enter Domain(e.g igniterealtime.org)"); tfPassword.putClientProperty("JTextField.placeholderText", "Enter Password"); tfUsername.putClientProperty("JTextField.placeholderText", "Enter Username"); setComponentsAvailable(true); } private void configureVisibility() { int height = filler3.getPreferredSize().height; if (Default.getBoolean(Default.HIDE_SAVE_PASSWORD_AND_AUTO_LOGIN) && !localPref.getPswdAutologin()) { pnlCheckboxes.remove(cbAutoLogin); pnlCheckboxes.remove(cbSavePassword); height = height + 20; } // Add option to hide "Login as invisible" selection on the login screen if (Default.getBoolean(Default.HIDE_LOGIN_AS_INVISIBLE) && !localPref.getInvisibleLogin()) { pnlCheckboxes.remove(cbLoginInvisible); height = height + 10; } // Add option to hide "Login anonymously" selection on the login screen if (Default.getBoolean(Default.HIDE_LOGIN_ANONYMOUSLY) && !localPref.getAnonymousLogin()) { pnlCheckboxes.remove(cbAnonymous); height = height + 10; } if (Default.getBoolean(Default.ACCOUNT_DISABLED) && !localPref.getAccountsReg()) { pnlBtns.remove(btnCreateAccount); height = height + 15; } if (!Default.getBoolean(Default.PASSWORD_RESET_ENABLED)) { pnlBtns.remove(btnReset); } if (Default.getBoolean(Default.ADVANCED_DISABLED) && !localPref.getAdvancedConfig()) { pnlBtns.remove(btnAdvanced); height = height + 15; } filler3.setPreferredSize(new Dimension(220, height)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnlLeft = new javax.swing.JPanel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 50), new java.awt.Dimension(250, 50), new java.awt.Dimension(32767, 50)); lblLogo = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); pnlCenter = new javax.swing.JPanel(); filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(220, 20), new java.awt.Dimension(0, 32767)); pnlInputs = new javax.swing.JPanel(); tfUsername = new javax.swing.JTextField(); tfDomain = new javax.swing.JTextField(); tfPassword = new javax.swing.JPasswordField(); pnlCheckboxes = new javax.swing.JPanel(); cbSavePassword = new javax.swing.JCheckBox(); cbAutoLogin = new javax.swing.JCheckBox(); cbLoginInvisible = new javax.swing.JCheckBox(); cbAnonymous = new javax.swing.JCheckBox(); pnlBtns = new javax.swing.JPanel(); btnLogin = new javax.swing.JButton(); btnCreateAccount = new javax.swing.JButton(); btnAdvanced = new javax.swing.JButton(); btnReset = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); pnlLeft.setPreferredSize(new java.awt.Dimension(260, 0)); pnlLeft.add(filler1); lblLogo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/spark-64x64.png"))); // NOI18N lblLogo.setPreferredSize(new java.awt.Dimension(250, 80)); lblLogo.setRequestFocusEnabled(false); pnlLeft.add(lblLogo); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Spark"); jLabel1.setPreferredSize(new java.awt.Dimension(250, 22)); pnlLeft.add(jLabel1); jLabel2.setText("Instant Messenger"); pnlLeft.add(jLabel2); lblProgress.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblProgress.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ripple.gif"))); // NOI18N lblProgress.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); lblProgress.setPreferredSize(new java.awt.Dimension(250, 90)); lblProgress.setRequestFocusEnabled(false); lblProgress.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); pnlLeft.add(lblProgress); add(pnlLeft, java.awt.BorderLayout.WEST); pnlCenter.setBackground(new java.awt.Color(255, 255, 255)); pnlCenter.setMinimumSize(new java.awt.Dimension(0, 0)); pnlCenter.setPreferredSize(new java.awt.Dimension(250, 0)); java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(); flowLayout1.setAlignOnBaseline(true); pnlCenter.setLayout(flowLayout1); pnlCenter.add(filler3); pnlInputs.setBackground(new java.awt.Color(255, 255, 255)); pnlInputs.setPreferredSize(new java.awt.Dimension(220, 110)); tfUsername.setPreferredSize(new java.awt.Dimension(200, 30)); tfUsername.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { tfUsernameMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { tfUsernameMouseExited(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { tfUsernameMousePressed(evt); } }); pnlInputs.add(tfUsername); tfDomain.setPreferredSize(new java.awt.Dimension(200, 30)); pnlInputs.add(tfDomain); tfPassword.setPreferredSize(new java.awt.Dimension(200, 30)); pnlInputs.add(tfPassword); pnlCenter.add(pnlInputs); pnlCheckboxes.setBackground(new java.awt.Color(255, 255, 255)); pnlCheckboxes.setPreferredSize(null); pnlCheckboxes.setLayout(new javax.swing.BoxLayout(pnlCheckboxes, javax.swing.BoxLayout.Y_AXIS)); cbSavePassword.setBackground(new java.awt.Color(255, 255, 255)); cbSavePassword.setText("Save Password"); cbSavePassword.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbSavePassword); cbAutoLogin.setBackground(new java.awt.Color(255, 255, 255)); cbAutoLogin.setText("Auto login"); cbAutoLogin.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbAutoLogin); cbLoginInvisible.setBackground(new java.awt.Color(255, 255, 255)); cbLoginInvisible.setText("Login as invisible"); cbLoginInvisible.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbLoginInvisible); cbAnonymous.setBackground(new java.awt.Color(255, 255, 255)); cbAnonymous.setText("Login anonymously"); cbAnonymous.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbAnonymous); pnlCenter.add(pnlCheckboxes); pnlBtns.setBackground(new java.awt.Color(255, 255, 255)); pnlBtns.setPreferredSize(new java.awt.Dimension(220, 120)); btnLogin.setBackground(new java.awt.Color(241, 100, 34)); btnLogin.setForeground(new java.awt.Color(255, 255, 255)); btnLogin.setText("Login"); btnLogin.setPreferredSize(new java.awt.Dimension(205, 30)); btnLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLoginActionPerformed(evt); } }); pnlBtns.add(btnLogin); btnCreateAccount.setBackground(new java.awt.Color(255, 255, 255)); btnCreateAccount.setText("Create Account"); btnCreateAccount.setBorderPainted(false); btnCreateAccount.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); btnCreateAccount.setOpaque(false); btnCreateAccount.setPreferredSize(new java.awt.Dimension(110, 28)); pnlBtns.add(btnCreateAccount); btnAdvanced.setBackground(new java.awt.Color(255, 255, 255)); btnAdvanced.setText("Advanced"); btnAdvanced.setBorderPainted(false); btnAdvanced.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); btnAdvanced.setOpaque(false); btnAdvanced.setPreferredSize(new java.awt.Dimension(90, 28)); pnlBtns.add(btnAdvanced); btnReset.setBackground(new java.awt.Color(255, 255, 255)); btnReset.setText("Reset Password"); btnReset.setBorderPainted(false); btnReset.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); btnReset.setOpaque(false); btnReset.setPreferredSize(new java.awt.Dimension(205, 28)); btnReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnResetActionPerformed(evt); } }); pnlBtns.add(btnReset); pnlCenter.add(pnlBtns); add(pnlCenter, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnLoginActionPerformed private void tfUsernameMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tfUsernameMousePressed if (SwingUtilities.isRightMouseButton(evt)) { getPopup().show(tfUsername, evt.getX(), evt.getY()); } }//GEN-LAST:event_tfUsernameMousePressed private void tfUsernameMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tfUsernameMouseEntered // getPopup().show(tfUsername, evt.getX(), evt.getY()); }//GEN-LAST:event_tfUsernameMouseEntered private void tfUsernameMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tfUsernameMouseExited // getPopup().setVisible(false); }//GEN-LAST:event_tfUsernameMouseExited private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed final String url = Default.getString(Default.PASSWORD_RESET_URL); try { BrowserLauncher.openURL(url); } catch (Exception e) { Log.error("Unable to load password " + "reset.", e); } }//GEN-LAST:event_btnResetActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdvanced; private javax.swing.JButton btnCreateAccount; private javax.swing.JButton btnLogin; private javax.swing.JButton btnReset; private javax.swing.JCheckBox cbAnonymous; private javax.swing.JCheckBox cbAutoLogin; private javax.swing.JCheckBox cbLoginInvisible; private javax.swing.JCheckBox cbSavePassword; private javax.swing.Box.Filler filler1; private javax.swing.Box.Filler filler3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel lblLogo; public final javax.swing.JLabel lblProgress = new javax.swing.JLabel(); private javax.swing.JPanel pnlBtns; private javax.swing.JPanel pnlCenter; private javax.swing.JPanel pnlCheckboxes; private javax.swing.JPanel pnlInputs; private javax.swing.JPanel pnlLeft; private javax.swing.JTextField tfDomain; private javax.swing.JPasswordField tfPassword; private javax.swing.JTextField tfUsername; // End of variables declaration//GEN-END:variables public JTextField getUsernameField() { return tfUsername; } public JPasswordField getPasswordField() { return tfPassword; } public JButton getBtnLogin() { return btnLogin; } public JCheckBox getCbAutoLogin() { return cbAutoLogin; } /** * Invokes the LoginDialog to be visible. * * @param parentFrame the parentFrame of the Login Dialog. This is used for * correct parenting. */ public void invoke(final JFrame parentFrame) { // Before creating any connections. Update proxy if needed. try { updateProxyConfig(); } catch (Exception e) { Log.error(e); } loginDialog = new JFrame(Default.getString(Default.APPLICATION_NAME)); // Construct Dialog EventQueue.invokeLater(() -> { loginDialog.setIconImage(SparkManager.getApplicationImage().getImage()); loginDialog.setContentPane(this); loginDialog.setLocationRelativeTo(parentFrame); loginDialog.setResizable(false); loginDialog.pack(); loginDialog.setSize(550, 390); // Center dialog on screen GraphicUtils.centerWindowOnScreen(loginDialog); // Show dialog loginDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { quitLogin(); } }); if (getUsernameField().getText().trim().length() > 0) { getPasswordField().requestFocus(); } if (!localPref.isStartedHidden() || !localPref.isAutoLogin()) { // Make dialog top most. loginDialog.setVisible(true); } }); } //This method can be overwritten by subclasses to provide additional validations //(such as certificate download functionality when connecting) protected boolean beforeLoginValidations() { return true; } protected void afterLogin() { // Make certain Enterprise features persist across future logins persistEnterprise(); // Load plugins before Workspace initialization to avoid any UI delays during plugin rendering, but after // Enterprise initialization, which can pull in additional plugin configuration (eg: blacklist). PluginManager.getInstance().loadPlugins(); // Initialize and write default values from "Advanced Connection Preferences" to disk initAdvancedDefaults(); } protected XMPPTCPConnectionConfiguration retrieveConnectionConfiguration() { int port = localPref.getXmppPort(); int checkForPort = loginServer.indexOf(":"); if (checkForPort != -1) { String portString = loginServer.substring(checkForPort + 1); if (ModelUtil.hasLength(portString)) { // Set new port. port = Integer.valueOf(portString); } } ConnectionConfiguration.SecurityMode securityMode = localPref.getSecurityMode(); boolean useOldSSL = localPref.isSSL(); boolean hostPortConfigured = localPref.isHostAndPortConfigured(); ProxyInfo proxyInfo = null; if (localPref.isProxyEnabled()) { ProxyInfo.ProxyType pType = localPref.getProtocol().equals("SOCKS") ? ProxyInfo.ProxyType.SOCKS5 : ProxyInfo.ProxyType.HTTP; String pHost = ModelUtil.hasLength(localPref.getHost()) ? localPref.getHost() : null; int pPort = ModelUtil.hasLength(localPref.getPort()) ? Integer.parseInt(localPref.getPort()) : 0; String pUser = ModelUtil.hasLength(localPref.getProxyUsername()) ? localPref.getProxyUsername() : null; String pPass = ModelUtil.hasLength(localPref.getProxyPassword()) ? localPref.getProxyPassword() : null; if (pHost != null && pPort != 0) { if (pUser == null || pPass == null) { proxyInfo = new ProxyInfo(pType, pHost, pPort, null, null); } else { proxyInfo = new ProxyInfo(pType, pHost, pPort, pUser, pPass); } } else { Log.error("No proxy info found but proxy type is enabled!"); } } DomainBareJid xmppDomain; try { xmppDomain = JidCreate.domainBareFrom(loginServer); } catch (XmppStringprepException e) { throw new IllegalStateException(e); } final XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder() .setUsernameAndPassword(loginUsername, loginPassword) .setXmppDomain(xmppDomain) .setPort(port) .setSendPresence(false) .setCompressionEnabled(localPref.isCompressionEnabled()) .setSecurityMode(securityMode); if (securityMode != ConnectionConfiguration.SecurityMode.disabled && localPref.isDisableHostnameVerification()) { TLSUtils.disableHostnameVerificationForTlsCertificates(builder); } if (localPref.isDebuggerEnabled()) { builder.enableDefaultDebugger(); } if (hostPortConfigured) { builder.setHost(localPref.getXmppHost()); } if (localPref.isProxyEnabled()) { builder.setProxyInfo(proxyInfo); } if (securityMode != ConnectionConfiguration.SecurityMode.disabled && !useOldSSL) { // This use STARTTLS which starts initially plain connection to upgrade it to TLS, it use the same port as // plain connections which is 5222. SparkSSLContextCreator.Options options; if (localPref.isAllowClientSideAuthentication()) { options = SparkSSLContextCreator.Options.BOTH; } else { options = SparkSSLContextCreator.Options.ONLY_SERVER_SIDE; } try { SSLContext context = SparkSSLContextCreator.setUpContext(options); builder.setCustomSSLContext(context); builder.setSecurityMode(securityMode); } catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException | NoSuchProviderException e) { Log.warning("Couldnt establish secured connection", e); } } if (securityMode != ConnectionConfiguration.SecurityMode.disabled && useOldSSL) { if (!hostPortConfigured) { // SMACK 4.1.9 does not support XEP-0368, and does not apply a port change, if the host is not changed too. // Here, we force the host to be set (by doing a DNS lookup), and force the port to 5223 (which is the // default 'old-style' SSL port). DnsName serverNameDnsName = DnsName.from(loginServer); builder.setHost(DNSUtil.resolveXMPPServiceDomain(serverNameDnsName, null, ConnectionConfiguration.DnssecMode.disabled).get(0).getFQDN()); builder.setPort(5223); } SparkSSLContextCreator.Options options; if (localPref.isAllowClientSideAuthentication()) { options = SparkSSLContextCreator.Options.BOTH; } else { options = SparkSSLContextCreator.Options.ONLY_SERVER_SIDE; } builder.setSocketFactory(new SparkSSLSocketFactory(options)); // SMACK 4.1.9 does not recognize an 'old-style' SSL socket as being secure, which will cause a failure when // the 'required' Security Mode is defined. Here, we work around this by replacing that security mode with an // 'if-possible' setting. builder.setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible); } if (securityMode != ConnectionConfiguration.SecurityMode.disabled) { SASLAuthentication.registerSASLMechanism(new SASLExternalMechanism()); } // SPARK-1747: Don't use the GSS-API SASL mechanism when SSO is disabled. SASLAuthentication.unregisterSASLMechanism(SASLGSSAPIMechanism.class.getName()); SASLAuthentication.unregisterSASLMechanism(SASLGSSAPIv3CompatMechanism.class.getName()); // Add the mechanism only when SSO is enabled (which allows us to register the correct one). if (localPref.isSSOEnabled()) { // SPARK-1740: Register a mechanism that's compatible with Smack 3, when requested. if (localPref.isSaslGssapiSmack3Compatible()) { // SPARK-1747: Don't use the GSSAPI mechanism when SSO is disabled. SASLAuthentication.registerSASLMechanism(new SASLGSSAPIv3CompatMechanism()); } else { SASLAuthentication.registerSASLMechanism(new SASLGSSAPIMechanism()); } } if (localPref.isLoginAnonymously() && !localPref.isSSOEnabled()) { //later login() is called without arguments builder.performSaslAnonymousAuthentication(); } // TODO These were used in Smack 3. Find Smack 4 alternative. // config.setRosterLoadedAtLogin(true); // if(ModelUtil.hasLength(localPref.getTrustStorePath())) { // config.setTruststorePath(localPref.getTrustStorePath()); // config.setTruststorePassword(localPref.getTrustStorePassword()); return builder.build(); } /** * Returns the username the user defined. * * @return the username. */ private String getUsername() { return XmppStringUtils.escapeLocalpart(tfUsername.getText().trim()); } /** * Returns the resulting bareJID from username and server * * @return */ private String getBareJid() { return tfUsername.getText() + "@" + tfDomain.getText(); } /** * Returns the password specified by the user. * * @return the password. */ private String getPassword() { return new String(tfPassword.getPassword()); } /** * Returns the server name specified by the user. * * @return the server name. */ private String getServerName() { return tfDomain.getText().trim(); } /** * Return whether user wants to login as invisible or not. * * @return the true if user wants to login as invisible. */ boolean isLoginAsInvisible() { return cbLoginInvisible.isSelected(); } /** * ActionListener implementation. * * @param e the ActionEvent */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnCreateAccount) { AccountCreationWizard createAccountPanel = new AccountCreationWizard(); createAccountPanel.invoke(loginDialog); if (createAccountPanel.isRegistered()) { tfUsername.setText(createAccountPanel.getUsernameWithoutEscape()); tfPassword.setText(createAccountPanel.getPassword()); tfDomain.setText(createAccountPanel.getServer()); btnLogin.setEnabled(true); } } else if (e.getSource() == btnLogin) { validateLogin(); } else if (e.getSource() == btnAdvanced) { final LoginSettingDialog loginSettingsDialog = new LoginSettingDialog(); loginSettingsDialog.invoke(loginDialog); useSSO(localPref.isSSOEnabled()); } else if (e.getSource() == cbSavePassword) { cbAutoLogin.setEnabled(cbSavePassword.isSelected()); if (!cbSavePassword.isSelected()) { cbAutoLogin.setSelected(false); } } else if (e.getSource() == cbAutoLogin) { if ((cbAutoLogin.isSelected() && (!localPref.isSSOEnabled()))) { cbSavePassword.setSelected(true); } } else if (e.getSource() == cbAnonymous) { tfUsername.setEnabled(!cbAnonymous.isSelected()); tfPassword.setEnabled(!cbAnonymous.isSelected()); validateDialog(); } } private JPopupMenu getPopup() { JPopupMenu popup = new JPopupMenu(); for (final String key : _usernames) { JMenuItem menu = new JMenuItem(key); final String username = key.split("@")[0]; final String host = key.split("@")[1]; menu.addActionListener(e -> { tfUsername.setText(username); tfDomain.setText(host); try { tfPassword.setText(localPref.getPasswordForUser(getBareJid())); if (tfPassword.getPassword().length < 1) { btnLogin.setEnabled(cbAnonymous.isSelected()); } else { btnLogin.setEnabled(true); } } catch (Exception e1) { } }); popup.add(menu); } return popup; } /** * KeyListener implementation. * * @param e the KeyEvent to process. */ @Override public void keyTyped(KeyEvent e) { validate(e); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT && ((JTextField) e.getSource()).getCaretPosition() == ((JTextField) e.getSource()).getText().length()) { getPopup().show(otherUsers, 0, 0); } } @Override public void keyReleased(KeyEvent e) { validateDialog(); } /** * Checks the users input and enables/disables the login button depending on * state. */ private void validateDialog() { btnLogin.setEnabled(cbAnonymous.isSelected() || ModelUtil.hasLength(getUsername()) && (ModelUtil.hasLength(getPassword()) || localPref.isSSOEnabled()) && ModelUtil.hasLength(getServerName())); } /** * Validates key input. * * @param e the keyEvent. */ private void validate(KeyEvent e) { if (btnLogin.isEnabled() && e.getKeyChar() == KeyEvent.VK_ENTER) { validateLogin(); } } @Override public void focusGained(FocusEvent e) { Object o = e.getSource(); if (o instanceof JTextComponent) { ((JTextComponent) o).selectAll(); } } @Override public void focusLost(FocusEvent e) { } /** * Enables/Disables the editable components in the login screen. * * @param available true to enable components, otherwise false to disable. */ private void setComponentsAvailable(boolean available) { cbSavePassword.setEnabled(available); cbAutoLogin.setEnabled(available); cbLoginInvisible.setEnabled(available); cbAnonymous.setEnabled(available); // Need to set both editable and enabled for best behavior. tfUsername.setEditable(available); tfUsername.setEnabled(available && !cbAnonymous.isSelected()); tfPassword.setEditable(available); tfPassword.setEnabled(available && !cbAnonymous.isSelected()); if (Default.getBoolean(Default.HOST_NAME_CHANGE_DISABLED) || !localPref.getHostNameChange()) { tfDomain.setEditable(false); tfDomain.setEnabled(false); } else { tfDomain.setEditable(available); tfDomain.setEnabled(available); } if (available) { // Reapply focus to password field tfPassword.requestFocus(); } } /** * Displays the progress bar. * * @param visible true to display progress bar, false to hide it. */ private void setProgressBarVisible(boolean visible) { lblProgress.setVisible(visible); } /** * Validates the users login information. */ private void validateLogin() { final SwingWorker loginValidationThread = new SwingWorker() { @Override public Object construct() { setLoginUsername(getUsername()); setLoginPassword(getPassword()); setLoginServer(getServerName()); boolean loginSuccessfull = beforeLoginValidations() && login(); if (loginSuccessfull) { afterLogin(); lblProgress.setText(Res.getString("message.connecting.please.wait")); // Startup Spark startSpark(); // dispose login dialog loginDialog.dispose(); // Show ChangeLog if we need to. // new ChangeLogDialog().showDialog(); } else { EventQueue.invokeLater(() -> { setComponentsAvailable(true); setProgressBarVisible(false); }); } return loginSuccessfull; } }; // Start the login process in separate thread. // Disable text fields setComponentsAvailable(false); // Show progressbar setProgressBarVisible(true); loginValidationThread.start(); } @Override public Dimension getPreferredSize() { final Dimension dim = super.getPreferredSize(); dim.height = 230; return dim; } public void useSSO(boolean use) { if (use) { //usernameLabel.setVisible(true); tfUsername.setVisible(true); //passwordLabel.setVisible(false); tfPassword.setVisible(false); cbSavePassword.setVisible(false); cbSavePassword.setSelected(false); tfDomain.setVisible(true); cbAutoLogin.setVisible(true); //serverLabel.setVisible(true); cbLoginInvisible.setVisible(true); cbAnonymous.setVisible(false); if (localPref.getDebug()) { System.setProperty("java.security.krb5.debug", "true"); System.setProperty("sun.security.krb5.debug", "true"); } else { System.setProperty("java.security.krb5.debug", "false"); System.setProperty("sun.security.krb5.debug", "false"); } String ssoMethod = localPref.getSSOMethod(); if (!ModelUtil.hasLength(ssoMethod)) { ssoMethod = "file"; } System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); GSSAPIConfiguration config = new GSSAPIConfiguration(ssoMethod.equals("file")); Configuration.setConfiguration(config); LoginContext lc; String princName = localPref.getLastUsername(); String princRealm = null; try { lc = new LoginContext("com.sun.security.jgss.krb5.initiate"); lc.login(); Subject mySubject = lc.getSubject(); for (Principal p : mySubject.getPrincipals()) { //TODO: check if principal is a kerberos principal first... String name = p.getName(); int indexOne = name.indexOf("@"); if (indexOne != -1) { princName = name.substring(0, indexOne); princRealm = name.substring(indexOne + 1); } btnLogin.setEnabled(true); } } catch (LoginException le) { Log.debug(le.getMessage()); //useSSO(false); } String ssoKdc; if (ssoMethod.equals("dns")) { if (princRealm != null) { //princRealm is null if we got a LoginException above. ssoKdc = getDnsKdc(princRealm); System.setProperty("java.security.krb5.realm", princRealm); System.setProperty("java.security.krb5.kdc", ssoKdc); } } else if (ssoMethod.equals("manual")) { princRealm = localPref.getSSORealm(); ssoKdc = localPref.getSSOKDC(); System.setProperty("java.security.krb5.realm", princRealm); System.setProperty("java.security.krb5.kdc", ssoKdc); } else { //Assume "file" method. We don't have to do anything special, //java takes care of it for us. Unset the props if they are set System.clearProperty("java.security.krb5.realm"); System.clearProperty("java.security.krb5.kdc"); } String userName = localPref.getLastUsername(); if (ModelUtil.hasLength(userName)) { tfUsername.setText(userName); } else { tfUsername.setText(princName); } } else { cbAutoLogin.setVisible(true); tfUsername.setVisible(true); tfPassword.setVisible(true); cbSavePassword.setVisible(true); // usernameLabel.setVisible(true); // passwordLabel.setVisible(true); // serverLabel.setVisible(true); tfDomain.setVisible(true); cbLoginInvisible.setVisible(true); cbAnonymous.setVisible(true); Configuration.setConfiguration(null); validateDialog(); } } /** * Login to the specified server using username, password, and workgroup. * Handles error representation as well as logging. * * @return true if login was successful, false otherwise */ private boolean login() { localPref = SettingsManager.getLocalPreferences(); localPref.setLoginAsInvisible(cbLoginInvisible.isSelected()); localPref.setLoginAnonymously(cbAnonymous.isSelected()); if (localPref.isDebuggerEnabled()) { SmackConfiguration.DEBUG = true; } SmackConfiguration.setDefaultReplyTimeout(localPref.getTimeOut() * 1000); try { // TODO: SPARK-2140 - add support to Spark for stream management. Challenges expected around reconnection logic! XMPPTCPConnection.setUseStreamManagementDefault(false); connection = new XMPPTCPConnection(retrieveConnectionConfiguration()); connection.setParsingExceptionCallback(new ExceptionLoggingCallback()); // If we want to launch the Smack debugger, we have to check if we are on the dispatch thread, because Smack will create an UI. if (localPref.isDebuggerEnabled() && !EventQueue.isDispatchThread()) { // Exception handling should be no different from the regular flow. final Exception[] exception = new Exception[1]; EventQueue.invokeAndWait(() -> { try { connection.connect(); } catch (IOException | SmackException | XMPPException | InterruptedException e) { exception[0] = e; } }); if (exception[0] != null) { throw exception[0]; } } else { connection.connect(); } if (localPref.isLoginAnonymously() && !localPref.isSSOEnabled()) { // ConnectionConfiguration.performSaslAnonymousAuthentication() used earlier in connection configuration builder, // so now we can just login() connection.login(); } else { String resource = localPref.getResource(); if (Default.getBoolean(Default.HOSTNAME_AS_RESOURCE) || localPref.isUseHostnameAsResource()) { try { resource = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { Log.warning("Cannot set hostname as resource - unable to retrieve hostname.", e); } } else if (Default.getBoolean(Default.VERSION_AS_RESOURCE) || localPref.isUseVersionAsResource()) { resource = JiveInfo.getName() + " " + JiveInfo.getVersion(); } Resourcepart resourcepart = Resourcepart.from(modifyWildcards(resource).trim()); connection.login(getLoginUsername(), getLoginPassword(), resourcepart); } final SessionManager sessionManager = SparkManager.getSessionManager(); sessionManager.setServerAddress(connection.getXMPPServiceDomain()); sessionManager.initializeSession(connection, getLoginUsername(), getLoginPassword()); sessionManager.setJID(connection.getUser()); final ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection); reconnectionManager.setFixedDelay(localPref.getReconnectDelay()); reconnectionManager.setReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY); reconnectionManager.enableAutomaticReconnection(); final CarbonManager carbonManager = CarbonManager.getInstanceFor(connection); if (carbonManager.isSupportedByServer()) { carbonManager.enableCarbons(); } } catch (Exception xee) { Log.error("Exception in Login:", xee); final String errorMessage; if (localPref.isSSOEnabled()) { errorMessage = Res.getString("title.advanced.connection.sso.unable"); } else if (xee.getMessage() != null && xee.getMessage().contains("not-authorized")) { errorMessage = Res.getString("message.invalid.username.password"); } else if (xee.getMessage() != null && (xee.getMessage().contains("java.net.UnknownHostException:") || xee.getMessage().contains("Network is unreachable") || xee.getMessage().contains("java.net.ConnectException: Connection refused:"))) { errorMessage = Res.getString("message.server.unavailable"); } else if (xee.getMessage() != null && xee.getMessage().contains("Hostname verification of certificate failed")) { errorMessage = Res.getString("message.cert.hostname.verification.failed"); } else if (xee.getMessage() != null && xee.getMessage().contains("unable to find valid certification path to requested target")) { errorMessage = Res.getString("message.cert.verification.failed"); } else if (xee.getMessage() != null && xee.getMessage().contains("StanzaError: conflict")) { errorMessage = Res.getString("label.conflict.error"); } else if (xee instanceof SmackException) { errorMessage = xee.getLocalizedMessage(); } else { errorMessage = Res.getString("message.unrecoverable.error"); } EventQueue.invokeLater(() -> { lblProgress.setVisible(false); // Show error dialog UIManager.put("OptionPane.okButtonText", Res.getString("ok")); if (!loginDialog.isVisible()) { loginDialog.setVisible(true); } if (loginDialog.isVisible()) { if (xee.getMessage() != null && xee.getMessage().contains("Self Signed certificate")) { // Handle specific case: if server certificate is self-signed, but self-signed certs are not allowed, show a popup allowing the user to override. // Prompt user if they'd like to add the failed chain to the trust store. final Object[] options = { Res.getString("yes"), Res.getString("no") }; final int userChoice = JOptionPane.showOptionDialog(this, Res.getString("dialog.certificate.ask.allow.self-signed"), Res.getString("title.certificate"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if (userChoice == JOptionPane.YES_OPTION) { // Toggle the preference. localPref.setAcceptSelfSigned(true); SettingsManager.saveSettings(); // Attempt to login again. validateLogin(); } } else { final X509Certificate[] lastFailedChain = SparkTrustManager.getLastFailedChain(); final SparkTrustManager sparkTrustManager = (SparkTrustManager) SparkTrustManager.getTrustManagerList()[0]; // Handle specific case: if path validation failed because of an unrecognized CA, show popup allowing the user to add the certificate. if (lastFailedChain != null && ((xee.getMessage() != null && xee.getMessage().contains("Certificate not in the TrustStore")) || !sparkTrustManager.containsTrustAnchorFor(lastFailedChain))) { // Prompt user if they'd like to add the failed chain to the trust store. final CertificateModel certModel = new CertificateModel(lastFailedChain[0]); final Object[] options = { Res.getString("yes"), Res.getString("no") }; final int userChoice = JOptionPane.showOptionDialog(this, new UnrecognizedServerCertificatePanel(certModel), Res.getString("title.certificate"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if (userChoice == JOptionPane.YES_OPTION) { // Add the certificate chain to the truststore. sparkTrustManager.addChain(lastFailedChain); // Attempt to login again. validateLogin(); } } else { // For anything else, show a generic error dialog. MessageDialog.showErrorDialog(loginDialog, errorMessage, xee); } } } }); setEnabled(true); return false; } // Since the connection and workgroup are valid. Add a ConnectionListener connection.addConnectionListener(SparkManager.getSessionManager()); // Initialize chat state notification mechanism in smack ChatStateManager.getInstance(SparkManager.getConnection()); // Persist information localPref.setLastUsername(getLoginUsername()); // Check to see if the password should be saved or cleared from file. if (cbSavePassword.isSelected()) { try { localPref.setPasswordForUser(getBareJid(), getPassword()); } catch (Exception e) { Log.error("Error encrypting password.", e); } } else { try { localPref.clearPasswordForAllUsers();//clearPasswordForUser(getBareJid()); } catch (Exception e) { Log.debug("Unable to clear saved password..." + e); } } localPref.setSavePassword(cbSavePassword.isSelected()); localPref.setAutoLogin(cbAutoLogin.isSelected()); localPref.setServer(tfDomain.getText()); SettingsManager.saveSettings(); return true; } @Override public void handle(Callback[] callbacks) throws IOException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { NameCallback ncb = (NameCallback) callback; ncb.setName(getLoginUsername()); } else if (callback instanceof PasswordCallback) { PasswordCallback pcb = (PasswordCallback) callback; pcb.setPassword(getPassword().toCharArray()); } else { Log.error("Unknown callback requested: " + callback.getClass().getSimpleName()); } } } /** * If the user quits, just shut down the application. */ private void quitLogin() { System.exit(1); } /** * Initializes Spark and initializes all plugins. */ private void startSpark() { // Invoke the MainWindow. try { EventQueue.invokeLater(() -> { final MainWindow mainWindow = MainWindow.getInstance(); /* if (tray != null) { // Remove trayIcon tray.removeTrayIcon(trayIcon); } */ // Creates the Spark Workspace and add to MainWindow Workspace workspace = Workspace.getInstance(); LayoutSettings settings = LayoutSettingsManager.getLayoutSettings(); LocalPreferences pref = SettingsManager.getLocalPreferences(); if (pref.isDockingEnabled()) { JSplitPane splitPane = mainWindow.getSplitPane(); workspace.getCardPanel().setMinimumSize(null); splitPane.setLeftComponent(workspace.getCardPanel()); SparkManager.getChatManager().getChatContainer().setMinimumSize(null); splitPane.setRightComponent(SparkManager.getChatManager().getChatContainer()); int dividerLoc = settings.getSplitPaneDividerLocation(); if (dividerLoc != -1) { mainWindow.getSplitPane().setDividerLocation(dividerLoc); } else { mainWindow.getSplitPane().setDividerLocation(240); } mainWindow.getContentPane().add(splitPane, BorderLayout.CENTER); } else { mainWindow.getContentPane().add(workspace.getCardPanel(), BorderLayout.CENTER); } final Rectangle mainWindowBounds = settings.getMainWindowBounds(); if (mainWindowBounds == null || mainWindowBounds.width <= 0 || mainWindowBounds.height <= 0) { // Use Default size mainWindow.setSize(500, 520); // Center Window on Screen GraphicUtils.centerWindowOnScreen(mainWindow); } else { mainWindow.setBounds(mainWindowBounds); } if (loginDialog != null) { if (loginDialog.isVisible()) { mainWindow.setVisible(true); } loginDialog.dispose(); } // Build the layout in the workspace workspace.buildLayout(); }); } catch (Exception e) { e.printStackTrace(); } } /** * Updates System properties with Proxy configuration. * * @throws Exception thrown if an exception occurs. */ private void updateProxyConfig() throws Exception { if (ModelUtil.hasLength(Default.getString(Default.PROXY_PORT)) && ModelUtil.hasLength(Default.getString(Default.PROXY_HOST))) { String port = Default.getString(Default.PROXY_PORT); String host = Default.getString(Default.PROXY_HOST); System.setProperty("socksProxyHost", host); System.setProperty("socksProxyPort", port); return; } boolean proxyEnabled = localPref.isProxyEnabled(); if (proxyEnabled) { String host = localPref.getHost(); String port = localPref.getPort(); String username = localPref.getProxyUsername(); String password = localPref.getProxyPassword(); String protocol = localPref.getProtocol(); if (protocol.equals("SOCKS")) { System.setProperty("socksProxyHost", host); System.setProperty("socksProxyPort", port); if (ModelUtil.hasLength(username) && ModelUtil.hasLength(password)) { System.setProperty("java.net.socks.username", username); System.setProperty("java.net.socks.password", password); } } else { System.setProperty("http.proxyHost", host); System.setProperty("http.proxyPort", port); System.setProperty("https.proxyHost", host); System.setProperty("https.proxyPort", port); if (ModelUtil.hasLength(username) && ModelUtil.hasLength(password)) { System.setProperty("http.proxyUser", username); System.setProperty("http.proxyPassword", password); } } } } /** * Checks for historic Spark settings and upgrades the user. * * @throws Exception thrown if an error occurs. */ private void checkForOldSettings() throws Exception { // Check for old settings.xml File settingsXML = new File(Spark.getSparkUserHome(), "/settings.xml"); if (settingsXML.exists()) { SAXReader saxReader = new SAXReader(); Document pluginXML; try { // SPARK-2147: Disable certain features for security purposes (CVE-2020-10683) saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false); saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); pluginXML = saxReader.read(settingsXML); } catch (DocumentException e) { Log.error(e); return; } List<?> plugins = pluginXML.selectNodes("/settings"); for (Object plugin1 : plugins) { Element plugin = (Element) plugin1; String username = plugin.selectSingleNode("username").getText(); localPref.setLastUsername(username); String server = plugin.selectSingleNode("server").getText(); localPref.setServer(server); String autoLogin = plugin.selectSingleNode("autoLogin").getText(); localPref.setAutoLogin(Boolean.parseBoolean(autoLogin)); String savePassword = plugin.selectSingleNode("savePassword").getText(); localPref.setSavePassword(Boolean.parseBoolean(savePassword)); String password = plugin.selectSingleNode("password").getText(); localPref.setPasswordForUser(username + "@" + server, password); SettingsManager.saveSettings(); } // Delete settings File settingsXML.delete(); } } /** * Use DNS to lookup a KDC * * @param realm The realm to look up * @return the KDC hostname */ private String getDnsKdc(String realm) { //Assumption: the KDC will be found with the SRV record // _kerberos._udp.$realm try { Hashtable<String, String> env = new Hashtable<>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext context = new InitialDirContext(env); Attributes dnsLookup = context.getAttributes("_kerberos._udp." + realm, new String[]{"SRV"}); ArrayList<Integer> priorities = new ArrayList<>(); HashMap<Integer, List<String>> records = new HashMap<>(); for (Enumeration<?> e = dnsLookup.getAll(); e.hasMoreElements();) { Attribute record = (Attribute) e.nextElement(); for (Enumeration<?> e2 = record.getAll(); e2.hasMoreElements();) { String sRecord = (String) e2.nextElement(); String[] sRecParts = sRecord.split(" "); Integer pri = Integer.valueOf(sRecParts[0]); if (priorities.contains(pri)) { List<String> recs = records.get(pri); if (recs == null) { recs = new ArrayList<>(); } recs.add(sRecord); } else { priorities.add(pri); List<String> recs = new ArrayList<>(); recs.add(sRecord); records.put(pri, recs); } } } Collections.sort(priorities); List<String> l = records.get(priorities.get(0)); String toprec = l.get(0); String[] sRecParts = toprec.split(" "); return sRecParts[3]; } catch (NamingException e) { return ""; } } protected String getLoginUsername() { return loginUsername; } protected void setLoginUsername(String loginUsername) { this.loginUsername = loginUsername; } protected String getLoginPassword() { return loginPassword; } protected void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword; } protected String getLoginServer() { return loginServer; } protected void setLoginServer(String loginServer) { this.loginServer = loginServer; } protected ArrayList<String> getUsernames() { return _usernames; } private void persistEnterprise() { new Enterprise(); localPref.setAccountsReg(Enterprise.containsFeature(Enterprise.ACCOUNTS_REG_FEATURE)); localPref.setAdvancedConfig(Enterprise.containsFeature(Enterprise.ADVANCED_CONFIG_FEATURE)); localPref.setHostNameChange(Enterprise.containsFeature(Enterprise.HOST_NAME_FEATURE)); localPref.setInvisibleLogin(Enterprise.containsFeature(Enterprise.INVISIBLE_LOGIN_FEATURE)); localPref.setAnonymousLogin(Enterprise.containsFeature(Enterprise.ANONYMOUS_LOGIN_FEATURE)); localPref.setPswdAutologin(Enterprise.containsFeature(Enterprise.SAVE_PASSWORD_FEATURE)); localPref.setUseHostnameAsResource(Enterprise.containsFeature(Enterprise.HOSTNAME_AS_RESOURCE_FEATURE)); localPref.setUseVersionAsResource(Enterprise.containsFeature(Enterprise.VERSION_AS_RESOURCE_FEATURE)); } private void initAdvancedDefaults() { localPref.setCompressionEnabled(localPref.isCompressionEnabled()); localPref.setDebuggerEnabled(localPref.isDebuggerEnabled()); localPref.setDisableHostnameVerification(localPref.isDisableHostnameVerification()); localPref.setHostAndPortConfigured(localPref.isHostAndPortConfigured()); localPref.setProtocol("SOCKS"); localPref.setProxyEnabled(localPref.isProxyEnabled()); // localPref.setProxyPassword(""); // localPref.setProxyUsername(""); localPref.setResource("Spark"); localPref.setSaslGssapiSmack3Compatible(localPref.isSaslGssapiSmack3Compatible()); localPref.setSSL(localPref.isSSL()); localPref.setSecurityMode(localPref.getSecurityMode()); localPref.setSSOEnabled(localPref.isSSOEnabled()); localPref.setSSOMethod("file"); localPref.setTimeOut(localPref.getTimeOut()); // localPref.setTrustStorePassword(""); // localPref.setTrustStorePath(""); localPref.setUseHostnameAsResource(localPref.isUseHostnameAsResource()); localPref.setUseVersionAsResource(localPref.isUseVersionAsResource()); // localPref.setXmppHost(""); localPref.setXmppPort(localPref.getXmppPort()); SettingsManager.saveSettings(); } }
package authzadmin; import authzadmin.shibboleth.ShibbolethPreAuthenticatedProcessingFilter; import authzadmin.shibboleth.ShibbolethUserDetailService; import authzadmin.shibboleth.mock.MockShibbolethFilter; import authzadmin.voot.EnsureAccessFilter; import authzadmin.voot.VootClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.*; import org.springframework.context.annotation.Scope; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; import org.springframework.security.oauth2.client.token.AccessTokenRequest; import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; import javax.annotation.Resource; import java.util.Map; @Configuration @EnableWebSecurity public class ShibbolethSecurityConfig extends WebSecurityConfigurerAdapter { private static final Logger LOG = LoggerFactory.getLogger(ShibbolethSecurityConfig.class); @Autowired private VootClient vootClient; @Value("${allowed_group}") private String allowedGroup; @Bean @Profile("dev") public FilterRegistrationBean mockShibbolethFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new MockShibbolethFilter());
package com.jnhankins.jff.render.ocl; import com.jnhankins.jff.flame.Flame; import com.jnhankins.jff.flame.VariationDefinition; import com.jnhankins.jff.render.FlameRenderer; import com.jnhankins.jff.render.RendererSettings; import com.jnhankins.jff.render.RendererTask; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.net.URI; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.file.*; import java.util.*; import org.jocl.*; import static org.jocl.CL.*; /** * * @author Jeremiah N. Hankins */ public class FlameRendererOpenCL extends FlameRenderer { // Progam Code Templates private static final String oclVariationCodeTemplatePath = "OCLVariationTemplate.cl"; private static final String oclProgramCodeTemplatePath = "OCLProgramTemplate.cl"; private static String oclVariationCodeTemplate; private static String oclProgramCodeTemplate; private static FileSystem fileSystem; // OpenCL Platform and Device Info private final int platformIndex; private final int deviceIndex; private final cl_platform_id platform; private final cl_device_id device; // OpenCL Context and Command Queue private cl_context context; private cl_command_queue queue; // OpenCL Program private final Set<VariationDefinition> variationSet = new TreeSet(); private cl_program program; private cl_kernel initKernel; private cl_kernel warmKernel; private cl_kernel plotKernel; private cl_kernel previewKernel; private cl_kernel finishKernel1; private cl_kernel finishKernel2; // Worksize private int workSize = -1; private long[] workOffset = new long[1]; private long[] workSizePlot = new long[1]; private long[] workSizeColor = new long[1]; // Iteration Buffers private int workCapacity = -1; private cl_mem iterRStateMem; private cl_mem iterPointsMem; private cl_mem iterColorsMem; // Xform Buffers private int xformCapacity = -1; private int xformVariationsCapacity = -1; private int xformParametersCapacity = -1; private cl_mem xformWeightMem; private cl_mem xformCmixesMem; private cl_mem xformColorsMem; private cl_mem xformAffineMem; private cl_mem xformVariationsMem; private cl_mem xformParametersMem; // Flame Buffers private cl_mem flameViewAffineMem; private cl_mem flameColorationMem; private cl_mem flameBackgroundMem; // Blur Param Buffer private cl_mem blurParamMem; // Image Buffers private int imageCapacity = -1; private cl_mem histogramMem; private cl_mem preRasterMem; private cl_mem imgRasterMem; // Hit-Counts Buffer private cl_mem hitcountsMem; // Bufferd Images private BufferedImage frontImage; private BufferedImage backImage; // The preview time private long updateInterval; private long preUpdateTime; // Current flame, settings, and listeners private RendererTask task; private Flame flame; private RendererSettings settings; static { // Enable exceptions setExceptionsEnabled(true); } public FlameRendererOpenCL(DeviceType type) { // Get the platforms int numPlatforms[] = new int[1]; clGetPlatformIDs(0, null, numPlatforms); cl_platform_id platforms[] = new cl_platform_id[numPlatforms[0]]; clGetPlatformIDs(platforms.length, platforms, null); // Keep track of which device & platform is the fastest int bestPlatformIndex = -1; int bestDeviceIndex = -1; cl_platform_id bestPlatform = null; cl_device_id bestDevice = null; int bestSpeed = -1; // For each platform for (int platformI=0; platformI<platforms.length; platformI++) { cl_platform_id currPlatform = platforms[platformI]; // Get all devices cl_device_id[] devices = getAllDevices(currPlatform); // For each device for (int deviceI=0; deviceI<devices.length; deviceI++) { cl_device_id currDevice = devices[deviceI]; // Skip this device if it is not the correct type if ((getDeviceLong(currDevice, CL_DEVICE_TYPE) & type.type) == 0) continue; // Determine the speed of the device int freq = getDeviceInt(currDevice, CL_DEVICE_MAX_CLOCK_FREQUENCY); int unit = getDeviceInt(currDevice, CL_DEVICE_MAX_COMPUTE_UNITS); int speed = freq*unit; // Keep track of the fastest device and platform if (bestSpeed < speed) { bestPlatformIndex = platformI; bestDeviceIndex = deviceI; bestPlatform = currPlatform; bestDevice = currDevice; bestSpeed = speed; } } } // If no suitable platform and device was found, throw an exception if (bestPlatform == null || bestDevice == null) throw new RuntimeException("Could not find a suitable platform and device of type: "+type.name()); // Store the platform and device info platformIndex = bestPlatformIndex; deviceIndex = bestDeviceIndex; platform = bestPlatform; device = bestDevice; } public FlameRendererOpenCL(int platformIndex, int deviceIndex) { // Store the platform and device indexes this.platformIndex = platformIndex; this.deviceIndex = deviceIndex; // Obtain the platform cl_platform_id platforms[] = getAllPlatforms(); if (!(0<=platformIndex && platformIndex<platforms.length)) throw new IllegalArgumentException("Invalid platform and device index pair: "+platformIndex+" "+deviceIndex); platform = platforms[platformIndex]; // Obtain the device cl_device_id devices[] = getAllDevices(platform); if (!(0<=deviceIndex && deviceIndex<devices.length)) throw new IllegalArgumentException("Invalid platform and device index pair: "+platformIndex+" "+deviceIndex); device = devices[deviceIndex]; } /** * Returns the index of the OpenCL platform being used by this * {@code FlameRendererOpenCL} object. * * @return the index of the OpenCL platform being used by this * {@code FlameRendererOpenCL} object. */ public int getPlatformIndex() { return platformIndex; } /** * Returns the index of the OpenCL device being used by this * {@code FlameRendererOpenCL} object. * * @return the index of the OpenCL device being used by this * {@code FlameRendererOpenCL} object */ public int getDeviceIndex() { return deviceIndex; } /** * Returns the {@code String} name of the OpenCL platform being used by this * {@code FlameRendererOpenCL} object. * * @return the {@code String} name of the OpenCL platform being used by this * {@code FlameRendererOpenCL} object */ public String getPlatformName() { return getPlatformString(platform, CL_PLATFORM_NAME); } /** * Returns the {@code String} name of the OpenCL device being used by this * {@code FlameRendererOpenCL} object. * * @return the {@code String} name of the OpenCL device being used by this * {@code FlameRendererOpenCL} object */ public String getDeviceName() { return getDeviceString(device, CL_DEVICE_NAME); } /** * Returns the maximum clock frequency for the OpenCL device being used by * this {@code FlameRendererOpenCL} object. * * @return the maximum clock frequency for the OpenCL device being used by * this {@code FlameRendererOpenCL} object. */ public int getDeviceMaxClockFrequency() { return getDeviceInt(device, CL_DEVICE_MAX_CLOCK_FREQUENCY); } /** * Returns the maximum number of avaiable compute units for the OpenCL * device being used by this {@code FlameRendererOpenCL} object. * * @return the maximum number of avaiable compute units for the OpenCL * device being used by this {@code FlameRendererOpenCL} object. */ public int getDeviceMaxComputeUnits() { return getDeviceInt(device, CL_DEVICE_MAX_COMPUTE_UNITS); } @Override public void setUpdatesPerSec(double updatesPerSecond) { super.setUpdatesPerSec(updatesPerSecond); if (updatesPerSecond <= 0) { updateInterval = 0; } else { updateInterval = Math.max((long)(1e9/updatesPerSecond), 1); } } @Override public String toString() { StringBuilder str = new StringBuilder(); str.append("Flame Renderer {\n"); str.append(" Status: "); if (isRunning()) str.append("RUNNING\n"); else if (isShutdown()) str.append("SHUTDOWN\n"); else if (isTerminated()) str.append("TERMINATED\n"); else str.append("READY\n"); str.append(" Type: OpenCL\n"); str.append(" CL_PLATFORM_INDEX: ").append(platformIndex).append('\n'); str.append(" CL_PLATFORM_NAME: ").append(getPlatformName()).append('\n'); str.append(" CL_PLATFORM_VERSION: ").append(getPlatformString(platform, CL_PLATFORM_VERSION)).append('\n'); str.append(" CL_DEVICE_INDEX: ").append(platformIndex).append('\n'); str.append(" CL_DEVICE_NAME: ").append(getDeviceName()).append('\n'); str.append(" CL_DEVICE_MAX_CLOCK_FREQUENCY: ").append(getDeviceMaxClockFrequency()).append('\n'); str.append(" CL_DEVICE_MAX_COMPUTE_UNITS: ").append(getDeviceMaxComputeUnits()).append('\n'); str.append(" updatesPerSec: ").append(getUpdatesPerSec()).append('\n'); str.append(" updateImages: ").append(getUpdateImages()).append('\n'); str.append(" isBatchAccelerated: ").append(this.isBatchAccerlated()).append('\n'); str.append(" maxBatchTime: ").append(this.getMaxBatchTimeSec()).append('\n'); str.append("}"); return str.toString(); } @Override protected void initResources() { // Initialize code templates loadCodeTempaltes(); // Create the context cl_context_properties contextProps = new cl_context_properties(); contextProps.addProperty(CL_CONTEXT_PLATFORM, platform); context = clCreateContext(contextProps, 1, new cl_device_id[]{device}, null, null, null); // Create the command-queue queue = clCreateCommandQueue(context, device, 0, null); // Create fixed-size mem objets flameViewAffineMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, 6*Sizeof.cl_float, null, null); flameColorationMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, 3*Sizeof.cl_float, null, null); flameBackgroundMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, 4*Sizeof.cl_float, null, null); blurParamMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, 3*Sizeof.cl_float, null, null); hitcountsMem = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, 2*Sizeof.cl_int, null, null); } private String loadCodeTemplate(String templatePath) { try { // Get the resource URL URL url = getClass().getResource(templatePath); if (url == null) throw new FileNotFoundException("Could not find file: "+templatePath); // Do some nonsense to be able to read from within the JAR String[] array = url.toURI().toString().split("!"); if (fileSystem == null) { URI uri = URI.create(array[0]); try { fileSystem = FileSystems.getFileSystem(uri); } catch (FileSystemNotFoundException ex) { Map<String, String> env = new HashMap(); env.put("create","true"); fileSystem = FileSystems.newFileSystem(uri, env); } } // Return the entire file as a String return new String(Files.readAllBytes(fileSystem.getPath(array[1]))); } catch (URISyntaxException | IOException ex) { // Should never happen unless the user deletes or renames the // OpenCL template files. throw new RuntimeException(ex); } } private void loadCodeTempaltes() { // Load the variation tempalte code if (oclVariationCodeTemplate == null) { String temp = loadCodeTemplate(oclVariationCodeTemplatePath); temp = temp.replaceAll("\r\n","\n"); // Remove redundent carriage returns temp = temp.replaceAll("\r","\n"); // Convert the remaining carriage returns to newlines temp = temp.substring(temp.indexOf("//")); // Remove header oclVariationCodeTemplate = temp; } // Load the kenel template code if (oclProgramCodeTemplate == null) { String temp = loadCodeTemplate(oclProgramCodeTemplatePath); temp = temp.replaceAll("\r\n","\n"); // Remove redundent carriage returns temp = temp.replaceAll("\r","\n"); // Convert the remaining carriage returns to newlines oclProgramCodeTemplate = temp; } } @Override protected void freeResources() { // Work Size workSize = -1; // Iteration Buffers workCapacity = -1; if (iterRStateMem != null) { clReleaseMemObject(iterRStateMem); iterRStateMem = null; } if (iterPointsMem != null) { clReleaseMemObject(iterPointsMem); iterPointsMem = null; } if (iterColorsMem != null) { clReleaseMemObject(iterColorsMem); iterColorsMem = null; } // Xform Buffers xformCapacity = -1; xformVariationsCapacity = -1; xformParametersCapacity = -1; if (xformWeightMem != null) { clReleaseMemObject(xformWeightMem); xformWeightMem = null; } if (xformCmixesMem != null) { clReleaseMemObject(xformCmixesMem); xformCmixesMem = null; } if (xformColorsMem != null) { clReleaseMemObject(xformColorsMem); xformColorsMem = null; } if (xformAffineMem != null) { clReleaseMemObject(xformAffineMem); xformAffineMem = null; } if (xformVariationsMem != null) { clReleaseMemObject(xformVariationsMem); xformVariationsMem = null; } if (xformParametersMem != null) { clReleaseMemObject(xformParametersMem); xformParametersMem = null; } // Flame Buffers if (flameViewAffineMem != null) { clReleaseMemObject(flameViewAffineMem); flameViewAffineMem = null; } if (flameColorationMem != null) { clReleaseMemObject(flameColorationMem); flameColorationMem = null; } if (flameBackgroundMem != null) { clReleaseMemObject(flameBackgroundMem); flameBackgroundMem = null; } // Blur Param Buffer if (blurParamMem != null) { clReleaseMemObject(blurParamMem); blurParamMem = null; } // Image Buffers imageCapacity = -1; if (histogramMem != null) { clReleaseMemObject(histogramMem); histogramMem = null; } if (preRasterMem != null) { clReleaseMemObject(preRasterMem); preRasterMem = null; } if (imgRasterMem != null) { clReleaseMemObject(imgRasterMem); imgRasterMem = null; } // Hit-Counts Buffer if (hitcountsMem != null) { clReleaseMemObject(hitcountsMem); hitcountsMem = null; } // Bufferd Images frontImage = null; backImage = null; // OpenCL Program variationSet.clear(); if (initKernel != null) { clReleaseKernel(initKernel); initKernel = null; } if (warmKernel != null) { clReleaseKernel(warmKernel); warmKernel = null; } if (plotKernel != null) { clReleaseKernel(plotKernel); plotKernel = null; } if (previewKernel != null) { clReleaseKernel(previewKernel); previewKernel = null; } if (finishKernel1 != null) { clReleaseKernel(finishKernel1); finishKernel1 = null; } if (finishKernel2 != null) { clReleaseKernel(finishKernel2); finishKernel2 = null; } if (program != null) { clReleaseProgram(program); program = null; } // OpenCL Data if (queue != null) { clReleaseCommandQueue(queue); queue = null; } if (context != null) { clReleaseContext(context); context = null; } } @Override protected void renderNextFlame(RendererTask task) { // Store the task this.task = task; settings = task.getSettings(); flame = task.getNextFlame(); workSizeColor[0] = settings.getWidth()*settings.getHeight(); // Prepare the OpenCL program and kernels prepCLProgram(); // Prep flame buffers prepFlameBuffers(); // Prep iter buffers prepIterBuffers(); // Prep image buffers prepImageBuffers(); // Prep hit coutners buffer prepHitCountsBuffer(); // Run the init kernel clEnqueueNDRangeKernel(queue, initKernel, 1, workOffset, workSizePlot, null, 0, null, null); // Run the warmup kernel int[] numTransforms = new int[] { flame.getNumTransforms() }; clSetKernelArg(warmKernel, 0, Sizeof.cl_int, Pointer.to(numTransforms)); clEnqueueNDRangeKernel(queue, warmKernel, 1, workOffset, workSizePlot, null, 0, null, null); // Set the remaining plot kernel args clSetKernelArg(plotKernel, 0, Sizeof.cl_float, Pointer.to(new float[]{settings.getWidth()})); clSetKernelArg(plotKernel, 1, Sizeof.cl_float, Pointer.to(new float[]{settings.getHeight()})); clSetKernelArg(plotKernel, 2, Sizeof.cl_int, Pointer.to(numTransforms)); // Set the remaining blur kernel args if needed if (settings.getUseBlur()) { clSetKernelArg(finishKernel2, 0, Sizeof.cl_float, Pointer.to(new int[] { settings.getWidth() })); clSetKernelArg(finishKernel2, 1, Sizeof.cl_float, Pointer.to(new int[] { settings.getHeight() })); ByteBuffer blurParamBuffer = clEnqueueMapBuffer(queue, blurParamMem, CL_BLOCKING, CL_MAP_WRITE, 0, 3*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); blurParamBuffer.putFloat(settings.getBlurAlpha()); blurParamBuffer.putFloat(settings.getBlurMinRadius()); blurParamBuffer.putFloat(settings.getBlurMaxRadius()); // (2n+1)^2 blurParamBuffer.rewind(); clEnqueueUnmapMemObject(queue, blurParamMem, blurParamBuffer, 0, null, null); } // Keep track of the image quality long longTotalHits = 0, longPixelHits = 0; int totalHits, pixelHits; double currQuality = 0; // Start the timer long currTime = System.nanoTime(); long startTime = currTime; // Keep track of the total number of points plotted long numIter = 0; // Keep track of the total elapsed time double elapTime = 0; // Store frequenly used settings on the stack double maxTime = settings.getMaxTime(); double maxQuality = settings.getMaxQuality(); // If the renderer is overdue for a preview image, force one to happen boolean forcePreview = updateImages && updateInterval > 0 && currTime >= preUpdateTime+updateInterval; // Set the batch size. Always starts at 1. May change each iteration if // the isBatchAccerlated flag is set to true. int[] batchSize = new int[] { 1 }; Pointer batchPointer = Pointer.to(batchSize); clSetKernelArg(plotKernel, 15, Sizeof.cl_int, batchPointer); // Store a copy of the isAccerlated flag on the stack, so that if the // flag changes mid render, an error does not occur. boolean isAccel = isBatchAccelerated; // Get the maximum batch time double maxBatchTime = calcMaxBatchTimeSec(); // Perform the main ploting cycle while ((!task.isCancelled()|| forcePreview) && currQuality < maxQuality && elapTime < maxTime) { // If it is time to update if (updateInterval > 0 && currTime >= preUpdateTime+updateInterval) { // If not generating update image... if (!updateImages) { // Send a progress update callback without an image update(task, flame, null, currQuality, numIter*workSize, elapTime, false); // Calculate the 'previous' update time preUpdateTime = Math.max(preUpdateTime+updateInterval, currTime-updateInterval); } else if (numIter >= 20) { // Update the image updateImage(currQuality, numIter*workSize, startTime, false); // Calculate the 'previous' preview time preUpdateTime = Math.max(preUpdateTime+updateInterval, currTime-updateInterval); // Unset the force preview flag forcePreview = false; // If we just previewed and the task is cancled, return if (task.isCancelled()) { return; } } } // Flush and finish the queue to prevent hanging clFinish(queue); // Keep track of how long it takes to run the batch long batchTime = System.nanoTime(); // Run the plotting kernel clEnqueueNDRangeKernel(queue, plotKernel, 1, workOffset, workSizePlot, null, 0, null, null); clFinish(queue); batchTime = System.nanoTime() - batchTime; // Map the hit counters buffer for reading ByteBuffer hitCounters = clEnqueueMapBuffer(queue, hitcountsMem, CL_BLOCKING, CL.CL_MAP_READ, 0, 2*Sizeof.cl_int, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); // Get the total number pixel hits totalHits = hitCounters.getInt(); // Get the number of individual pixel's hit pixelHits = hitCounters.getInt(); // Rewind the hit counters buffer hitCounters.rewind(); // Unmap the hit counters buffer clEnqueueUnmapMemObject(queue, hitcountsMem, hitCounters, 0, null, null); // If the total-hits counter overflows... if (totalHits < 0) { // Map the hit counters buffer for writing hitCounters = clEnqueueMapBuffer(queue, hitcountsMem, CL_BLOCKING, CL.CL_MAP_WRITE, 0, 2*Sizeof.cl_int, 0, null, null, null); // Zero the buffer hitCounters.putLong(0); // Unmap the hit counters buffer clEnqueueUnmapMemObject(queue, hitcountsMem, hitCounters, 0, null, null); // Accumulate the total hits and pixel hits into the long totals longTotalHits += totalHits & 0xFFFFFFFFL; longPixelHits += pixelHits & 0xFFFFFFFFL; // Zero the counters totalHits = 0; pixelHits = 0; } // Rember the old quality double oldQuality = currQuality; // Calculate the current quality currQuality = pixelHits==0?0:(longTotalHits+totalHits)/(double)(longPixelHits+pixelHits); // Get the curren time currTime = System.nanoTime(); // Calculate the elapsed time elapTime = (currTime-startTime)/1e9; // Update the total number of iterations numIter += batchSize[0]; // If using the accelerated batching algorithm... if (isAccel) { // Caclulate the improvement in quality per second double qrate = (currQuality - oldQuality)/(batchTime*1e-9); // Caclualte the seconds remaining based on quality double dtime = (maxQuality - currQuality)/qrate; // Reduce the time for the next batch based on max-time dtime = Math.min(dtime, maxTime - elapTime); // If using a max batch-time, limit by the max batch-time if (maxBatchTime > 0) dtime = Math.min(dtime, maxBatchTime); // Reduce the time for the next batch based on the next update // Calc the batch next batch-size based on the batch-time int iBatchSize = (int)(batchSize[0]*dtime/batchTime*1e9); // Ensure the batch size is atleast one batchSize[0] = iBatchSize <= 0? 1 : iBatchSize; // Set the batch size argument clSetKernelArg(plotKernel, 15, Sizeof.cl_int, batchPointer); } } // If the task has not been cancled, update the final image if (!task.isCancelled()) { // Update the image updateImage(currQuality, numIter*workSize, startTime, true); } } private void prepCLProgram() { // Get all of the variation definitions from the flame Set<VariationDefinition> variations = flame.getVariationSet(); // If this variation set is not equal to the flame's variation set if (!variationSet.equals(variations)) { // Make this variation set equal to the flame's variation set variationSet.clear(); variationSet.addAll(variations); // Recompile the OpenCL program kernels makeCLProgram(); } } private void makeCLProgram() { // Release the existing program and kernels if (initKernel != null) { clReleaseKernel(initKernel); initKernel = null; } if (warmKernel != null) { clReleaseKernel(warmKernel); warmKernel = null; } if (plotKernel != null) { clReleaseKernel(plotKernel); plotKernel = null; } if (previewKernel != null) { clReleaseKernel(previewKernel); previewKernel = null; } if (finishKernel1 != null) { clReleaseKernel(finishKernel1); finishKernel1 = null; } if (finishKernel2 != null) { clReleaseKernel(finishKernel2); finishKernel2 = null; } if (program != null) { clReleaseProgram(program); program = null; } // Create the clProgram code for this set of variations String programSource = makeCLProgramCode(); try { // Print the source code // printSourceCode(programSource); // Create the program program = clCreateProgramWithSource(context, 1, new String[]{ programSource }, null, null); // Create the device list cl_device_id[] devices = new cl_device_id[] { device }; // Compile the program on the device clBuildProgram(program, 1, devices, "-cl-fast-relaxed-math", null, null); // Create the kernels initKernel = clCreateKernel(program, "initKernel", null); warmKernel = clCreateKernel(program, "warmKernel", null); plotKernel = clCreateKernel(program, "plotKernel", null); previewKernel = clCreateKernel(program, "quckFinishKernel", null); finishKernel1 = clCreateKernel(program, "blurFinishKernel1", null); finishKernel2 = clCreateKernel(program, "blurFinishKernel2", null); // Determine the work group size clGetKernelWorkGroupInfo(plotKernel, device, CL_KERNEL_WORK_GROUP_SIZE, Sizeof.size_t, Pointer.to(workSizePlot), null); workSize = (int)workSizePlot[0]; // System.out.println("workSize: "+workSize); // Set kernel arguments setKernelArgs(); } catch (Exception ex) { // Print the source code printSourceCode(programSource); // Print the error stack trage ex.printStackTrace(System.err); } } private String makeCLProgramCode() { // Create the kernel #define flags source code block StringBuilder flags = new StringBuilder(); // If linear variations are the only variations, then disable variations boolean useVariations = settings.getUseVariations(); if (variationSet.size() == 1 && variationSet.contains(VariationDefinition.LINEAR)) useVariations = false; if (useVariations) flags.append("#define USE_VARIATIONS 1\n"); if (settings.getUseFinalTransform()) flags.append("#define USE_FINAL_TRANSFORM 1\n"); if (settings.getUsePostAffines()) flags.append("#define USE_POST_AFFINES 1\n"); if (settings.getUseJitter()) flags.append("#define USE_JITTER 1\n"); // Create the variation code block StringBuilder variationCodeBlock = new StringBuilder(); // Keep track of the variation and parameter indexes int variationIndex = 0; int parameterIndex = 0; // For each variation for (VariationDefinition variation: variationSet) { // Get the varation's name String variationName = variation.getName(); // Get the variation's source code String variationCode = variation.getCode(); // For each paramter in theis variation definition for (String parameterName: variation.getParameters().keySet()) { // Replace direct references to parameters with a references to the parameter array variationCode = variationCode.replaceAll(parameterName, "(PARAMETERS["+parameterIndex+"])"); // Increment the parameter index parameterIndex++; } // Format the variation's source code variationCode = variationCode.replaceAll("\n","\n ").trim(); // Insert the variation's source code intot he variation block template variationCode = oclVariationCodeTemplate.replaceAll("___VARIATION_SOURCE_CODE___", variationCode); // Insert the variation's name variationCode = variationCode.replaceAll("___VARIATION_NAME___", variationName); // Insert the variation's index variationCode = variationCode.replaceAll("___VARIATION_INDEX___", Integer.toString(variationIndex)); // Insert the variation's coefficient refeence variationCode = variationCode.replaceAll("COEF", "(VARIATIONS["+variationIndex+"])"); // Append this variation's code to the rest of the variation code block variationCodeBlock.append(variationCode); // Increment the variation index variationIndex++; } // Initialize the clProgram's source code from the template String newProgramCode = oclProgramCodeTemplate; // Insert the kernel flags newProgramCode = newProgramCode.replaceFirst("___FLAGS___", flags.toString()); // Insert the variation source block newProgramCode = newProgramCode.replaceFirst("___VARIATIONS___", variationCodeBlock.toString()); // Insert the total number of variations newProgramCode = newProgramCode.replaceAll("___NUM_VARIATIONS___", Integer.toString(flame.getNumVariations())); // Insert the total number of parameters newProgramCode = newProgramCode.replaceAll("___NUM_PARAMETERS___", Integer.toString(flame.getNumParameters())); // Return the clProgram code return newProgramCode; } private void printSourceCode(String programCode) { // Split the source code by line String[] lines = programCode.split("\n"); // Figure out how many digits are needed to display the largest line number int numDigits = (int)Math.log10(lines.length)+1; // Use a string builder to build the output string StringBuilder builder = new StringBuilder(); // For each line for (int i=0; i<lines.length; i++) { // Prefix the line with the line number using left 0 paded numbers builder.append(String.format("%"+numDigits+"d", i).replace(' ', '0')); // Append the line builder.append(" "); builder.append(lines[i]); builder.append("\n"); } // Print the source code to the error stream System.err.println(builder.toString()); } private void setKernelArgs() { if (iterRStateMem != null) { /// InitKernel clSetKernelArg(initKernel, 0, Sizeof.cl_mem, Pointer.to(iterRStateMem)); clSetKernelArg(initKernel, 1, Sizeof.cl_mem, Pointer.to(iterPointsMem)); clSetKernelArg(initKernel, 2, Sizeof.cl_mem, Pointer.to(iterColorsMem)); /// WarmKernel // clSetKernelArg(warmKernel, 0, Sizeof.cl_int, numTransforms); clSetKernelArg(warmKernel, 1, Sizeof.cl_mem, Pointer.to(xformWeightMem)); clSetKernelArg(warmKernel, 2, Sizeof.cl_mem, Pointer.to(xformCmixesMem)); clSetKernelArg(warmKernel, 3, Sizeof.cl_mem, Pointer.to(xformColorsMem)); clSetKernelArg(warmKernel, 4, Sizeof.cl_mem, Pointer.to(xformAffineMem)); clSetKernelArg(warmKernel, 5, Sizeof.cl_mem, Pointer.to(xformVariationsMem)); clSetKernelArg(warmKernel, 6, Sizeof.cl_mem, Pointer.to(xformParametersMem)); clSetKernelArg(warmKernel, 7, Sizeof.cl_mem, Pointer.to(iterRStateMem)); clSetKernelArg(warmKernel, 8, Sizeof.cl_mem, Pointer.to(iterPointsMem)); clSetKernelArg(warmKernel, 9, Sizeof.cl_mem, Pointer.to(iterColorsMem)); /// PlotKernel // clSetKernelArg(plotKernel, 0, Sizeof.cl_float, Pointer.to{new float[]{width,}); // clSetKernelArg(plotKernel, 1, Sizeof.cl_float, Pointer.to{new float[]{height}); // clSetKernelArg(plotKernel, 2, Sizeof.cl_int, numTransforms); clSetKernelArg(plotKernel, 3, Sizeof.cl_mem, Pointer.to(xformWeightMem)); clSetKernelArg(plotKernel, 4, Sizeof.cl_mem, Pointer.to(xformCmixesMem)); clSetKernelArg(plotKernel, 5, Sizeof.cl_mem, Pointer.to(xformColorsMem)); clSetKernelArg(plotKernel, 6, Sizeof.cl_mem, Pointer.to(xformAffineMem)); clSetKernelArg(plotKernel, 7, Sizeof.cl_mem, Pointer.to(xformVariationsMem)); clSetKernelArg(plotKernel, 8, Sizeof.cl_mem, Pointer.to(xformParametersMem)); // clSetKernelArg(plotKernel, 9, Sizeof.cl_mem, Pointer.to(flameViewAffineMem)); clSetKernelArg(plotKernel, 10, Sizeof.cl_mem, Pointer.to(iterRStateMem)); clSetKernelArg(plotKernel, 11, Sizeof.cl_mem, Pointer.to(iterPointsMem)); clSetKernelArg(plotKernel, 12, Sizeof.cl_mem, Pointer.to(iterColorsMem)); clSetKernelArg(plotKernel, 13, Sizeof.cl_mem, Pointer.to(histogramMem)); // clSetKernelArg(plotKernel, 14, Sizeof.cl_mem, Pointer.to(hitcountsMem)); /// PreviewKernel // clSetKernelArg(previewKernel, 0, Sizeof.cl_float, 1.0f/quality); // clSetKernelArg(previewKernel, 1, Sizeof.cl_mem, Pointer.to(flameColorationMem)); // clSetKernelArg(previewKernel, 2, Sizeof.cl_mem, Pointer.to(flameBackgroundMem)); clSetKernelArg(previewKernel, 3, Sizeof.cl_mem, Pointer.to(histogramMem)); clSetKernelArg(previewKernel, 4, Sizeof.cl_mem, Pointer.to(imgRasterMem)); /// FinishKernel1 // clSetKernelArg(finishKernel1, 0, Sizeof.cl_float, 1.0f/quality); // clSetKernelArg(finishKernel1, 1, Sizeof.cl_mem, Pointer.to(flameColorationMem)); clSetKernelArg(finishKernel1, 2, Sizeof.cl_mem, Pointer.to(histogramMem)); clSetKernelArg(finishKernel1, 3, Sizeof.cl_mem, Pointer.to(preRasterMem)); /// FinishKernel2 // clSetKernelArg(finishKernel2, 0, Sizeof.cl_int, width); // clSetKernelArg(finishKernel2, 1, Sizeof.cl_int, height); // clSetKernelArg(finishKernel2, 2, Sizeof.cl_mem, Pointer.to(flameBlurParamsMem)); // clSetKernelArg(finishKernel2, 3, Sizeof.cl_mem, Pointer.to(flameBackgroundMem)); clSetKernelArg(finishKernel2, 4, Sizeof.cl_mem, Pointer.to(histogramMem)); clSetKernelArg(finishKernel2, 5, Sizeof.cl_mem, Pointer.to(preRasterMem)); clSetKernelArg(finishKernel2, 6, Sizeof.cl_mem, Pointer.to(imgRasterMem)); } clSetKernelArg(plotKernel, 9, Sizeof.cl_mem, Pointer.to(flameViewAffineMem)); clSetKernelArg(plotKernel, 14, Sizeof.cl_mem, Pointer.to(hitcountsMem)); clSetKernelArg(previewKernel, 1, Sizeof.cl_mem, Pointer.to(flameColorationMem)); clSetKernelArg(previewKernel, 2, Sizeof.cl_mem, Pointer.to(flameBackgroundMem)); clSetKernelArg(finishKernel1, 1, Sizeof.cl_mem, Pointer.to(flameColorationMem)); clSetKernelArg(finishKernel2, 2, Sizeof.cl_mem, Pointer.to(blurParamMem)); clSetKernelArg(finishKernel2, 3, Sizeof.cl_mem, Pointer.to(flameBackgroundMem)); } private void prepFlameBuffers() { // Calc the new capacity requirement int transformSize = flame.getNumTransforms(); int variationSize = Math.max(transformSize*flame.getNumVariations(), 1); int parameterSize = Math.max(transformSize*flame.getNumParameters(), 1); // Flame Data if (xformCapacity < transformSize) { // Store the new capacity xformCapacity = transformSize; // Release the mem objects if (xformWeightMem != null) { clReleaseMemObject(xformWeightMem); clReleaseMemObject(xformCmixesMem); clReleaseMemObject(xformColorsMem); clReleaseMemObject(xformAffineMem); } // Create new mem objects xformWeightMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, transformSize*Sizeof.cl_float, null, null); xformCmixesMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, transformSize*Sizeof.cl_float, null, null); xformColorsMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, transformSize*4*Sizeof.cl_float, null, null); xformAffineMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, transformSize*12*Sizeof.cl_float, null, null); // Set the kernel arguments clSetKernelArg(warmKernel, 1, Sizeof.cl_mem, Pointer.to(xformWeightMem)); clSetKernelArg(warmKernel, 2, Sizeof.cl_mem, Pointer.to(xformCmixesMem)); clSetKernelArg(warmKernel, 3, Sizeof.cl_mem, Pointer.to(xformColorsMem)); clSetKernelArg(warmKernel, 4, Sizeof.cl_mem, Pointer.to(xformAffineMem)); clSetKernelArg(plotKernel, 3, Sizeof.cl_mem, Pointer.to(xformWeightMem)); clSetKernelArg(plotKernel, 4, Sizeof.cl_mem, Pointer.to(xformCmixesMem)); clSetKernelArg(plotKernel, 5, Sizeof.cl_mem, Pointer.to(xformColorsMem)); clSetKernelArg(plotKernel, 6, Sizeof.cl_mem, Pointer.to(xformAffineMem)); } if (xformVariationsCapacity < variationSize) { // Store the new capacity xformVariationsCapacity = variationSize; // Release the mem objects if (xformVariationsMem != null) clReleaseMemObject(xformVariationsMem); // Create new mem objects xformVariationsMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, variationSize*Sizeof.cl_float, null, null); // Set the kernel arguments clSetKernelArg(warmKernel, 5, Sizeof.cl_mem, Pointer.to(xformVariationsMem)); clSetKernelArg(plotKernel, 7, Sizeof.cl_mem, Pointer.to(xformVariationsMem)); } if (xformParametersCapacity < parameterSize) { // Store the new capacity xformParametersCapacity = parameterSize; // Release the mem objects if (xformParametersMem != null) clReleaseMemObject(xformParametersMem); // Create new mem objects xformParametersMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, parameterSize*Sizeof.cl_float, null, null); // Set the kernel arguments clSetKernelArg(warmKernel, 6, Sizeof.cl_mem, Pointer.to(xformParametersMem)); clSetKernelArg(plotKernel, 8, Sizeof.cl_mem, Pointer.to(xformParametersMem)); } // Map the buffers ByteBuffer xformWeightBuffer = clEnqueueMapBuffer(queue, xformWeightMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, transformSize*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer xformCmixesBuffer = clEnqueueMapBuffer(queue, xformCmixesMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, transformSize*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer xformColorsBuffer = clEnqueueMapBuffer(queue, xformColorsMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, transformSize*4*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer xformAffineBuffer = clEnqueueMapBuffer(queue, xformAffineMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, transformSize*12*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer xformVariationsBuffer = clEnqueueMapBuffer(queue, xformVariationsMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, variationSize*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer xformParametersBuffer = clEnqueueMapBuffer(queue, xformParametersMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, parameterSize*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer flameViewAffineBuffer = clEnqueueMapBuffer(queue, flameViewAffineMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, 6*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer flameColorationBuffer = clEnqueueMapBuffer(queue, flameColorationMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, 3*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer flameBackgroundBuffer = clEnqueueMapBuffer(queue, flameBackgroundMem, CL_NON_BLOCKING, CL_MAP_WRITE, 0, 4*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); clFinish(queue); // Write to the buffers flame.fillBuffers(settings.getWidth(), settings.getHeight(), xformWeightBuffer.asFloatBuffer(), xformCmixesBuffer.asFloatBuffer(), xformColorsBuffer.asFloatBuffer(), xformAffineBuffer.asFloatBuffer(), xformVariationsBuffer.asFloatBuffer(), xformParametersBuffer.asFloatBuffer(), flameViewAffineBuffer.asFloatBuffer(), flameColorationBuffer.asFloatBuffer(), flameBackgroundBuffer.asFloatBuffer()); /* DEBUG printOut("xformWeightBuffer", 1, xformWeightBuffer.asFloatBuffer()); printOut("xformCmixesBuffer", 1, xformCmixesBuffer.asFloatBuffer()); printOut("xformColorsBuffer", 4, xformColorsBuffer.asFloatBuffer()); printOut("xformAffineBuffer", 2, xformAffineBuffer.asFloatBuffer()); printOut("xformVariationsBuffer", 1, xformVariationsBuffer.asFloatBuffer()); printOut("xformParametersBuffer", 1, xformParametersBuffer.asFloatBuffer()); printOut("aft: flameViewAffineBuffer", 2, flameViewAffineBuffer.asFloatBuffer()); printOut("flameColorationBuffer", 2, flameColorationBuffer.asFloatBuffer()); printOut("flameBackgroundBuffer", 2, flameBackgroundBuffer.asFloatBuffer()); */ // Unmap the buffers clEnqueueUnmapMemObject(queue, xformWeightMem, xformWeightBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, xformCmixesMem, xformCmixesBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, xformColorsMem, xformColorsBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, xformAffineMem, xformAffineBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, xformVariationsMem, xformVariationsBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, xformParametersMem, xformParametersBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, flameViewAffineMem, flameViewAffineBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, flameColorationMem, flameColorationBuffer, 0, null, null); clEnqueueUnmapMemObject(queue, flameBackgroundMem, flameBackgroundBuffer, 0, null, null); } /* DEBUG private static void printOut(String name, int size, FloatBuffer buffer) { buffer.rewind(); System.out.print(name+": "); for (int i=0; i<buffer.limit()/size; ) { System.out.print("("); for (int j=0; j<size; j++, i++) { System.out.print(Float.toString(buffer.get())); System.out.print(", "); } System.out.print(") "); } System.out.println(); } private static void printCSV(String label, int size, FloatBuffer buffer) { try (FileWriter out = new FileWriter(new File(label+".csv"))) { buffer.rewind(); for (int i=0; i<buffer.limit(); ) { for (int j=0; j<size; j++, i++) { out.write(Float.toString(buffer.get())); out.write(","); } out.write("\n"); } } catch (Exception ex) { ex.printStackTrace(System.err); } } */ private void prepIterBuffers() { // If the mem objects are not large enough if (workCapacity < workSize) { // Store the new capacity workCapacity = workSize; // Release the mem objects if (iterRStateMem != null) { clReleaseMemObject(iterRStateMem); clReleaseMemObject(iterPointsMem); clReleaseMemObject(iterColorsMem); } // Create new mem objects iterRStateMem = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, workCapacity*2*Sizeof.cl_uint, null, null); iterPointsMem = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, workCapacity*2*Sizeof.cl_float, null, null); iterColorsMem = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, workCapacity*4*Sizeof.cl_float, null, null); // Set the kernel arguments clSetKernelArg(initKernel, 0, Sizeof.cl_mem, Pointer.to(iterRStateMem)); clSetKernelArg(initKernel, 1, Sizeof.cl_mem, Pointer.to(iterPointsMem)); clSetKernelArg(initKernel, 2, Sizeof.cl_mem, Pointer.to(iterColorsMem)); clSetKernelArg(warmKernel, 7, Sizeof.cl_mem, Pointer.to(iterRStateMem)); clSetKernelArg(warmKernel, 8, Sizeof.cl_mem, Pointer.to(iterPointsMem)); clSetKernelArg(warmKernel, 9, Sizeof.cl_mem, Pointer.to(iterColorsMem)); clSetKernelArg(plotKernel, 10, Sizeof.cl_mem, Pointer.to(iterRStateMem)); clSetKernelArg(plotKernel, 11, Sizeof.cl_mem, Pointer.to(iterPointsMem)); clSetKernelArg(plotKernel, 12, Sizeof.cl_mem, Pointer.to(iterColorsMem)); // Fill the RNG state buffer with random numbers Random random = new Random(); ByteBuffer iterRStateBuffer = clEnqueueMapBuffer(queue, iterRStateMem, CL_BLOCKING, CL_MAP_WRITE, 0, workCapacity*2*Sizeof.cl_uint, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); for (int i=0; i<workCapacity*2; i++) iterRStateBuffer.putInt(random.nextInt()); clEnqueueUnmapMemObject(queue, iterRStateMem, iterRStateBuffer, 0, null, null); } } private void prepImageBuffers() { int width = settings.getWidth(); int height = settings.getHeight(); // Calc the new capacity requirement int imageSize = width*height; // If the mem objects are not large enough if (imageCapacity < imageSize) { // Store the new capacity imageCapacity = imageSize; // Release the mem objects if (histogramMem != null) { clReleaseMemObject(histogramMem); clReleaseMemObject(imgRasterMem); } // Create new mem objects histogramMem = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, imageCapacity*4*Sizeof.cl_float, null, null); preRasterMem = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, imageCapacity*4*Sizeof.cl_float, null, null); imgRasterMem = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, imageCapacity*Sizeof.cl_int, null, null); // Set the kernel arguments clSetKernelArg(plotKernel, 13, Sizeof.cl_mem, Pointer.to(histogramMem)); clSetKernelArg(previewKernel, 3, Sizeof.cl_mem, Pointer.to(histogramMem)); clSetKernelArg(previewKernel, 4, Sizeof.cl_mem, Pointer.to(imgRasterMem)); clSetKernelArg(finishKernel1, 2, Sizeof.cl_mem, Pointer.to(histogramMem)); clSetKernelArg(finishKernel1, 3, Sizeof.cl_mem, Pointer.to(preRasterMem)); clSetKernelArg(finishKernel2, 4, Sizeof.cl_mem, Pointer.to(histogramMem)); clSetKernelArg(finishKernel2, 5, Sizeof.cl_mem, Pointer.to(preRasterMem)); clSetKernelArg(finishKernel2, 6, Sizeof.cl_mem, Pointer.to(imgRasterMem)); } // Zero the histogram ByteBuffer histogramBuffer = clEnqueueMapBuffer(queue, histogramMem, CL_BLOCKING, CL_MAP_WRITE, 0, imageSize*4*Sizeof.cl_float, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); for (int i=0; i<imageSize*4; i++) histogramBuffer.putInt(0); clEnqueueUnmapMemObject(queue, histogramMem, histogramBuffer, 0, null, null); } private void prepHitCountsBuffer() { // Zero the hit counts buffer ByteBuffer buffer = clEnqueueMapBuffer(queue, hitcountsMem, CL_BLOCKING, CL_MAP_WRITE, 0, 2*Sizeof.cl_int, 0, null, null, null).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(0); buffer.putInt(0); buffer.rewind(); clEnqueueUnmapMemObject(queue, hitcountsMem, buffer, 0, null, null); } private void updateImage(double quality, double points, long startTime, boolean isFinished) { int width = settings.getWidth(); int height = settings.getHeight(); // Set the scaleConstant arg float[] scaleConstant = new float[] { (float)(1/quality) }; if (!isFinished || !settings.getUseBlur()) { // Set the argument clSetKernelArg(previewKernel, 0, Sizeof.cl_float, Pointer.to(scaleConstant)); // Run the coloration kernel clEnqueueNDRangeKernel(queue, previewKernel, 1, workOffset, workSizeColor, null, 0, null, null); } else { // Set the argument for the first kernel clSetKernelArg(finishKernel1, 0, Sizeof.cl_float, Pointer.to(scaleConstant)); // Run the first kernel clEnqueueNDRangeKernel(queue, finishKernel1, 1, workOffset, workSizeColor, null, 0, null, null); // Run the second kernel clEnqueueNDRangeKernel(queue, finishKernel2, 1, workOffset, workSizeColor, null, 0, null, null); } // Ensure the back image is the right size if (backImage == null || backImage.getWidth()!=width || backImage.getHeight()!=height) backImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // Get the int array backing the bufferd image int[] data = ((DataBufferInt)backImage.getRaster().getDataBuffer()).getData(); // Read the data directly into the buffered image's array clEnqueueReadBuffer(queue, imgRasterMem, CL_BLOCKING, 0, width*height*Sizeof.cl_int, Pointer.to(data), 0, null, null); // Swap the front and back images BufferedImage swapImage = frontImage; frontImage = backImage; backImage = swapImage; // Determine the elapsed time (since work began on this image) double elapTime = (System.nanoTime()-startTime)*1e-9; // Alert the image listeners update(task, flame, frontImage, quality, points, elapTime, isFinished); } private static cl_platform_id[] getAllPlatforms() { int numPlatforms[] = new int[1]; clGetPlatformIDs(0, null, numPlatforms); cl_platform_id platforms[] = new cl_platform_id[numPlatforms[0]]; clGetPlatformIDs(platforms.length, platforms, null); return platforms; } private static cl_device_id[] getAllDevices(cl_platform_id platform) { int numDevices[] = new int[1]; clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 0, null, numDevices); cl_device_id devices[] = new cl_device_id[numDevices[0]]; clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, numDevices[0], devices, null); return devices; } private static String getPlatformString(cl_platform_id platform, int paramName) { long size[] = new long[1]; clGetPlatformInfo(platform, paramName, 0, null, size); byte buffer[] = new byte[(int)size[0]]; clGetPlatformInfo(platform, paramName, buffer.length, Pointer.to(buffer), null); return new String(buffer, 0, buffer.length-1); } private static String getDeviceString(cl_device_id device, int paramName) { long size[] = new long[1]; clGetDeviceInfo(device, paramName, 0, null, size); byte buffer[] = new byte[(int)size[0]]; clGetDeviceInfo(device, paramName, buffer.length, Pointer.to(buffer), null); return new String(buffer, 0, buffer.length-1); } private static int getDeviceInt(cl_device_id device, int paramName) { int buffer[] = new int[1]; clGetDeviceInfo(device, paramName, Sizeof.cl_int, Pointer.to(buffer), null); return buffer[0]; } private static long getDeviceLong(cl_device_id device, int paramName) { long buffer[] = new long[1]; clGetDeviceInfo(device, paramName, Sizeof.cl_long, Pointer.to(buffer), null); return buffer[0]; } public static enum DeviceType { ALL(CL_DEVICE_TYPE_ALL), CPU(CL_DEVICE_TYPE_CPU), GPU(CL_DEVICE_TYPE_GPU), DEFAULT(CL_DEVICE_TYPE_DEFAULT), ACCELERATOR(CL_DEVICE_TYPE_ACCELERATOR); final long type; DeviceType(long type) { this.type = type; } } }